Archivo

Entradas Etiquetadas ‘perl’

Yo adoro Perl, pero…

Domingo, 19 de octubre de 2008

Perl nos tiene esperando por una versión nueva desde hace tiempo. Pero de allí a que un blogger en O’Reilly salga diciendo que Perl + CGI es todavía una alternativa viable para hacer aplicaciones web hay mucho trecho.

¿Donde estás Perl, que no te vemos? Mientras tanto, Java Servlets 3.0 promete cosas interesantes.

Buscar en otros sitios:

Blogalaxia:, , ,
Technorati:, , ,
To2blogs:, , ,
Del.icio.us:, , ,

Sin categoría , , ,

Sentilla tiene soporte para OSX y Linux Ubuntu

Viernes, 6 de junio de 2008

Ya sacaron el beta. Del foro oficial de Sentilla:

NEW! Sentilla Work (Beta) for Mac and Linux

Downloads of the Beta release of Sentilla Work for both Mac OS X and Ubuntu Linux are now available for current Perk customers at the following URLs:

  • Sentilla Work (Beta) for Linux
  • Sentilla Work (Beta) for Mac OS X

Go to the URL for your OS of choice and login as

XXXXXX

and use the password

ZZZZZZZZ

After you download the release to your computer and expand the files, refer to the Release Notes included with the builds for installation instructions (page 10) and important notices. You do not need to reinstall mote firmware for this release; your current Perk firmware will work on both the Mac OS X and Linux platforms.

Note that you cannot install firmware with the Mac OS X release.

Christine at Sentilla

Los instalaré en algún momento el fin de semana, vamos a ver que tal se porta.

Buscar en otros sitios:

Blogalaxia:, , , ,
Technorati:, , , ,
To2blogs:, , , ,
Del.icio.us:, , , ,

kodegeek , , , ,

RSS de Globovision está roto II: Java al rescate

Domingo, 9 de marzo de 2008

Bueno, varias horas después y sin respuesta de Lunar Pages, me decidí a reescribir el programa usando Java. Lo primero que intenté fue tratar de procesar la página de noticias de Globovision.com, pero quienes hicieron el código del sitio Web simplemente no saben de programación HTML, y el daño es demasiado para el ya sensible JTidy:

line 15 column 1 - Warning: unexpected </head> in <link>line 20 column 165 - Warning: unexpected </a> in <img>line 20 column 169 - Warning: unexpected </td> in <img>line 23 column 97 - Warning: unexpected </td> in <img>line 24 column 5 - Warning: unexpected </tr> in <img>line 26 column 93 - Warning: unexpected </a> in <img>line 26 column 97 - Warning: unexpected </td> in <img>This document has errors that must be fixed beforeusing HTML Tidy to generate a tidied up version.

Asi que, ¿como procesar un documento que está así de roto en Java?

Bueno, el sitio de Java tiene mucha documentación y una de las cosas interesantes que muestran es como usar el parser que tiene Swing pero afuera de sus componentes gráficos. Esto resolvió perfectamente como obtener e iterar un documento roto, ahora sólo quedaba resolver el problema de escribir el RSS lo más fácil posible.

Después de buscar un poco me decidí a usar la librería Rome. No es pesada, lo único fastidioso es que requiere JDOM. Bueno, antes tuve que pedir que instalarn Expat para Perl, asi que mejor no me quejo :)

