jueves, 4 de abril de 2013

Android: Init with Android on Linux Ubuntu

Init to develop with Android on Ubuntu
How to init a development with Android on Linux Ubuntu?

1) Download:
Search in: http://www.android.com/ 
Open: http://developer.android.com/sdk/index.html
Download: adt-bundle-linux-x86-20130219.zip

2) Install:
Unzip on Home folder.
Home->adt-bundle-linux-x86-20130219

3) First project.
Run Eclipse... Home->adt-bundle-linux-x86-20130219->eclipse
Help->About ADT

New->Android Application Project
Run As->Android Application
Select... Yes
Select... "Launch a New Android Virtual Device"; Select Manager; Select New; Select... Device: Nexus S (4.0,480x800:dhpi)
Select... Target: Android 4.2.2 - API Level 17
Click... Start.



Select... Run Configuration -> Select... Target -> "Always prompt to pick device".

Referencias:

sábado, 23 de marzo de 2013

Como instalar Linux desde un Pendrive Memory Stick


1) Bajamos la imagen ISO de alguna distribución de Linux:

Ubuntu (12.04 o 12.10)
Linux Mint 13 "Maya" - MATE (32-bit)
Linux Mint 13 "Maya" - MATE (64-bit)

2) Crear un  "USB flash drive" (Pendrive Memory Stick) bootable que contenga el instalador de Linux (Ubuntu):

2) a) Insertamos el "USB flash drive" (se deberia auto-montar) en una compu anfitrion.

2) b) 1) Desde Linux Ubuntu: Se puede usar el software usb-creator-gtk o usb-creator-kde que se supone esta en Sistema-->Administracion o K-Menu-->Applications-->System-->Startup Disk Creator (Kubuntu). Si no esta se puede instalar con "Synaptic Package Manager" or "Ubuntu Software Center".
Si esta instalado tipeamos en linea de comandos:
usb-creator-gtk

Seleccionar la Imagen ISO, seleccionar la unidad "USB flash drive", elegir "Erase" o "Format" y elegir "Make Startup Disk".

2) b) 2) Desde Windows:
Bajar y usar "Linux Live Usb Creator" (usb-creator.exe) o Unetbootin to create a bootable USB flash drive. http://unetbootin.sourceforge.net/.

3) Instalar desde "USB flash drive". Conectamos el "USB flash drive" en la compu donde se desea instalar el sistema operativo. Iniciamos la máquina, entramos a la configuración de arranque y configuramos para que arranque desde el "USB flash drive". Re-arrancamos la máquina y deberia bootear el Pen y comenzar la Instalación del sistema Linux.


References:
https://help.ubuntu.com/community/Installation/FromUSBStick
GUIA: Ubuntu 12.04 LTS (Precise Pangolin)
GUIA: Ubuntu 12.10 (Quantal Quetzal)


miércoles, 6 de febrero de 2013

Perl: Exception Handling In Perl

Manejo de Excepciones en Perl 5


En Perl 5 se suele usar excepciones mediante "la vieja escuela" (la forma tradicional o nativa), pero también se puede usar el estilo try-catch (estilo Java) usando la librería Try::Tiny.

1) Manejo de excepciones con la vieja escuela.

#This is perl 5, version 14, subversion 2 (v5.14.2)
#!/usr/bin/perl
#Example 1: Exception Handling In Perl

#How to Handle Exception In Perl?
#perl 5, version 14, subversion 2 (v5.14.2)

use Scalar::Util qw(blessed);

# Start main
local $@; #exception


eval { #=try
     print "Doing... \n";
     die MyException->new( msg => "mensaje" )  # throw exception
};
$exception=$@;
if ($exception) { #=catch
      if (blessed($exception) && $exception->isa("MyException")) {
          print "Handle specific exception  \n";
          print $exception->get_msg;
      }
      else {         
          print "Handle all other possible exceptions \n";
      }
}

print "end \n";
# End main

# Start The exception class
package MyException;
  sub new
  {
      my $class = shift;
      bless { msg=>"@_" }, $class;
  }
  sub get_msg
  {
      my ($self) = @_;
      return sprintf "Exception: %s\n", $self->{msg};
  }
1;
# End The exception class



2) Manejo de excepciones con Try::Tiny.

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: script_test_exception.pl
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny; #Módulo para excepciones try catch

try {
        #Bloque de código
die 'foo'; #lanza exception
} catch {
my $exception = $_;  #captura exception
warn "Message: $exception";
} finally {
print "Doing finally...";
};

=pod
Imprime en pantalla:
Message: foo at C:\Users\usuario\Documents\dario\Perl\script_NameStr.pl line 9.
Doing finally...
=cut



References:
-Exception Handling In Perl.
-Blog: Exceptions in Perl 5.
-Exceptions with (Try-Catch) Try::Tiny.




miércoles, 30 de enero de 2013

Perl: How to take time to benchmark or profiling


