El postre del amour

Como algunos sabeis, otro de mis hobbys es la cocina. Hace tiempo aprendi a hacer un postre que una amiga apodo ‘el postre del amor’ y desde ese momento lo bautice asi, por supuesto lo aprendi de mi madre, la gran maestra. Es un postre rapido, sencillo y rico. Ingredientes:

  • 2 Limones
  • 8 Yogures naturales (cada yogur 125gr, gracias Raquel!)
  • 1 Bote grande de leche condensada (Lata 397gr)
  • Azucar
  • Ron
  • Topping a elegir (pepitas de chocolate, lacasitos…) y Mikado

Limpiamos bien los limones y cogemos una fuente grande. Cogemos un rayador y rayamos la piel de los limones y la pone en la fuente. La rayadura cuanto mas fina mejor para que luego no se note demasiado. Una vez tenemos ambos limones rayados cogemos uno de ellos y lo exprimimos (si queremos mas sabor a limon, exprimir ambos). Echamos un chorrito de ron y vaciamos todos los yogures y el bote de leche condensada en la fuente. Removemos bien para que se mezcle todo bien y vamos añadiendo azucar y probando hasta que este al gusto.

Lo metemos todo en la nevera para que se enfrie. Una vez frio, lo echamos en un vaso y echamos el topping que queramos un palito de Mikado para decorar.

Por Copenhague ya estan disfrutando de ello, ¿o no Lucia? ;)

[HOW-TO] Creating a REST webservice with Python and Bottle

Nowadays there are mutiple web applications that need to provide an API to let the rest of the world interact with its services. One approach to achieve a fast, easy-to-develop and easy-to-use API is using REST.  If you don’t know what is REST about, I recommend you this video: An introduction to REST.

This time I am using Python to develop the example. We are going to need a python web framework called Bottle which makes the creation of the REST service a piece of cake. Bottle runs with Python 2.5+ and 3.x, make sure you are using a supported version. You can download Bottle from PyPI or install it via:

pip install bottle

Code is very straight-forward. We need to import bottle route, run and request. Each time we want to map a request, all we need is to define @route(‘/map’, method=’REST_METHOD’) above the method that will manage that request. For example: @route(‘/helloworld’, method=’GET’). That would take account of /helloworld and will generate a response for that request. Also, Bottle framework provides a method to wait and attend the requests: run(). It is configurable (host, port, server name…) but if you call it without parameters it will start a server listening to localhost:8080.

As a response, we should provide the requested information in JSON or XML format. Python has libraries to make this duty easy. These formats are used because they are easy to parse.

Bottle framework has capabilities to read from Cookies, HTTP Headers and Query Variables as well. There is more information about in http://bottlepy.org/docs/dev/tutorial.html. Here, there is a little example to create the REST API:

'''
Created on 26/06/2012
@author: Héctor Veiga. hveiga.com
'''
import bottle
from bottle import route,run,request

@route('/helloworld', method='GET')
def hello():
    return 'Hello World!'

 # JSON format response
@route('/book/:id', method='GET')
def book():

    return {'id':id, 'name':'A Game of Thrones: A Song of Ice and Fire'}

# Query string is /action?id=4&op=6. JSON format response
@route('/action')
def select_action():

    action_id = request.query.id
    option = request.query.op

    return {'action_id':action_id, 'option':option, 'result':'200 OK'}

# Image there is a text input named 'title' and a file input name 'image'
@route('/upImage', method='POST')
def upload_image():
    title = request.forms.title
    image = request.files.image
    if title and image and image.file:
        raw_data = image.file.read()
        filename = image.filename
        return 'Image uploaded!'
    return 'Something went wrong. Please try again'

[HOW-TO] Installing and using RabbitMQ in Ubuntu

 

 

RabbitMQ is a powerful open source messaging system that implements the Advanced Message Queuing Protocol (AMQP) standard. Nowadays, there are thousand of applications that need a reliable messaging service to queue, for example, requests. Amazon offers a messaging service called Simple Queue Service (SQS) which is suitable for little project where the message load is not very heavy.