El código como siempre está en Source Forge, en el sitio de KodeGeek. Se los pongo aquí por comodidad:

  1 package com.kodegeek.blog.rss;  2  3 import java.io.BufferedReader;  4 import java.io.FileWriter;  5 import java.io.InputStreamReader;  6 import java.io.Reader;  7 import java.io.Writer;  8 import java.net.URL;  9 import java.util.ArrayList; 10 import java.util.Date; 11 import java.util.List; 12 import java.util.logging.Level; 13 import java.util.logging.Logger; 14 15 import javax.swing.text.AttributeSet; 16 import javax.swing.text.MutableAttributeSet; 17 import javax.swing.text.html.HTML; 18 import javax.swing.text.html.HTML.Tag; 19 import javax.swing.text.html.HTMLEditorKit.ParserCallback; 20 import javax.swing.text.html.parser.ParserDelegator; 21 22 import com.sun.syndication.feed.synd.SyndEntry; 23 import com.sun.syndication.feed.synd.SyndEntryImpl; 24 import com.sun.syndication.feed.synd.SyndFeed; 25 import com.sun.syndication.feed.synd.SyndFeedImpl; 26 import com.sun.syndication.io.SyndFeedOutput; 27 28 29 /** 30  * Program that converts the main summary news from Globovision.comto RSS format. 31  * @author josevnz at kodeeek.com 32  *

License: GPL

 33  * I use a combination of Yahoo Pipes and Google Reader to keep meupdated about news of any kind. However, some websites like 34  * Globovision.com still don't have a proper RSS feed,so one day Idecided to create my own mashup :) . 35  * It worked for a while until my Blog hosting providerdecided toremove the XML::RSS Perl module I asked to install for me.Because of that, 36  * this Java version was born. 37  */ 38 public final class GlobovisionHtml2Rss { 39 40  public static final StringGLOBOVISION_URL = "http://globovision.com"; 41  public static final String NEWS_URL =GLOBOVISION_URL + "/history.php?cha=1&pag=1"; 42 43  private static Logger log; 44  private static final long DEFAULT_WAIT = 1000L*60L*5L; 45 46  // Do not alow instances of this class to be created 47  private GlobovisionHtml2Rss() { 48   // Empty 49  } 50 51  static { 52 53   log = Logger.getLogger(GlobovisionHtml2Rss.class.getName()); 54  } 55 56  /** 57   * @param args 58   */ 59  public static void main(String[] args) throws Exception { 60 61   try { 62    fetch(NEWS_URL, args[0]); 63   } catch (Exception exp) { 64    log.log(Level.SEVERE, "Cannot recover from thisexception", exp); 65   } 66  } 67 68  /** 69   * Try to fetch the URL and convert it to a Document 70   * @param url 71   * @param outfile 72   * @return 73   * @throws Exception 74   */ 75  private static void fetch(String url, String outfile) throws Exception { 76   Reader reader = null; 77   Writer writer = null; 78   SyndFeed feed; 79   List <SyndEntry>news = new ArrayList<SyndEntry>(); 80   try { 81    feed = new SyndFeedImpl(); 82    feed.setAuthor("Jose Nunez, josevnz at kodegeek.com"); 83    feed.setDescription("Globovision.com news - Brough toyou by http://KodeGeek.com"); 84    feed.setFeedType("rss_1.0"); 85    feed.setLink("http://www.kodegeek.com/rss/globovision.rss"); 86    feed.setTitle("Globovision.com Venezuelan News"); 87    URL globovisionURL = new URL(url); 88    reader = new BufferedReader(new InputStreamReader(globovisionURL.openStream())); 89    ParserDelegator parser = new ParserDelegator(); 90    parser.parse(reader, new GlobovisionHtml2Rss().new GlobovisionParser(news), false); 91    if (news.size() > 0) { 92     feed.setEntries(news); 93     writer = new FileWriter(outfile); 94     SyndFeedOutput feedOut = new SyndFeedOutput(); 95     feedOut.output(feed, writer); 96    } 97   } catch (Exception exp) { 98    throw new Exception("Unexpected problem", exp); 99   } finally {100101    if (reader != null) {102     reader.close();103    }104105    if (writer != null) {106     writer.close();107    }108    news.clear();109   }110  }111112  /**113   * Helper class used to parse Globovision news website114   * @author josevnz115   */116  class GlobovisionParser extends ParserCallback {117118   private boolean getHeadline = false;119   private AttributeSet attribute;120   private List <SyndEntry>entries;121122   public GlobovisionParser(List <SyndEntry>entries) {123    this.entries = entries;124   }125126   /**127    * Globovision HTML is so broken than we will ignore the errorssilently.128    * Increase the logger verbosity to see the errors129    */130   public void handleError(String errorMsg, int pos) {131    log.log(Level.FINE, String.format("%s, %d", errorMsg, pos));132   }133134   /**135    * Looking for:  tag = "a" and  attr{href} =~ /news.php?nid=\d+/136    * @param t Tag137    * @param a Attribute set138    * @param pos position139    */140   public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {141    if (142      (t == Tag.A) &&143      (a.getAttribute(HTML.Attribute.HREF) != null)&&144      (a.getAttribute(HTML.Attribute.HREF).toString().matches("news\\.php\\?nid=\\d+"))145    ) {146      attribute = a.copyAttributes();147      log.log(Level.FINE,String.format("Tag: %s, attributes: %s", t, a));148      getHeadline = true;149    }150151   }152153   /**154    * Get the headline and also write the RSS entry155    * @param data Text next to the headline156    * @param pos position157    */158   public void handleText(char[] data, int pos) {159    if (getHeadline) {160     SyndEntry entry = new SyndEntryImpl();161     entry.setLink(String.format("%s/%s",GLOBOVISION_URL, attribute.getAttribute(HTML.Attribute.HREF).toString()));162     entry.setPublishedDate(new Date());163     entry.setTitle(new String(data));164     entries.add(entry);165     getHeadline = false;166     attribute = null;167    }168   }169170171172  }173174 }

Debo admitir que el proceso para volver a crear el RSS de Globovision desde Java fué más complejo y requirió más código que el de Perl (aunque terminé mi nueva versión antes que Lunar Pages reemplazara el modulo perdido, unas cuantas horas después) . Pero por otro lado, aprendí más trucos con este y al menos ya no tengo que preocuparme por pedirles que instalen módulos no estandares.

Nota a los subscriptores del la fuente de Globovision en RSS: La versión vieja ya funciona de nuevo. Pienso montar la nueva dentro de poco con nuevas mejoras. Una de ellas es que este tipo de error no afectará el programa (aunque no doy ningún tipo de garantias por soporte gratis :) ).

