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.

domingo, 25 de noviembre de 2012

3 ERP softwares open source evaluation

Evaluation of 3 "ERP Open Source" softwares (OFBiz vs Tryton vs OpenERP)



See Comparing between OFBiz, Tryton and OpenERP.

General features:

- OFBiz:      ERP + CRM + E-commerce + POS + HR
                   (Java + Apache + Multiple database).
                   Licence: Apache

- OpenERP: ERP + CRM + E-commerce + POS + HR
                   (Python + Postgres).
                   Licence: Software as a Service

- Tryton:     ERP
                   (Python + Postgres).
                   Licence: GPL

Installing on Ubuntu 12.04 guides:
- Installing OFBiz.
- Installing OpenERP.
- Installing Tryton.

References:
- Comparing between OFBiz, Tryton and OpenERP.
- OpenERP vs other Open Source ERP.

Install Tryton on Ubuntu 12

Log de instalación de Tryton 2.4 sobre Ubuntu 12.04 (Install Tryton ERP 2.4 on Ubuntu)

Tryton ERP is open source ERP software done with Python language.

Requirement: postgres, python
   See how to install postgres and python in "openERP installing guide".



Ubuntu LOG:
#demo@demo:$ sudo apt-get install python-webdav python-pydot python-tz
#---------------------------------------------------- 
# Install Mercurial SCM 
#----------------------------------------------------
demo@demo:~$ apt-get install mercurial 
demo@demo:~$ cd /tmp
demo@demo:/tmp$ hg clone http://bitbucket.org/pmezard/hgforest-crew/
demo@demo:/tmp$ cd hgforest-crew
demo@demo:/tmp/hgforest-crew$ sudo mkdir -p /usr/local/src/hgforest
demo@demo:/tmp/hgforest-crew$ sudo cp forest.py /usr/local/src/hgforest/
demo@demo:/tmp/hgforest-crew$ sudo su -
root@demo:~# echo -e "[extensions]\nforest=/usr/local/src/hgforest/forest.py" >> /etc/mercurial/hgrc
root@demo:~# nano /etc/mercurial/hgrc
root@demo:~# exit
demo@demo:/tmp/hgforest-crew$ sudo mkdir /usr/local/tryton
demo@demo:/tmp/hgforest-crew$ cd /usr/local/tryton 
 
#---------------------------------------------------- 
# Install tryton 
#----------------------------------------------------
#demo@demo:/usr/local/tryton$ sudo hg clone http://hg.tryton.org/trytond/
#demo@demo:/usr/local/tryton$ sudo hg clone http://hg.tryton.org/tryton/ 
#Instalar la version 2.4 que es compatible con los modulos de Argentina 
 
demo@demo:/usr/local/tryton$ sudo hg clone http://hg.tryton.org/2.4/tryton/
demo@demo:/usr/local/tryton$ sudo hg clone http://hg.tryton.org/2.4/trytond/
 
 demo@demo:/usr/local/tryton$ sudo adduser --no-create-home --system --group tryton