Amazon’s SQS could seem very cheap ($0.01 per 10,000 Amazon SQS Requests)  but if your application is repeatedly checking for new messages from several queues, the cost starts to matter. RabbitMQ is the solution. RabbitMQ is fast, free, supports clustering, easy-to-use, easy-to-install… However, there is one point that you need to take special care: availability. High-availability comes for free with Amazon SQS. You can find more information about RabbitMQ vs SQS here.

Let’s install and configure. We need to add a new repository to download RabbitMQ, so let’s open a new terminal and run:

sudo pico /etc/apt/sources.list

This file contains the repositories sources. Move to the end of the file and write:

deb http://www.rabbitmq.com/debian/ testing main

Now we need a public key to avoid warnings, so run:

wget http://www.rabbitmq.com/rabbitmq-signing-key-public.asc
sudo apt-key add rabbitmq-signing-key-public.asc

It should have replied ‘OK’ when adding the key. So, let’s update and download RabbitMQ:

sudo apt-get update
sudo apt-get install rabbitmq-server

RabbitMQ comes with a handy tool called ‘rabbitmqctl’ to control the application (it must be used as root). To make our system a little more secure, we should set up a password for the ‘guest’ user. I am using ‘abcde’ as example. We can do this running:

sudo rabbitmqctl change_password guest abcde

Now everything is ready to start using it. Remember if you are using a remote server to open RabbitMQ’s default port 5672 in the firewall to accept connections. To test it, we are using the Official Java Client. You’ll need the libraries to run this code:

package com.hveiga;

import java.io.IOException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class TestRabbitMQ {

	private static String QUEUE_NAME = "TestQueue";
	private static ConnectionFactory factory = new ConnectionFactory();

	private static void init() {
	    factory.setHost("localhost"); // Host will be different if you are in remotes
	    factory.setUsername("guest");
	    factory.setPassword("abcde");
	}

	public static void send(String message) throws IOException {
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();
	    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

	    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
	    System.out.println(" [S] Message Sent: '" + message + "'");
	    channel.close();
	    connection.close();
	}

	public static void receive() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();

	    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

	    QueueingConsumer consumer = new QueueingConsumer(channel);
	    channel.basicConsume(QUEUE_NAME, true, consumer);

	    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
	    String message = new String(delivery.getBody());
	    System.out.println(" [R] Message Received: '" + message + "'");
	}

	public static void main(String[] args) {
		init();

		try {
			send("HelloWorld!");
			Thread.sleep(2000);
			receive();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

 

More example and different uses can be found in the official site. In addition, Spring framework contains some method to interact with RabbitMQ. More information about Spring with RabbitMQ can be found here.

ColdTrix Game Suite for MCF5272 in C

Back in 2010, my colleague and friend Luis Úbeda ( @lubeme23 ) and me developed a video game suite for ‘Digital Systems Laboratory’ (LSED) course in ETSIT-UPM. This course is based on creating a system (usually a game) using C for MCF5272 microcontroller (AKA Motorolla Coldfire). The student has to create the appropiate hardware and software to achieve it.

What we did? The basic assignment consisted in creating a similar game to the famous Tetris. We had to create a matrix of 8×4 LEDs to use as the board and manage it  using Coldfire. Game was controlled using a usual 12-digit keyboard that was managed by the Coldfire as well. In addition to the basic assignment, we decided to improve the system: we developed the Snake game for the same board, we put music to the games, we added a little LED matrix that showed you the next piece that was going to appear, added a voice read menu… Moreover, we tried to control the system using the PSP with infrared but we didn’t find out how to make it work in time (interruptions were behaving strangely!).

After many hours of development we finished. That hard work was worth because we learnt a lot and we got Honors in that course :) .

Now we have decided to publish the code under GPL license. Every comment and description is in Spanish. You can find it in Github: https://github.com/kec0/Coldtrix-Suite-Game

For ones who want to know the system deeper here it is the report of the system (also in Spanish): Coldtrix Suite Game Report

To sum up, this is a demo video we recorded:

LSED (‘Digital Systems Lab’ course at ETSIT-UPM): Tetris & Snake. Honors awarded.