Mar 6 2010

Code Monkey like Fritos

blaxter

Until now I've never heard about this song, about a code monkey, funny and nice at the same time. The same songwriter, Jonathan Coulton, has a lot more of similar (geek) songs. Awesome.

Code Monkey get up get coffee
Code Monkey go to job
Code Monkey have boring meeting with boring manager Rob
Rob say Code Monkey very diligent
but his output stink
his code not functional or elegant
what do Code Monkey think
Code Monkey think maybe manager want to write goddamn login page himself
Code Monkey not say it out loud
Code Monkey not crazy just proud

Code Monkey like Fritos
Code Monkey like Tab and Mountain Dew
Code Monkey very simple man
with big warm fuzzy secret heart
Code Monkey like you
Code Monkey like you

Code Monkey hang around at front desk
tell you sweater look nice
Code Monkey offer buy you soda
bring you cup bring you ice
you say no thank you for the soda cause
soda make you fat
anyway you busy with the telephone
no time for chat

Code Monkey have long walk back to cubicle
he sit down pretend to work
Code Monkey not thinking so straight
Code Monkey not feeling so great

Code Monkey like Fritos
Code Monkey like Tab and Mountain Dew
Code Monkey very simple man
with big warm fuzzy secret heart
Code Monkey like you
Code Monkey like you a lot

Code Monkey have every reason
to get out this place
Code Monkey just keep on working
to see your soft pretty face
Much rather wake up eat a coffee cake
Take bath, take nap
This job fulfilling in creative way
such a load of crap
Code Monkey think someday he have everything even pretty girl like you
Code Monkey just waiting for now
Code Monkey say someday, somehow

Code Monkey like Fritos
Code Monkey like Tab and Mountain Dew
Code Monkey very simple man
with big warm fuzzy secret heart
Code Monkey like you
Code Monkey like you


Ene 11 2010

Practical Reporting with Ruby and Rails

blaxter

practical reporting with ruby and railsPractical Reporting with Ruby and Rails es un libro escrito por David Berube sobre reporting con la ayuda de ruby. Se compone de varios capítulos que van desde generar un gráfico con gruff, generar xml/csv/pdf, importaciones desde feeds, hojas de cálculo o Microsoft Office. Todo esto suena bastante bien, pero es el propio carácter del libro, practical, que hace que pierda bastante puntos por su simpleza y falta de profundidad a la hora de tocar los distintos temas.

Es un libro realmente bueno si lo lees con las expectativas apropiadas, y puede llegar a ser un auténtico fiasco en otros casos. En mi particular caso fue el último escenario.

Ya es la segunda vez que me pasa con libros de esta editorial, Apress. Son libros bien escritos, tratando muchos temas, pero con un nivel bastante bajo en cuanto a profundidad de conceptos y nivel requerido. Esto no es malo, por supuesto, simplemente es algo a tener en cuenta para saber si es un libro que te reportará algún beneficio y satisfacción.

Cada capítulo suele seguir la siguiente estructura: (1) Puesta en contexto del problema a resolver, (2) introducción de herramientas a usar, (3) trozo de código, (4) explicación del código. Donde las dos últimas partes suelen ser prácticamente la totalidad del capítulo. El código suele ser bastante simple y sencillo de entender, pero a pesar de ello tendremos luego un considerable número de páginas para explicar obviedades para cualquiera que haya programado mínimamente en ruby o en reporting en general. Si a esto añadimos que el libro no es muy extenso en páginas (280 aprox.) tenemos que se podría resumir el libro en un listado de referencias a herramientas usadas y 5 o 6 snippets de código interesantes de no más de 200 líneas.

De todas formas, para alguien que esté interesado en estos temas (reporting) y que no tenga mucha experiencia (en reporting, en ruby o en ambos), es un libro bastante bueno, bien redactado, bien explicado (demasiado) y de rápida lectura. En otros casos no lo recomendaría, y personalmente no me ha gustado mucho que digamos.


Dic 20 2009

boost::asio, synchronous read with timeout

blaxter

The boost::asio (which means asynchronous input/output) library, is quite powerful library for asynchronous i/o, but it could be a bit difficult at first to figure out how to do a normal synchronous read. So, as a reminder for my future-me, and for you, this snippet it'll be very useful to accomplish that. Probably there will be another ways for doing that, but this is how I managed to do it:

using namespace boost::asio;
using namespace boost::system;
using boost::optional;
 
ip::tcp::socket _socket; // it could be another kind of socket, not only ip::tcp
 
/**
 * Dumb function to be used as handler argument and save the error_code
 * into a pointer
 *
 * e.g.: boost::bind( &set_result, some_pointer, _1 )
 */
void set_result( optional<error_code>* a, error_code b )
{
  a->reset( b );
}
 
#define TIMEOUT 60
/**
 * it uses _socket
 * if timeout happends throw a system_error exception
 */
