sábado, 27 de febrero de 2010

Mastermind in scheme. Now with GUI!!

plt scheme has a wide collection of libraries, some bundled with the basic package, and some which have to be installed through PLaneT.

GUI library is from the first group, so if you have plt-scheme already installed (not mzshceme alone, but the complete suite, with drscheme and so) you already have everything you need.

WARNING: It seems there's some programming course in NY with an assignment related to writing a mastermind. If it's your case, please, do not use my code blindly. I'm a novice scheme programmer, and probaly, my code is not very idiomatic. Anyway, have fun.

I've been using the mastermind game as a toy project to learn scheme for the last month. And now, it even has a little GUI. I also have a solver in 5 tries (in the worst case) but I haven't embedded it yet in the GUI.

The process of writing GUIs using plt-scheme is easier than I thought. It's great to write little things (we could say it makes easy things really easy). I don't know how difficult it'd be to write a more complex GUI, for example, I haven't found any grid component. Only comboboxes, radiobuttons, buttons and text-fields.

The good part is that it's really easy to assemble these compoonents in layouts, panels, frames, and so. It's also really easy adding menus to windows.

Here follows a little code that lets you play mastermind, fully coded in scheme.

Btw, This is (more or less) what I used last wednesday at flibug meeting to show an example of GUIs in plt. I really enjoyed the meeting: Learning, sharing, having fun, and beers :) .There's some more info about the last flibug meeting in my last post.

viernes, 26 de febrero de 2010


This has been a frenetic week. It seems that flibug and Perl Mongers meet at the same week every month.

But first things first.

Monday: Erlang.

I attended to the first class of an introductory erlang course. For the moment, we only looked at erlang syntax (btw, it sucks), and some points of functional programming. Pattern matching, tail recursion, consing, lists, and some erlang's BIFs to manage lists (we have neither while nor for). I'll expand a bit more on erlang on a future post.

Wednesday: Flibug.

A small and familiar meeting. Thomas H. Marc-André L., Andrew B., Andy W and me. As always, we talked about what we are hacking on lately and did some lightning talks.

  • I did my first lightning talk, about making GUIs using plt-scheme. A bit simple for the general level of flibug talks, but well, I think it's a good way to start doing talks. And probably, Thomas will do a talk next month on an alternative way to write GUIs in scheme. I'll post about it in a future post.
  • Andrew B. talked about an app he did some time ago in OCaml to apply morphologic filters to images. Pretty interesting but I couldn't understand the details. All in all, I think I got a good overview and I got 'the message': "functional pays off more times than we think".
  • Wingo showed us some interesting parts of guile code. Mostly the evaluator, and he explained us the multilevel scheme compiler/interpreter (c -> scheme -> scheme). He also showed us the guile-gtk bindings.
Great meeting, as always, and it makes you feel like hacking more and more.

Thursday: Breakout && Barcelona Perl Mongers.

After $work, I went to borneo bar, the place where this month's Breakout was held. Some chitchat while having lunch with other smalltalkers, then some hacking, and at 20:00, we had a PerlMongers meeting.
  • Alexm brought some round tuits for us. He explained some of his experiences at last FOSDEM.
  • Esteve did a talk about FluidDB implementation and it's intended usage. Pretty cool stuff, and little by little, I think I start to understand the amplitude of the concept.
  • Fxn ended the session with a talk on his Net::FluidDB module, and the difficulties he had to coerce floats,ints and booleans between fluiddb and Perl. He talked about some Perl internals I didn't know. And he's a great speaker, so it's always a pleasure to hear.
  • It was probably the most crowded PM meeting I've been to. It was a really great meeting.

You see... pretty busy week, isn't it? Well, in fact, at $work I've been busy too, reading about evolving graphs in genetic algorithms. I've done some literature fetching on GA parallelization.

My brain's gonna explode in 5, 4, 3, 2,.... Ah no, I'm just in coma.

Btw, when writing this post, I've started a new tiny tool which I called LinkAdder, that's just intended to add some common html links I insert over and over on my posts. Its repo is here. It's a very simple translator for now, but I have some ideas for it.

viernes, 19 de febrero de 2010

Roboshop 0.01

This is an addendum to my last post on web scraping with perl and HTML::TreeBuilder. I've named the script Roboshop.

Ok, I've rewritten the roboshop script. Now it's shorter, and more reliable (as reliable as a webscrapper can be)
So If you want code(you got it) (yeah, I know it sounds better with "if you want blog, you got it", but there's little chance I can make this pun, and AC/DC is cool anyway).

The site seems to send different html pages depending on some (unknown to me) variables.

So I analyzed the two variants. At present version (alpha 0.01) it just outputs an array with prices, but I'm in the process of making it cooler, and send me mails when it finds some interesting thing in the INTERNETZ.

Here you can see the use for HTML::Element look_down with chained calls to get the desired node. Apart from cpan, there's more info here.

I'm thinking about writing a WWW::Search subclass too. We'll see...

Btw, I don't understand why perl isn't syntax-highlighted when embedded in the blog. If you have any pointers, I'd be very happy to hear a way to solve that. Sorry for the inconvenience.

See ya in the next post.

Thanks for the shopped Artwork go to nabax. =)