#!/usr/bin/perl
#How to benchmark your Perl code?
#Example of how to take time for benchmark or profiling in Perl.
#Calcular el tiempo transcurrido entre lineas de codigo.

use strict;
use warnings;

########### EXAMPLE 1 ###########
#sample works for second intervals
my $start_ = time;
sleep rand(17)/3;  #Job: or some other crazy pieces of code
my $end_ = time;
my $length = $end_ - $start_;
print "It took us $length seconds.\n";
#Out: It took us 3 seconds.

########### EXAMPLE 2 ###########
#Using Time::HiRes
#How can I get the time in milliseconds in Perl using Time::HiRes
use Time::HiRes qw/ time sleep gettimeofday tv_interval /;
my $start = time; #Returns a floating seconds since the epoch.
my $s1; #seconds since the epoch
my $usec1;  #microsegundos
my $s2; #seconds since the epoch
my $usec2; #microsegundos
($s1, $usec1) = gettimeofday; # get seconds and microseconds since the epoch
sleep rand(17)/3; #Job: or some other crazy pieces of code
my $end   = time; #Returns a floating seconds since the epoch.
# get seconds and microseconds since the epoch
($s2, $usec2) = gettimeofday; # get seconds and microseconds since the epoch
print 'Slept for ', ( $s2 - $s1 ) , " seconds \n";
print 'Slept for ', ( $usec2 - $usec1 ) , " micro-seconds \n";
print 'Slept for ', ( $end - $start ) , " floating seconds since the epoch \n";
print 'Slept for ', tv_interval ( [$s1, $usec1], [$s2, $usec2]), " floating seconds \n";
#Out: Slept for 1 seconds
#Out: Slept for -360540 micro-seconds
#Out: Slept for 0.639461040496826 floating seconds since the epoch
#Out: Slept for 0.63946 floating seconds

########### EXAMPLE 3 ###########
#Using Benchmark
use Benchmark;
my $t0 = new Benchmark;
sleep rand(17)/3; #Job: or some other crazy pieces of code
my $t1 = new Benchmark;
my $td = timestr(timediff($t1, $t0));
print "It took us : " . $td . "\n";
#Out: It took us :   2 wallclock secs ( 0.01 usr +  0.00 sys =  0.01 CPU)

########### EXAMPLE 4 ###########
#Using Benchmark::Timer
#Install it on ubuntu with: apt-get install libbenchmark-timer-perl
#Example of Benchmarking with statistical confidence.
use Benchmark::Timer;
my $t = Benchmark::Timer->new(skip => 0);
for(1 .. 4) {
        $t->start('test_01');
        sleep rand(17)/3; #Job: or some other crazy pieces of code
        $t->stop('test_01');
}
print $t->report;
#Out: 4 trials of test_01 (10.204s total), 2.551s/trial


########### EXAMPLE 5 ###########
# Para comparar la prestancia entre dos métodos.
# Este es un script aparte:
#!/usr/bin/perl -w

use strict;
use warnings;
use Time::HiRes qw(time);
use Benchmark qw(:all) ;

my $msg = "mensaje";

#Start test

cmpthese($times, {
    'method 1' => sub { function_1( 100 ) },
    'method 2' => sub { function_2( 100 ) },
});

#End test

sub function_1 {
   my $iterations = shift;
   for (my $i = $iterations; $i >= 1; $i--) {       
    #Hace algo 1
    print "Mensaje: $msg";
   }
}

sub function_2 {
   my $iterations = shift;
   for (my $i = $iterations; $i >= 1; $i--) {       
    #Hace algo 2
    print "Mensaje: $msg";
   }
}


Reference:
- http://perldoc.perl.org/Time/HiRes.html
- http://perldoc.perl.org/Benchmark.html
- http://search.cpan.org/~dcoppit/Benchmark-Timer-0.7102/lib/Benchmark/Timer.pm


viernes, 18 de enero de 2013

Perl Thread and concurrence 1


1) Example of Perl Thread and concurrence:

#!/usr/bin/perl -w
# This is perl 5, version 14

# File name: thread_example_01.pl

use strict;
use Thread qw(:DEFAULT async yield);

my %hash = ( t3 => '', t2 => '', t1 => '', );

for my $key ( keys %hash ) {
        $hash{$key} = Thread->new(\&doSomething, $key)->yield;       
    }

sleep(15);
print "Thread->list = " . Thread->list . "\n";

#Function concurrent
sub doSomething {
    my $thread = shift;
    print "thread $thread - start tid = " . Thread->self->tid . "\n";
    sleep(3);
    print "thread $thread - end tid = " . Thread->self->tid . "\n";
    #yield();
}


Console out:

$ perl thread_example_01.pl
thread t3 - start tid = 1
thread t2 - start tid = 2
thread t1 - start tid = 3
thread t3 - end tid = 1
thread t2 - end tid = 2
thread t1 - end tid = 3
Thread->list = 3
Perl exited with active threads:
    0 running and unjoined
    3 finished and unjoined
    0 running and detached



References:

viernes, 4 de enero de 2013

Perl: Mojolicious y Perl


