lunes, 2 de septiembre de 2013

OpenERP: Install version 6.1 on ubuntu for development

Install OpenERP 6.1 on ubuntu for development

¿How to install OpenERP 6.1? ... Guide:

 I) Dependences

 
# Install postgres (database)
#----------------------------------------------------------------------

sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
psql --version

sudo su postgres -c psql
ALTER USER postgres WITH PASSWORD 'postgresdemo';

sudo passwd -d postgres
sudo su postgres -c passwd

sudo su - postgres
createuser --createdb --username postgres --no-createrole --no-superuser --pwprompt openerp
exit



# Install python (base language)
#----------------------------------------------------------------------

sudo apt-get install python python-psycopg2 python-reportlab \
python-egenix-mxdatetime python-tz python-pychart python-mako \
python-pydot python-lxml python-vobject python-yaml python-dateutil \
python-pychart python-webdav

sudo apt-get install python-cherrypy3 python-formencode python-pybabel \
python-simplejson python-pyparsing

sudo apt-get install python-gtk2 python-glade2 \
    python-matplotlib python-egenix-mxdatetime python-hippocanvas

#sudo apt-get install python-xml 
 

II) OpenERP

# Install OPENERP (Application)
#----------------------------------------------------------------------
 
To see more in: http://trescloud.blogspot.com.ar/2012/11/instalacion-de-openerp-6.html
 
The recommended installation is copy all in a folder named /opt/openerp
 
#Create structure folder, user and permission
sudo adduser --system --home=/opt/openerp --group openerp
cd /opt/openerp
sudo mkdir /opt/openerp/download
sudo chmod 755 /opt/openerp/download
sudo chown openerp: /opt/openerp/download
sudo mkdir server
sudo chmod 755 /opt/openerp/server
sudo chown openerp: /opt/openerp/server
sudo mkdir web
sudo chmod 755 /opt/openerp/web
sudo chown openerp: /opt/openerp/web
sudo mkdir client
sudo chmod 755 /opt/openerp/client
sudo chown openerp: /opt/openerp/client
sudo mkdir /var/log/openerp
sudo chown openerp:root /var/log/openerp
 