To Lunar Pages: Response to this issue was kind of slow, thanks for fixing the issue on my account anyways.

Buscar en otros sitios:

Blogalaxia:, , , ,
Technorati:, , , ,
To2blogs:, , , ,
Del.icio.us:, , , ,

java , , , ,

RSS de Globovision está roto I

Domingo, 9 de marzo de 2008

Creo que mi proveedor de hospedaje decidió remover el modulo de Perl XML::RSS que utilizo para crear el RSS de Globovisión el día de hoy:

Can't locate XML/RSS.pm in @INC (@INC contains:/usr/lib/perl5/5.8.5/i386-linux-thread-multi/usr/lib/perl5/5.8.5 /usr/lib/perl5/site_perl/5.8.5/i386-linux-thread-multi/usr/lib/perl5/site_perl/5.8.4/i386-linux-thread-multi/usr/lib/perl5/site_perl/5.8.3/i386-linux-thread-multi/usr/lib/perl5/site_perl/5.8.2/i386-linux-thread-multi/usr/lib/perl5/site_perl/5.8.1/i386-linux-thread-multi/usr/lib/perl5/site_perl/5.8.0/i386-linux-thread-multi/usr/lib/perl5/site_perl/5.8.5 /usr/lib/perl5/site_perl/5.8.4/usr/lib/perl5/site_perl/5.8.3 /usr/lib/perl5/site_perl/5.8.2/usr/lib/perl5/site_perl/5.8.1 /usr/lib/perl5/site_perl/5.8.0/usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/usr/lib/perl5/vendor_perl/5.8.4/i386-linux-thread-multi/usr/lib/perl5/vendor_perl/5.8.3/i386-linux-thread-multi/usr/lib/perl5/vendor_perl/5.8.2/i386-linux-thread-multi/usr/lib/perl5/vendor_perl/5.8.1/i386-linux-thread-multi/usr/lib/perl5/vendor_perl/5.8.0/i386-linux-thread-multi/usr/lib/perl5/vendor_perl/5.8.5 /usr/lib/perl5/vendor_perl/5.8.4/usr/lib/perl5/vendor_perl/5.8.3 /usr/lib/perl5/vendor_perl/5.8.2/usr/lib/perl5/vendor_perl/5.8.1 /usr/lib/perl5/vendor_perl/5.8.0/usr/lib/perl5/vendor_perl .) at/home/kodeg2/scripts/GlobovisionHtml2Rss.pl line 6.BEGIN failed--compilation aborted at/home/XXXX/scripts/GlobovisionHtml2Rss.pl line 6.

Esta es una de las pocas cosas que odio de Perl; Montar módulos en ubicaciones alternativas ES UN FASTIDIO (si no tienes ROOT). En mi caso no tengo accesso a shell para hacerlo yo, así que dependo de la bondad de los administradores de Lunar Pages para que ellos lo hagan.