demo@demo:/usr/local/tryton$ sudo chown -R tryton:tryton /usr/local/tryton
demo@demo:/usr/local/tryton$ sudo find /usr/local/tryton/ -type d -exec chmod 775 {} \;
demo@demo:/usr/local/tryton$ cd /usr/local/tryton
demo@demo:/usr/local/tryton$ sudo mkdir /etc/tryton
demo@demo:/usr/local/tryton$ sudo cp trytond/etc/trytond.conf /etc/tryton
demo@demo:/usr/local/tryton$ cd /tmp
demo@demo:/tmp$ cd /usr/local/tryton
demo@demo:/usr/local/tryton$ sudo mkdir config_backup
demo@demo:/usr/local/tryton$ sudo cp /home/demo/Descargas/tryton-server.init config_backup
demo@demo:/usr/local/tryton/config_backup$ sudo cd /etc/tryton
demo@demo:/usr/local/tryton/config_backup$ ls
demo@demo:/usr/local/tryton/config_backup$ cd /etc
demo@demo:/etc$ ls tryton/
demo@demo:/etc$ cd ..
demo@demo:/$ ls try*
demo@demo:/etc$ ls try*
trytond.conf
demo@demo:/etc$ sudo nano trytond.conf
demo@demo:/etc$ cd tryton
demo@demo:/etc/tryton$ ls
demo@demo:/etc/tryton$ sudo nano trytond.conf
demo@demo:/etc/tryton$ cd /usr/local/tryton
demo@demo:/usr/local/tryton$ ls
demo@demo:/usr/local/tryton$ cd config_backup/
demo@demo:/usr/local/tryton/config_backup$ ls
demo@demo:/usr/local/tryton/config_backup$ sudo cp tryton-server.init /etc/init.d/trytond
demo@demo:/usr/local/tryton/config_backup$ sudo chmod +x /etc/init.d/trytond
demo@demo:/usr/local/tryton/config_backup$ sudo mkdir /usr/local/etc/default/
demo@demo:/usr/local/tryton/config_backup$ ls
demo@demo:/usr/local/tryton/config_backup$ cd ..
demo@demo:/usr/local/tryton$ ls
demo@demo:/usr/local/tryton$ cd trytond
demo@demo:/usr/local/tryton/trytond$ ls
demo@demo:/usr/local/tryton/trytond$ cd etc
demo@demo:/usr/local/tryton/trytond/etc$ ls
demo@demo:/usr/local/tryton/trytond/etc$ cd trytond
demo@demo:/usr/local/tryton/trytond/etc$ ls
demo@demo:/usr/local/tryton/trytond/etc$ cd ..
demo@demo:/usr/local/tryton/trytond$ ls
demo@demo:/usr/local/tryton/trytond$ cd etc
demo@demo:/usr/local/tryton/trytond/etc$ ls
demo@demo:/usr/local/tryton/trytond/etc$ cd ..
demo@demo:/usr/local/tryton/trytond$ cd ..
demo@demo:/usr/local/tryton$ sudo mkdir /var/lib/trytond
demo@demo:/usr/local/tryton$ 
demo@demo:/usr/local/tryton$ sudo chown tryton:tryton /var/lib/trytond
demo@demo:/usr/local/tryton$ /etc/init.d/trytond start
demo@demo:/usr/local/tryton$ /etc/init.d/trytond stop
demo@demo:/usr/local/tryton$ sudo /etc/init.d/trytond start
demo@demo:/usr/local/tryton$ sudo /etc/init.d/trytond stop
demo@demo:/usr/local/tryton$ sudo mkdir -p /usr/local/etc/default/
demo@demo:/usr/local/tryton$ sudo su - postgres
postgres@demo:~$ createuser --createdb --no-adduser -P tryton
postgres@demo:~$ exit
demo@demo:/usr/local/tryton$ ls
demo@demo:/usr/local/tryton$ cd tryton
demo@demo:/usr/local/tryton/tryton$ ls
demo@demo:/usr/local/tryton/tryton$ ls
demo@demo:/usr/local/tryton/tryton$ sudo /etc/init.d/trytond start
demo@demo:/usr/local/tryton/tryton$ ls
demo@demo:/usr/local/tryton/tryton$ cd bin
demo@demo:/usr/local/tryton/tryton/bin$ ls
demo@demo:/usr/local/tryton/tryton/bin$ tryton
demo@demo:/usr/local/tryton/tryton/bin$ sudo apt-get install tryton-client
demo@demo:/usr/local/tryton/tryton/bin$ tryton

demo@demo:/usr/local/tryton/tryton/bin$ sudo su -
root@demo: cd /usr/local/tryton/trytond/trytond/modules/
root@demo:/usr/local/tryton/trytond/trytond/modules# 
 
sudo apt-get install tryton-modules-all

# Modules to install (is not necessary be installed manually):
hg clone http://hg.tryton.org/modules/account
hg clone http://hg.tryton.org/modules/account_be
hg clone http://hg.tryton.org/modules/account_de_skr03
hg clone http://hg.tryton.org/modules/account_invoice
hg clone http://hg.tryton.org/modules/account_invoice_history
hg clone http://hg.tryton.org/modules/account_product
hg clone http://hg.tryton.org/modules/account_statement
hg clone http://hg.tryton.org/modules/analytic_account
hg clone http://hg.tryton.org/modules/analytic_invoice
hg clone http://hg.tryton.org/modules/analytic_purchase
hg clone http://hg.tryton.org/modules/analytic_sale
hg clone http://hg.tryton.org/modules/calendar
hg clone http://hg.tryton.org/modules/company
hg clone http://hg.tryton.org/modules/company_work_time
hg clone http://hg.tryton.org/modules/country
hg clone http://hg.tryton.org/modules/currency
hg clone http://hg.tryton.org/modules/google_maps
hg clone http://hg.tryton.org/modules/google_translate
hg clone http://hg.tryton.org/modules/party
hg clone http://hg.tryton.org/modules/party_vcarddav
hg clone http://hg.tryton.org/modules/product
hg clone http://hg.tryton.org/modules/product_cost_fifo
hg clone http://hg.tryton.org/modules/product_cost_history
hg clone http://hg.tryton.org/modules/project
hg clone http://hg.tryton.org/modules/project_plan
hg clone http://hg.tryton.org/modules/project_revenue
hg clone http://hg.tryton.org/modules/purchase
hg clone http://hg.tryton.org/modules/sale
hg clone http://hg.tryton.org/modules/stock
hg clone http://hg.tryton.org/modules/stock_forecast
hg clone http://hg.tryton.org/modules/stock_inventory_location
hg clone http://hg.tryton.org/modules/stock_location_sequence
hg clone http://hg.tryton.org/modules/stock_product_location
hg clone http://hg.tryton.org/modules/stock_supply
hg clone http://hg.tryton.org/modules/stock_supply_day
hg clone http://hg.tryton.org/modules/timesheet 
 