jueves, 18 de febrero de 2010

Mi último sueño

De pequeño escribía historias imposibles y las acababa diciendo que el personaje se despertaba. Estaba bien la impunidad que daba el sueño, y la invencibilidad de la que disponías.

De mayor a veces me pasan cosas que al despertarme recuerdo, y hubiera preferido estarlas soñando. Pero no. Hay pruebas reales.

Entonces me doy la vuelta e intento volver a dormir, para soñar con la noche anterior, y mandar la historia entera al mundo de Morfeo. Pero ya no me duermo.

lunes, 15 de febrero de 2010

robots go shopping!

One way to go shopping is spending long afternoons walking among crowds. I imagine it can be less boring than I think but anyway... I've written a little perl program that finds cheap books for me, and mail me if there's any good oportunity. This makes shopping more fun for sure. :)

I've used HTML::TreeBuilder to parse the html. Yo'll have to take a look at HTML::Element too.

The site I'm parsing has changed three times since I started writing this script (2 weeks ago), so it will get outdated very soon, but well...

HTML::TreeBuilder can treat any given html as a Tree (huh, really? ¬¬ ) and lets you navigate through it in multiple ways. A very intuitive way to traverse a tree looking for some tag is using look_down. it accepts an even number of arguments, the first being an attribute name, and the next being the content you want to match.

For example here's a stupid code that extracts some tables from an html.

my $tb = HTML::TreeBuilder->new();
my $root = $tree->root;
my @res = $tb->look_down('_tag', 'table', 'class' , 'result');
say $_->as_text for (@res);

The steps are really easy and this lib gives you the power to write web spiders fairly easy. If you're more fond of python, you can use beautiful soup (which has a smalltalk port too).

As the code is pure unstable crap, I'm not going to upload it for the moment...

OFF-TOPIC PS for last Saturday hardparty-ers: I'm still alive, well and kicking. Thanks, sorry, and good luck!

jueves, 11 de febrero de 2010


WARNING: Este post fue escrito el mismo dia de presentar, y lo he dejado talcual, aunque con perspectiva se ve cutre-friki-quieroYNoPuedo de cojones. Pero lo dejo talcual.

Todos como uno solo, alcemos la voz al cielo, porqué $DEITY (en caso de que hayas definido esa variable) nos escucha desde $DEITY->location. Gritad conmigo: Hallelujah! Hallelujah! Hallelujah! Hallelujah!

Porqué al final del camino, la luz brilla más que a la mitad de él. Gritemos Hallelujah!

Después de estar recibiendo enseñanzas durante 8 años (y pico) en el monte FIB, hacer un viaje para aprender de otros en La Laguna, de donde volví con el espíritu cargado de fuerzas gracias a profetas y discípulos, el viaje de aprendizaje formal terminó hace 2 semana, con un resultado francamente bueno.

Aquí os dejo, amigos míos, el resultado de mis 6 meses, entregados para vosotros. Mirad, y sonreír todos, que esto es lo mejor que se hacer, hablar de frikadas, y delante de gente. Y no me juzguéis si no queréis ser juzgados, que ahí me puntuaban, y no podía ser Rai 100%. Disfrutad de los primeros 10 minutos viéndome hablar a 2x en un baile 33% funky cold medina, 33% macarena y 33% saturday night (esta os la buscáis vosotros/as).

Quiero dar las gracias a mis padres, y también a todos los que no son mis padres. A todos los que me han dejado un sofá para pasar una noche (sóis más gente de la que os pensáis), quiénes me han iluminado y gentuza en general. Ya sabéis quien soys. Os quiero, gracias por este sueño, que os den por el culo, etc...

Venga, ahora unos links y los videos
El pe de efe: genetic algorithms memoria

Las transpas: genetic algorithms slides

Los códigos fuente de la memoria estan en mi github

La presentación.

Algoritmes genètics aplicats a ciències de la vida from Raimon Grau on Vimeo.

Las preguntas (y sus respuestas (y sus coñas marineras)).

Algoritmes genètics aplicats a ciències de la vida - preguntes from Raimon Grau on Vimeo.

Ahora por fin tengo tiempo de aprender.

miércoles, 10 de febrero de 2010

Are you attending more classes? No I'm just charging my batteries

I'm fucking amazed. I mean, I'm really FUCKIN amazed.

These Advanced OOP Design classes are more meta than I ever could have thought. Stéphane is that kind of guy that charges your batteries when listening him. A great and passionate speaker.