¿Que hacer? Bueno, o pedirles que lo monten en mi directorio (y yo agrego la ruta de busqueda usando “use lib”) o lo hago en otro lenguaje como Java (en cuyo caso copio mis Jar en donde me de la gana).

Voy a pensarlo un poco, vamos a ver que tanto tiempo toma escribir el mismo código en otro lenguaje.

Blogalaxia:, ,
Technorati:, ,
To2blogs:, ,
Del.icio.us:, ,

Buscar en otros sitios:

java , , ,

Appleworks 6.2 sucks: Unable to import a simple CVS file?

Lunes, 19 de noviembre de 2007

I decided to buy Appleworks when I got my Apple Quad machine as OpenOffice support seemed to be weak on OSX and I was not going to give $500+ dollars to Microsoft to use a 2004 version of Office.

So I was somehow happy with Appleworks until I decided to do something simple as to import a CSV file created with Google Finance portfolio application.

It didn’t work. Fustrated I asked for help on the Apple support forum (the Appleworks FAQ is just useless at least with this particular issue) and luckly for me I got my answer in a couple of hours.

At the end I rolled out a savy one Perl liner that solved my problem:

auyan:~/Desktop josevnz$ perl -p -i -e ‘s#,#\t#g; s#\n#\rn#;’ 401k-funds-appleworks.csv

I guess I will try OpenOffice again or will buy Office for OSX and byte the bullet. But my advice is to stay away from a product that cannot deal with a simple conversions like this :(

Correction: Is CSV file not CVS. Too lazy to republish the whole thing again :)

Blogalaxia:, , , , ,
Technorati:, , , , ,
To2blogs:, , , , ,
Del.icio.us:, , , , ,

Sin categoría , , , , ,

Convertidor de HTML a RSS para las noticias de Globovisión.

Domingo, 14 de octubre de 2007

Siguiendo con la fiebre de los Mashups hechos con Yahoo Pipes, llegué al punto en que decidí escribir un convertidor de HTML a RSS para Globovision. Como recordaran, Globovision no ofrece un feed RSS de sus noticias nacionales, lo cual es una verdadera lastima.

Asi que con un poco de imaginación decidí escribir este programa en Perl:

 1 #!/usr/bin/perl 2 3 use strict; 4 use LWP::UserAgent; 5 use HTML::Parser; 6 use XML::RSS; 7 8 my $rss = XML::RSS->new( version => '0.9' ); 910 my $rssFile = "$ENV{HOME}/globovision.rss";1112 $rss->channel(13  title        => "Globovision.com Venezuelan News",14  link         => "http://globovision.com/",15  description  => "Globovision.com news -Brough to you by http://KodeGeek.com");1617 # Be carefull with this one as nested elements can be ignored and18 # HTML normally is not well formed!19 my @ignore_tags = (20  "head",21  "h1",22  "strong",23  "form"24    );2526 my $baseUrl = "http://globovision.com/";2728 # We are only interested on the news from the first page,as more news come up it will push older news29 my $newsUrl = "$baseUrl" . "history.php?cha=1&pag=1";3031 use constant DEFAULT_TIMEOUT32  => 180;3334 my $agent = LWP::UserAgent->new({35   agent => 'GlobovisionHtml2Rss.pl/kodegeek 0.1',36   timeout => DEFAULT_TIMEOUT37      });38 my $response = $agent->get($newsUrl);39 if (! $response->is_success) {40  die  sprintf "[ERROR]: Unable to retrieve the HTMLfrom '%s', Status: '%s'", $newsUrl, $response->status_line;41 }42 my $parser = HTML::Parser->new(43                         api_version => 3,44    start_h => [ \&start_a, "tagname, attr" ],45    text_h => [ \&get_headline, "dtext" ]46    );47 $parser->ignore_tags(@ignore_tags);48 my $headlineFlag=0;49 my $currUrl=undef;50 $parser->parse($response->decoded_content());5152 $rss->save($rssFile);5354 # ****** Functions used on the script *******5556 # Get the headline57 sub get_headline {58  my $headline = $_[0];59  if ($headlineFlag) {60   $rss->add_item( title => $headline, link => $currUrl);61   $headlineFlag = 0;62   $currUrl=undef;63  }64 }6566 # Identify news items67 sub start_a {68  my $tagname = $_[0];69  my %attr = %{$_[1]};70  if ( ($tagname eq "a") && ($attr{href} =~ /^news.php?.nid=\d+/) ) {71   my $url = $baseUrl . "/" . $attr{href};72   $url =~ s/&/&/g;73   $currUrl = $url;74   $headlineFlag=1;75  }76 }77 __END__78 =head1 NAME7980 GlobovisionHtml2Rss.pl - Script to convert Globovision.com Venezuelalocal news from HTML to RSS.8182 =head1 DESCRIPTION8384 I use a combination of Yahoo Pipes and Google Reader to keep meupdated about news of any kind. However, some websites like85 Globovision.com still don't have a proper RSS feed, so one dayI decided to create my own mashup :).8687 =head1 AUTHOR8889 Jose Vicente Nunez Zuleta (josevnz@kodegeek.com)9091 =head1 BLOG9293 KodeGeek - http://kodegeek.com9495 =head1 LICENSE9697 GPL9899 cut