# Modulos Argentinos: 
sudo hg clone https://bitbucket.org/thymbra/account_ar
sudo hg clone https://bitbucket.org/thymbra/country_ar
sudo hg clone https://bitbucket.org/thymbra/account_voucher_ar
sudo hg clone https://bitbucket.org/thymbra/account_check_ar
sudo hg clone https://bitbucket.org/thymbra/account_bank_ar 
 
 
# Start services and launch tryton client
sudo /etc/init.d/postgresql restart
sudo /etc/init.d/trytond start
cd /usr/local/tryton/tryton/bin/
tryton
 
# Otra manera: 
#/usr/local/tryton/trytond/bin$ sudo trytond -c /etc/trytond.conf -u all -d demo
 
 
References:
Tryton org
http://wiki.opdevel.com/Tryton/Instalacion
http://code.google.com/p/tryton/wiki/InstallationOnUbuntu
http://doc.tryton.org/1.6/trytond/doc/topics/install.html
http://wiki.opdevel.com/Tryton/Instalacion
http://code.google.com/p/tryton/wiki/InstallationOnDebian
http://code.google.com/p/tryton/wiki/SetupAndStart

Instalación de la versión 2.4:
http://hg.tryton.org/2.4/
http://hg.tryton.org/2.4/modules
http://wiki.tryton.com.ar/LocalizacionArgentina
http://hg.tryton.org/2.4/tryton/archive/tip.tar.gz
http://hg.tryton.org/2.4/trytond/archive/tip.tar.gz
http://hg.tryton.org/2.4/modules/account/archive/tip.tar.gz
 
Modulos de GCoop para imprenta gráfica:
https://github.com/gcoop-libre/trytond_sale_printery_budget
wget https://github.com/gcoop-libre/trytond_sale_printery_budget/archive/master.zip
git clone git://github.com/gcoop-libre/trytond_sale_printery_budget.git
(copiar en la ubicación de los módulos)


Notas de GCoop para desarrollar en Tryton: 
http://introduccion-a-tryton.readthedocs.org/en/latest/funcional.html#instalar-modulos
https://github.com/gcoop-libre/apuntes_de_tryton 
Las fuentes:
https://github.com/gcoop-libre/apuntes_de_tryton
 

sábado, 24 de noviembre de 2012

Evaluating of Apache OFBiz demo on Ubuntu 12


Apache OFBiz is open source ERP software done with Java language.
This is a quick Getting Started Guide to quickly test it on Ubuntu 12.04.
The OFBiz version tested is "Nightly Trunk Builds" to java 1.6 (Nightly trunk builds do not have release numbers).

Read: "Demo and Test Setup Guide".
Requirement: Java 1.6, SVN and Ant (1.7 or later)

# Open Terminal

# Verify that Java 1.6 is installed
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)

# Verify that Subverrsion SVN is installed
svn --version
svn, version 1.7.7 (r1393599)
   compiled Oct 15 2012, 20:25:39
Copyright (C) 2012 The Apache Software Foundation.

# Verify that Ant is installed
ant -version
Apache Ant(TM) version 1.8.2 compiled on December 3 2011

# Download OFBiz, install demo and start
sudo su -
cd /opt/
svn co http://svn.apache.org/repos/asf/ofbiz/trunk ofbiz
cd /opt/ofbiz/
./ant
./ant run-install
./ant load-demo
./ant start

#Test website, Open a browser and go to:
#for the ecommerce http://127.0.0.1:8080/ecommerce/control/main
#for the ecommerce application or https://127.0.0.1:8443/webtools/control/main
#for the WebTools application or https://127.0.0.1:8443/catalog/control/main

Screenshots:

Applications Menu:

POS Screenshot:

References:
OFBiz:
-Vision general e instalacion con postgres (pdf).
https://cwiki.apache.org/OFBTECH/apache-ofbiz-technical-production-setup-guide.html
https://cwiki.apache.org/confluence/display/OFBADMIN/Demo+and+Test+Setup+Guide
Marksoft:
http://code.google.com/p/marksoft/wiki/Origen_ofbiz_eclispe
- Install OFBiz with MySQL database.
-Apache OFBiz Cookbook.

- Youtube: OFBiz training: How to setup OFBiz starting from an empty System .

- OFBiz Tutorial - A Beginners Development Guide.