Mojolicius es un framework que pretende facilitar la programación de aplicaciones web por medio de Perl. Utiliza el patrón MVC y soporta CGI, FastCGI y PSGI. De serie tiene soporte para rutas RESTful, extensiones, sesiones, cookies firmadas, servidor de ficheros estáticos, test unitarios, plantillas, JSON, I18N y Unicode. Entre las características más importantes de este framework están:
    Framework que implementa la estructura MVC apoyado a través de Mojolicious:Lite
    Crea una estructura de objetos muy limpia y que no requiere de nada especial, solo de la versión 5.8.1 de Perl.
    Implementación de websocket cliente/servidor con Ipv6, TLS, IDNA, pipelining, chunking y soporte multipartes.
    Soporte para CGI, FastCGI y PSGI.
    Código fresco basado en años de experiencia.
    Completa rutas con RESTful, plugins, sesiones, cookies firmadas, servidor de ficheros estáticos, framework de test, plantillas perl-ish, soporte para JSON, I18N y muchas más cosas.

Instalar Mojolicious on ubuntu linux


#1) Form one:
sudo apt-get install curl
curl get.mojolicio.us | sh
sudo apt-get install libmojolicious-perl

#2) Form two:
cpan Mojolicious
sudo apt-get install libmojolicious-perl

para desinstalar:
sudo apt-get remove libmojolicious-perl
sudo apt-get purge libmojolicious-perl
sudo apt-get clean libmojolicious-perl


#3) Install from CPAN:
perl -MCPAN -e shell
Terminal does not support AddHistory.

cpan shell -- CPAN exploration and modules installation (v1.960001)
Enter 'h' for help.

cpan[1]> install Mojolicious
...
...
  Database was generated on Fri, 19 Apr 2013 06:07:13 GMT
Mojolicious is up to date (3.95).

Testing

#Crear un archivo first_test.pl

use Mojolicious::Lite;
get '/' => {text => 'Hello World!'};
app->start;

#Ejecutar
morbo first_test.pl

Generate application

cd /home/user/
mojo generate app MyappAPI

/home/user/myapp_api$ ls
lib  log  public  script  t  templates

script/myapp_api daemon
Server available at http://127.0.0.1:3000.

Put in browser:
http://127.0.0.1:3000
...and will be shown:
Welcome to the Mojolicious real-time web framework!

Install Rest Client:

Install RESTClient, a debugger for RESTful web services to Mozilla:
https://addons.mozilla.org/es/firefox/addon/restclient/



Referencias:

Mojolicious web site.
Introduction to Mojolicious-Perl.





viernes, 28 de diciembre de 2012

Audio USB por Interface de Entrada en Ubuntu 12

¿Cómo usar un dispositivo externo de Audio USB para Interface de Entrada de audio en Ubuntu 12?

Un dispositivo externo de Audio USB puede servir para conectar instrumentos musicales, micrófonos o equipos de audio a una computadora por medio de un puerto USB.

Si tenemos una interface de grabación para puerto USB solo tenemos que ver si esta soportada por linux y la distribusión de Ubuntu:
http://wiki.linuxaudio.org/wiki/current_audio_gear


En mi caso es una Alesis iO2 Express:
[Alesis] - iO4 (usb - class compliant (1.1 or 2.0?))
WORKS completely: Tested under Ubuntu 9.04 on an eeePC using ALSA, Jack and Ardour. Also on Linux Mint KDE 12 with KXStudio.

Conectamos el dispositivo.

Los comando útiles para ver información de los dispositivos de audio son los siguientes:

#terminal# sudo cat /proc/asound/cards
 0 [Intel          ]: HDA-Intel - HDA Intel
                      HDA Intel at 0xf2620000 irq 45
 1 [io2            ]: USB-Audio - io|2
                      Alesis io|2 at usb-0000:00:1a.0-1.2, full speed
29 [ThinkPadEC     ]: ThinkPad EC - ThinkPad Console Audio Control
                      ThinkPad Console Audio Control at EC reg 0x30, fw 6IHT38WW-1.13

#terminal# lsusb
...
Bus 001 Device 007: ID 13b2:0008 Alesis

#terminal# aplay -l
**** List of PLAYBACK Hardware Devices ****
...
card 1: io2 [io|2], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

Conviene tener instalado algunas librerias e instalar gnome-alsamixer para control grafico de volúmenes:

#terminal# sudo apt-get install alsaplayer-jack libjack0 libavc1394-0 libiec61883-0
#terminal# sudo apt-get install gnome-alsamixer
#terminal# sudo apt-get install libfreebob0

Podemos lanzar cualquiera de los controladores gráficos:
#terminal# gnome-alsamixer
#terminal# alsamixer


Deberíamos instalar "Ardour" o "Audacity" software para captura y edición de audio.

Audacity: En audacity elegimos "Edit > Preferences" , luego "Recording" y allí elegimos el dispositivo USB externo (en mi caso alesis*).

Y listo, ya se puede grabar.