template<typename MutableBufferSequence>
optional<error_code> read_with_timeout(
    const MutableBufferSequence& buffer
  ) throw( system_error )
{
  optional<error_code> timer_result;
  optional<error_code> read_result;
 
  deadline_timer timer( _socket.io_service() );
 
  timer.expires_from_now( seconds(TIMEOUT) );
  timer.async_wait( boost::bind(&set_result, &timer_result, _1) );
 
  boost::asio::async_read(
      _socket,
      buffer,
      boost::asio::transfer_at_least( buffer_size_helper(buffer) ),
      boost::bind( &set_result, &read_result, _1 )
    );
 
  _socket.io_service().reset();
 
  while ( _socket.io_service().run_one() )
  {
    if ( read_result )
    {
      timer.cancel();
    }
    else if ( timer_result )
    {
      _socket.cancel();
      throw system_error(
          error_code( errc::timed_out, get_generic_category() )
        );
    }
  }
  return read_result;
}
 

I hope it will be useful, have fun.


Dic 2 2009

Mostrar iconos en los botones y menús de gnome

blaxter

En la última versión de gnome, han decidido poner por defecto que no salgan iconos ni en los botones, ni en los menús. Hasta ahora, tenías iconos en todos lados, esto implicaba que los botones eran siempre más grandes de los normal (por incluir dentro de ellos el icono pertinente) lo que hacia que en general, en gnome, las cosas fuesen como más grandes. Con este cambio los layouts van a ser más compactos, aunque también más rancios y menos usuables, IMHO.

No me gusta nada este cambio, más vale una imagen que mil palabras, teniendo iconos vas más rápido porque los reconoces y no necesitas leer cosas, aparte que uno de los aspectos que más me gusta de gnome es esa sensación de que todo es grandote :) . Al menos volver a tenerlos es tarea simple, activa /desktop/gnome/interface/buttons_have_icons y /desktop/gnome/interface/menus_have_icons en el editor de configuración de gnome y ya los tendrás.

$ gconftool-2 --type bool --set /desktop/gnome/interface/buttons_have_icons true
$ gconftool-2 --type bool --set /desktop/gnome/interface/menus_have_icons true

Nov 29 2009

Mostrar notificaciones emergentes desde la consola

blaxter

A veces es útil mostrar algún tipo de notificación gráfica para informarte, por ejemplo, de cuándo se ha terminado una tarea. Las notificaciones emergentes de Ubuntu, añadidas hace un par de versiones, son una muy buena opción.

Dos opciones, (1) instalarnos esta librería de perl libnet-dbus-perl, y nos ponemos esta función en nuestro ~/.bashrc

function notify()
{
    perl -e "use Net::DBus; my \$sessionBus = Net::DBus->session; my \$notificat
ionsService = \$sessionBus->get_service('org.freedesktop.Notifications'); my \$n
otificationsObject = \$notificationsService->get_object('/org/freedesktop/Notifi
cations', 'org.freedesktop.Notifications'); my \$notificationId; \$notificationI
d = \$notificationsObject->Notify(shift, 0, '', '$1', '$2', [], {}, -1);"
}
$ notify foooooooo baaarrr

notify

El primer parámetro es el título y el segundo el contenido.

Otra forma (2) todavía más fácil es instalarnos el paquete libnotify-bin, el cual contiene el binario notify-send que hace justamente esto. Probablemente la primera solución nos servirá para cualquier distro, mientras que la segunda solo en debian, ubuntu y derivados. Ambas funcionan exactamente igual y sin problemas.


Nov 23 2009

How to know, in ruby, which methods have been added and by whom?

blaxter

If you are not very careful, monkeypatching could be very harmful. One thing to remember is that you should never override a method to add funcionality, for those kind of thinks you must use alias chain method pattern, a safer way of doing that.

For the rest of the monkeypatching, i.e. add new methods, you could debug them really easy with something like this:

class Class
   def method_added(method_name)
      puts "#{method_name} added to #{self}, callstack:"
      puts caller.map{|line| "\t#{line}" }.join("\n")
   end
end

You can always add more code to filter by class or by method's name. Let's see an example:

$ more example.rb
require 'date'
require 'time'
 
class Class
   def method_added(method_name)
      return if %w(method_added).include? method_name.to_s
      puts "#{method_name} added to #{self}, callstack:"
      puts caller.map{|line| "\t#{line}" }.join("\n")
   end
end
 
class Time
   def to_date
      Date.ordinal self.year, self.yday
   end
end
 
class Date
   def to_time
      Time.parse self.to_s
   end
end
 
raise "to_date not working" unless
   Time.now.to_date == Date.today
raise "to time not working" unless
   Time.now.to_date.to_time == Date.today.to_time

The output will be:

$ ruby example.rb
to_date added to Time, callstack:
	example.rb:13
to_time added to Date, callstack:
	example.rb:19

Nice, isn't it?. Remember to be carefull with your monkeypatching, with great power comes great responsibility, it's just a tool, neither magic nor the panacea.