Lo más fastidioso de este ejercicio fué instalar EXPAT (para el procesamiento del XML del feed RSS) y el módulo parta crear el archivo RSS (me da un fastidio enorme aprender como es el formato resultante).

Mi proveedor de hosting gustosamente instaló el módulo XML::RSS. Después de probarlo un poco aquí les dejo las noticias de Globovisión para que la disfruten (planeo actualizar el lector de noticias cada 10 minutos para no matar a mi servidor).

Blogalaxia.com:globovision, rss, html to rss, perl, open source
Technorati.com:globovision, rss, html to rss, perl, open source

Sin categoría , , , ,

Nuevo grupo de fotos en Flickr: Venezuela Open Source

Domingo, 15 de julio de 2007

Walc2005 Mérida, Richard Stallman
Richard Stallman en Walc 2005, cortesía de Jorge Camargo.

Me parece curioso que habiendo tanta actividad del movimiento Open Source en Venezuela, no haya un grupo en Flickr en el cual se puedan compartir esos momentos capturados en una fotografía.

Por eso me decidí a crear un grupo, llamado Venezuela Open Source. El grupo está abierto a la discusión del acontecer Open Source en el país y no está limitado a fotos, sino tambien a captura de programas que ustedes conozcan.

Asi que les pido el favor y que rieguen la voz para que todos los interesados nos beneficiemos.

Blogalaxia.com:venezuela, open source, linux, java, gnu, perl, discusion
Technorati.com:venezuela, open source, linux, java, gnu, perl, discusion

java , , , , , ,

¿Como contar el espacio usado en un directorio usando Perl?

Lunes, 2 de abril de 2007

Una de esas tantas ociosidades que a la final resultan útiles si lo que se quiere es un programa que funcione igual bajo Windows, Linux o Solaris:

#!/usr/bin/perluse File::Find;use Getopt::Long;use strict;

my $func;my $unit;my @dirs;my %units = (      kb => [ 1024.0,  "KB"],      mb => [ 1024.0* 1024.0, "MB"],      gb => [ 1024.0 * 1024.0 * 1024.0, "GB" ]);

GetOptions("dirs=s" => \@dirs, "unit=s" => \$unit);die "Define the directories to measure" if (scalar(@dirs) == 0);$unit = "gb" if not defined $unit;$unit = "gb" if not defined $units{$unit};

{      my $tsize = 0;      $func = sub {              my (                      $dev,                      $ino,                      $mode,                      $nlink,                      $uid,                      $gid,                      $rdev,                      $size,                      $atime,                      $mtime,                      $ctime,                      $blksize,                      $blocks) = stat($File::Find::name);              if ( -f ($File::Find::name)) {                      $tsize += $size;              }              return $tsize;      }}

printf "Scanning directories: %s\n", join(',', @dirs);foreach my $dir (@dirs) {      find({ wanted => $func, follow => 0 }, $dir);}

printf "Total size of all combined directories: %.2f %s\n",      (&$func) / $units{$unit}[0], $units{$unit}[1];

La salida de ejemplo seria la siguiente:

auyan:~/src/perl/blog josevnz$ ./du.pl -dir /Users/josevnz -dir /tmp -unit ppScanning directories: /Users/josevnz,/tmpTotal size of all combined directories: 31.05 GB

Una belleza por lo simple :D

Blogalaxia.com:du, perl
Technorati.com:du, perl

Sin categoría ,