Today's class was more like a open-your-eyes session than a hardcore technical lecture. Maybe many people does not like these kind of things, but myself, I love them. It's when you feel you're not sure you're in the right path, or don't feel motivated enough to hack on things, the right person cracks in and explains his experiences, and gives you metarules to clear your ideas. Like giving you the toolkit and materials to build your toolchain to eval on yourself, and then, make or break.

Instead of doing the explanations on "why tiny methods matter", or discussing about aggregation vs composition (luckily I did my homework yesterday anyway), he pointed us some ideas of "how stuff should work" (Note to self: buy www.howstuffshouldwork.something), or better said, "where things are going". Also, explained his opinions about some dynamic languages. And explained the beauty of uniformity (object -> class -> metaclass-> metaclass class).

Some points I got (all bullets multiplied by my vision of things):
  • Gimme a man(1) with examples, or better still: gimme access to the code that uses XYZ function.
  • Simple and small m/(systems|rules)/ make $1 powerful and extensible. Don't break the simplicity as far as you can.
  • Systems should be small, but not smaller than useful (They're trying to do that in pharo)
  • Object -> Classes -> Metaclasses -> Metaclass class is so beautiful
  • Marketing is capable of amazing things.

On the meta side (all bullets multiplied by my vision of things):
  • Do stuff you like. Be a kid. play with stuff, break things, fix them, or throw them away, but don't be passive about the world.
  • Take the time to learn things. Invest in yourself. And now it's easier than ever getting info about anything you like. No more traveling 30 km to get a book that iif you're lucky, you can take home. "OH HAI INTERNETZ".
  • Value your time. Signal / noise is low nowadays. Evaluate what you spend time on.
  • Use internet wisely. After you downloaded all the crap you won't have time to watch/listen, take a look at http://arxiv.org/ ,http://portal.acm.org , or just take a project you like, and play. You can mail your 'idols' and probably they will answer you kindly.
  • You're not obliged to do anything of that, but keep in mind we're part of our community (the REAL world), and it depends on us building the future of the culture, community and so. Choice is yours.
I want to make clear that he didn't say anything of this textually, so most of the bullets are versions of high-level-ideas-he-said strongly modified by my highly biased way of thinking.

It's difficult to express how happy I am to attend these lectures. Thanks again to JD and SD. I think I'll subscribe to pharo mail list, and try to collaborate in anything I can do. Even if I only can do little support on IRC to smalltalk newbies.

lunes, 8 de febrero de 2010

Advanced OOP design with Smalltalk and Stéphane Ducasse

I've just been in the first lecture of Dr Ducasse's course on advanced OOP design here in Barcelona.

And I've to say it's been GREAT. A guru that talks with hackers in mind, being a great one himself. And with lots of good points in the prespective one should care about when entering a new world of hacking/amusement.

He started with an introduction to smalltalk while jumping back and forth to meta-level . We already saw the boolean implementation in the first 20 minutes, and jumped to ifTrue:ifFalse: implementation.

During the talk, he spoke about some real cases he encountered in his life, talking about india, china, project costs in "Old Europe" vs eastern, and the importance of having a delta that makes you different from your co-workers (oponents?). I've always thought like that too, so this guy seems really cool to me :).

On the technical side, He talked about the importance of taking advantage of the object system, and keep in mind that the dispatcher on message sends act as case statements, so we should use them as such. Minimizing logic in our code make it faster, more solid, and prettier.

We're following these slides mixed with these others.

While doing the lecture, he mentioned some cool books, some of them I already heard about (even read them), but others not, so I'm afraid my TOREAD list is about to grow a bit.

All in all, I had a really good time, and it's been only the first class!. It seems I'll be hacking some smalltalk in near future :)

Thanks to Jordi Delgado for making this possible, and to Stéphane for coming to Barcelona and sharing his knowledge.

Btw, if you don't know what is smalltalk nor who Stéphane Ducasse is, you should check pharo and you'll get a fair idea of what's smalltalk about and you'll be watching what is Stef working on.

viernes, 5 de febrero de 2010

Mysql from Perl

There's a lot of texts written about perl+sql . In fact there's a whole O'Reilly book about this.

But in perl, often the TIMTOWTDI motto fuzzies me a bit. So here's what I've chosen to use for my simple Mysql accesses (For complex and scalable things, there's DBIx::Class).

For small updates, or writting tests, you could go with plain DBD::DBI, but DBIx::Simple seems to fit better in my brain rules. There are plenty of well thought examples here.
my $dbh = DBIx::Simple->new(
$pwd, {RaiseError => 1}
#my $sql = SQL::Abstract->new;
my @fields = qw(codi A Br P S SA ZN e d);
my $result = $dbh->select('vGRID', \@fields, { idExp => $idExp, error => 0 }) ;

It's pretty confortable being able to use select, update, etc. as methods, and not bundled into strings. SQL::Abstract does a good job here too, giving the option to build hashes dinamically and passing to the select method.