#Download OpenERP server:
sudo -su openerp 
cd /opt/openerp/download 
wget http://nightly.openerp.com/6.1/releases/openerp-6.1-1.tar.gz
sudo tar -zxvf openerp-6.1-1.tar.gz
sudo mv openerp-6.1-1/* /opt/openerp/server
sudo rm -R openerp-6.1-1
cd /opt/openerp/
sudo chown -R openerp: *
 
wget http://nightly.openerp.com/6.1/releases/openerp-client-6.1-1.tar.gz
sudo tar -zxvf openerp-client-6.1-1.tar.gz
sudo mv openerp-6.1-1/* /opt/openerp/client
sudo rm -R openerp-client-6.1-1 /opt/openerp/
sudo chown -R openerp: *
cd /opt/openerp/
sudo chown -R openerp: *
 
 
 
#Configuration OpenERP server:
sudo cp /opt/openerp/server/doc/openerp-server.conf /etc/openerp-server.conf
sudo chown openerp:root /etc/openerp-server.conf
sudo chmod 640 /etc/openerp-server.conf
sudo cp /opt/openerp/server/openerp-server /etc/init.d/openerp-server
sudo chmod 755 /etc/init.d/openerp-server
sudo chown root: /etc/init.d/openerp-server
sudo cp /opt/openerp/web/doc/openerp-web.cfg /etc/openerp-web.conf
sudo chown openerp:root /etc/openerp-web.conf
sudo chmod 640 /etc/openerp-web.conf
sudo cp /opt/openerp/web/scripts/openerp-web /etc/init.d/openerp-web
sudo chmod 755 /etc/init.d/openerp-web
sudo chown root: /etc/init.d/openerp-web
 
# Launch applications
#----------------------------------------------------------------------

sudo /etc/init.d/postgresql restart
sudo /etc/init.d/openerp-server start
less /var/log/openerp/openerp-server.log

#sudo python /opt/openerp/server/bin/openerp-server.py -r openerp -w postgresdemo --db_host 127.0.0.1
#/opt/openerp/server/bin/openerp-server.py --config=/etc/openerp-server.conf

# See if OpenERP is running
#----------------------------------------------------------------------
ps aux | grep openerp
 

III) Development

# Install Eclipse (Java + IDE)
#----------------------------------------------------------------------
 
# Install Java
 
# If we install Oracle Java 7:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
 
# If we install sun-java6-jdk on ubuntu 12.04 
#
sudo add-apt-repository ppa:flexiondotorg/java
sudo apt-get update
sudo apt-get install sun-java6-jdk sun-java6-plugin 
 
# Select java to use between installed alternatives
sudo update-alternatives --config java


# View version:
~$ java -version
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) Server VM (build 20.5-b03, mixed mode)
 
 
# Install Eclipse (see more...)
Download Eclipse from http://www.eclipse.org/downloads/packages/eclipse-classic-421/junosr1
or http://www.eclipse.org/downloads/ 
 
# Install Plugins
 Install plugins following:
  • JavaScript Development Tools
  • XML Editors and Tools
  • Eclipse Web Developer Tools
  • PyDev for Eclipse
 For install go: Help->Install new software...
 
 
 
Referencias:
https://doc.openerp.com/v6.1/developer/index.html/#book-develop-link
http://www.slideshare.net/openobject/openerp-61-web-framework-tutorial
http://informaticartica.blogspot.com.ar/2012/02/crear-entorno-de-openerp-61.html
http://openerpdev.wordpress.com/2012/01/31/minimal-openerp-module-example/
http://planet.agilebg.com/en/2012/04/how-to-create-an-openerp-module-the-easy-way/
http://www.slideshare.net/openobject/openerp-61-web-framework-tutorial
http://trescloud.blogspot.com.ar/2013/02/configurar-eclipse-4.html

martes, 27 de agosto de 2013

Perl: Paso de parámetros por referencia

Paso de parámetros por referencia en Perl

Cuando invocamos una subrutina y le pasamos parámetros en realidad le estamos pasando una lista de datos, que se llama @_ . Cuando pasamos vectores (matrices, arreglos o arrays ) o tablas asociativas ( hashes ) como parámetros, en realidad los estamos introduciendo, elemento por elemento, en @_ . La forma más económica de pasar parámetros a subrutinas es pasarlos por referencia. De esta manera no pasamos los datos en sí, si no la dirección que ocupan en memoria. Así no es necesario enumerar y copiar todos los datos a @_, y evitar los problemas de pasar varios hashes o arreglos, y la subrutina que reciba las referencias puede acceder a los datos en su organización original, ya sean escalares, vectores o tablas asociativas, las tres clases de variables en Perl. Por otro lado el paso por referencia permite modificar de forma permanente, no local, los datos pasados como argumento.

1) Ejemplo de paso por referencia

#
# Ejemplo de paso de parámetros por referencia en Perl:
# ¿Como pasar parámetros por referencia y modificar los valores?
# How to pass parameters by reference in perl, modify the values​​?
#This is perl 5, version 14, subversion 2 (v5.14.2)
#!/usr/bin/perl

#use strict;
#use warnings;

my $param = "algo";
my @vector1 = (1,2,3);
function_with_params(\$param, \@vector1);
print "\n";
print $param;
print "\n";
print $vector1[0];
print "\n";

sub function_with_params{
    my ($arg1, $arg2) = @_;
    ${$arg1} = "changed...";
    @{$arg2}[0]=33;    #vector1
    return;
    }

2) Ejemplo de paso por referencia de un array.

#!/usr/bin/perl
use strict;
use warnings;

print "Ejemplo perl de paso por referencia de un array... \n";

my @airlines_travel = ("a","b","b","c","k");
my $arrayRef = \@airlines_travel; #referencia al array
my $string = "b";

print "Count: " . howManyTimesIsString($string, $arrayRef) . "\n";

# Cuenta cuantas veces esta un string en un array
sub howManyTimesIsString {
 my ($string, $arrayRef) = @_;
 my $count = 0;
 foreach my $item (@{$arrayRef}) {
   if ($string eq $item) {
      $count++;
   }
 }
 return $count;
}

3) POO y paso por referencia.


En perl todos los objetos son una referencia. Es decir, cuando tenes un $obj es una variable scalar que simplemente mantiene la referencia al objeto. Cuando pasamos un objeto como parámetro lo que estamos pasando es su referencia (no es necesario hacer nada extraño para explicitar esto).

También se puede explicitar usando \variableObject y $$variableObject pero no es recomendable usarlo de esta manera. A continuación un ejemplo de esta forma:

#This is perl 5, version 14, subversion 2 (v5.14.2)
#...

sub metodo1{
  my ($self) = @_;

  my $obj = Example->new();
  my $o = $self->metodo2(\$obj);
  print $o->getName();
  return;
}

sub metodo2{
  my ($self, $obj) = @_;
#...
  print $$obj->encodeHTMLtoUTF8($str);
  $$obj->setName("modificado");
  return $$obj;
}



Referencias:
-Paso de parámetros por valor y por referencia (Perl).
-Blog: Parametros por referencia en perl.




lunes, 29 de abril de 2013

Perl: Read a Table from database using DBI

¿How to read a Table from database using DBI? 

#!/usr/bin/perl -w

use strict;
use warnings;
use DBI;

use constant DATABASE => "mydatabase";
use constant HOSTNAME => "myhostname";
use constant USERNAME => "user";
use constant PASSWORD => "123";

my $dbh = db_connect();

print "\nRead MyTable table : \n";

my $rows = read_table($dbh);
my $affected_rows = print_table($dbh, $rows);
print "Affected rows: $affected_rows: \n";

#
sub read_table {
    my $dbh = shift;

    my $sql1 = qq(
        SELECT * FROM MyTable

    );
    my $sth1 = $dbh->prepare_cached( $sql1 );
    $sth1->execute();
    my $sql_return = $sth1->fetchall_arrayref( {} );
       
    return $sql_return;
}

#
sub print_table {
    my $dbh = shift;
    my $rows = shift;

    foreach my $row (@$rows) {       
          print "$row->{
columnName_01}\n";
          print "$row->{columnName_02}\n";  
        }

  my $arraySize = scalar (@$rows);
  return $arraySize;
   
}
   
sub db_connect {
   
    my $db   = DATABASE;
    my $host = HOSTNAME;
    my $user = USERNAME;
    my $pass = PASSWORD;

    my $dbh = DBI->connect(
        join(':', 'dbi:mysql', $db, $host), $user, $pass,
        { AutoCommit => 1, PrintError => 1, RaiseError => 1 },
    );

    return $dbh;
}

viernes, 26 de abril de 2013

Perl: Modules installing on Ubuntu system

¿What Perl Modules Already Installed On My System?
¿Qué módulos tengo instalado en el sistema?

How to list installed perl module? List installed perl module:

$ instmodsh

Available commands are:
   l            - List all installed modules
   m <module>   - Select a module
   q            - Quit the program
cmd? l
Installed modules are:
   Class::Load
   Data::OptList
   Dist::CheckConflicts
   ExtUtils::MakeMaker
   List::MoreUtils
   MRO::Compat
   Module::Implementation
   Module::Runtime
   Mojolicious
   Package::DeprecationManager
   Package::Stash
   Package::Stash::XS
   Params::Util
   Perl
   Perl::Metrics::Simple
   String::Util
   Sub::Exporter
   Sub::Install
   Sub::Uplevel
   Test::Deep
   Test::Exception
   Test::Fatal
   Test::NoWarnings
   Test::Requires
   Test::Tester
   Try::Tiny
   local::lib


Other way:
 
perl -e 'while (<@INC>) { while (<$_/*.pm>) { print "$_\n"; } }'
 
Show all perl paths:
 
perl -E 'say join "\n", @INC'
 
Find a file: 
sudo find / -type f -name 'Example.pm'
 
 
¿What Know if a Perl Modules Already Installed On My System?

perl -MNameModule -e 1
If not installed throw error "Can' locate module....."

For example: 
perl -MException::Base -e 1
perl -MLog::Log4perl -e 1

Install using CPAN:


For example:

sudo perl -MCPAN -e 'install IO::EventMux'
sudo perl -MCPAN -e 'install Log::Log4perl'
sudo perl -MCPAN -e 'install Test::Class'
sudo perl -MCPAN -e 'install Log::Dispatch'
sudo perl -MCPAN -e 'install Params::Validate'
sudo perl -MCPAN -e 'install DBD::mysql'
sudo perl -MCPAN -e 'install JSON::XS'
sudo perl -MCPAN -e 'install Cache::Memcached'  

sudo perl -MCPAN -e 'install Thread'    
sudo perl -MCPAN -e 'install Thread::Pool'

sudo perl -MCPAN -e 'install Exception::Base'
sudo perl -MCPAN -e 'install XML::LibXML' 

Install using System:

For example:

sudo apt-get install libtest-class-perl
sudo apt-get install liblog-dispatch-perl
sudo apt-get install libparams-validate-perl
sudo apt-get install libdbd-mysql-perl
sudo apt-get install libjson-xs-perl
sudo apt-get install libjson-perl
sudo apt-get install libjson-any-perl
sudo apt-get install libcache-memcached-perl

sudo apt-get install libnumber-format-perl
sudo apt-get install libtest-log-dispatch-perl
sudo apt-get install libconfig-inifiles-perl
sudo apt-get install libwww-perl
sudo apt-get install libdigest-md5-perl
sudo apt-get install libproc-daemon-perl
sudo apt-get install libxml-simple-perl

sudo apt-get install libxml-libxml-perl

¿Cómo saber si tenemos un módulo instalado?

Si Module::Util está instalado, use pm_which:
:~$ pm_which EL::Modulo

Use perldoc, pues para saber si un módulo está instalado y donde se encuentra (supuesto que el módulo contiene documentación en su interior) use perldoc -l:
:~$ perldoc -l EL::Modulo

También puede comprobar la existencia cargando el módulo:
:~$ perl -MEL::Modulo -e 1

Instale pmtools y use el comando pminst (Se puede obtener en http://search.cpan.org/~mlfisher/pmtools/.)

Sigue un ejemplo de uso:
pp2@nereida:~/src/perl/IPC-PerlSSH/lib/IPC$ pmdesc EL::Modulo # descripción

pp2@nereida:~/src/perl/coro$ pminst odulo
EL::Modulo
pp2@nereida:~/src/perl/IPC-PerlSSH/lib/IPC$ pmload EL::Modulo  # Que modulos carga

Módulos en el Núcleo de Perl:
:~> perl -MModule::CoreList -e \
   'print Module::CoreList->first_release("Data::Dumper")."\n"'


Referencias:-Saber que Módulos están Instalados: http://www.davioth.com/lhp/node188.html




martes, 23 de abril de 2013

Android: Adapter personalizado


Un Adapter es una extensión de la clase "android.widget.BaseAdapter" que intermedia entre las clases backend de datos y la frontend vista (LayoutInflater). Por ejemplo:

Object <--- ObjectAdapter --->  ObjectLayoutInflater

LayoutInflater es la clase que convierte xmls de vista frontend  a objetos.




Referencia:
-Como crear un adapter en Android.
http://www.nosolounix.com/2010/12/ejecutar-desde-eclipse-en-movil-android.html

miércoles, 17 de abril de 2013

Programación Python desde cero

Aprender Python desde cero en 10 pasos.

El siguiente video es un taller para Aprende a programar en Python desde cero:

A continuación los primeros pasos desde consola Linux:

1) ¿Cómo sabemos si tenemos instalado Python?
consola:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Si no lo tenes instalado hay que instalarlo. En Linux Ubuntu es como sigue:

sudo apt-get install python python-psycopg2 python-reportlab \
python-egenix-mxdatetime python-tz python-pychart python-mako \
python-pydot python-lxml python-vobject python-yaml python-dateutil \
python-pychart python-webdav

sudo apt-get install python-cherrypy3 python-formencode python-pybabel \
python-simplejson python-pyparsing

sudo apt-get install python-gtk2 python-glade2 \
    python-matplotlib python-egenix-mxdatetime python-hippocanvas

#sudo apt-get install python-xml 


2) El primer código hola mundo en python.
>>> print "Hola mundo"
Hola mundo

3) ¿Listas y diccionarios?
>>> milista=[10,5,"Hola",True]
>>> print milista
[10, 5, 'Hola', True]
>>> usuarios={"Daro":"micuenta", "Carlos":"czantanay", "Codejobs":"codejobs"}
>>> print usuarios["Daro"]
micuenta

4) Tipos implícitos de datos en python:
>>> dato_int=1
>>> dato_str="mi cadena"
>>> type(dato_int)
<type 'int'>
>>> type(dato_str)
<type 'str'>
...presionar Ctrl L para limpiar pantalla.

5) Algunas operaciones en python:
>>> 2 ** 3
8
>>> 100/5
20
>>> 100 % 2
0
>>> 10.5 / 2
5.25
>>> 10.5 // 2
5.0

6) ¿Cómo ejecutar un archivo python?
consola:~$ nano my_first_program.py
#Creamos un archivo...
#El archivo del primer programa:
daro = "micuenta"
if daro == "micuenta":
        print "Mi cuenta es @" + daro
elif daro == "cualquier cosa":
        print "cualquier cosa"
else:
        print "Visita @codejobs"
#guardamos y salimos... presionar: Ctrl O enter + Ctrl X
consola:~$ python my_first_program.py
Mi cuenta es @micuenta

7) ¿Cómo hacer Ciclos en python?
>>>  # bucles while:
consola:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> i = 0
>>> while i<5:
...     i = i + 1
...     print i
...
1
2
3
4
5
>>> # bucles for:
>>> lenguajes = ["php", "Java", "Perl", "Python", "C"]
>>> for item in lenguajes:
...     print "->" + item
...
->php
->Java
->Perl
->Python
->C
>>>

8) ¿Cómo definir funciones en python?
consola:~$ nano my_second_program.py
#Creamos un archivo...
#El archivo del primer programa:
def suma(dato1, dato2):
        print dato1 + dato2

def desplegar(cadena, numero):
        print numero * cadena

suma(5, 5)
desplegar("cadena ", 5)
#guardamos y salimos... presionar: Ctrl O enter + Ctrl X
consola:~$ python my_second_program.py
10
cadena cadena cadena cadena cadena

9) ¿Cómo leer desde consola?
>>> nombre = raw_input("Ingrese su nombre: ")
Ingrese su nombre:


10) ¿Cómo programar orientado a objetos en python?

#El archivo se debe llamar igual que el nombre de la clase.
consola:~$ nano MiPrimeraClase.py
class MiPrimeraClase:
        """Comentarios"""
        nombre = "daro"
        def __init__(self, nombre):
                self.nombre = nombre
        def hola(self):
                print "Hola " + self.nombre

#Instanciar la clase
miprimeraclase = MiPrimeraClase("cacho")
miprimeraclase.hola()
#guardamos y salimos... presionar: Ctrl O enter + Ctrl X

consola:~$ python MiPrimeraClase.py
Hola cacho

Tener en cuenta que:
"Programar programa cualquiera. Para programar bien hay que estudiar. Estudie."

Referencias:
-Taller de programacion Python en Youtube.
-Python Training for HP OSO.
-Python: Orientación a objetos..


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.