Feeds:
Posts
Comments

2009

Para mi, el 2009 fue una extraña mezcla de felicidad, tristeza, alegría, desesperación, pasión, humor, logros, fracasos y crecimiento. Lo anterior puede sonar muy trillado, pero en realidad así fue.

Al comienzo del año y prácticamente hasta la mitad(días más, dias menos) viví digamos, demasiado cómodo, feliz, a gusto con mi vida, con mi familia, con mi pareja, con mi escuela; estaba yo tan feliz que en momentos llegué a pensar que algo grande estaba por ocurrir, no sabía si bueno o malo, pero muy en el fondo sabía que era algo, al menos, no tan bueno.

Y… ¡pasó!. A finales de Agosto surgió un asunto importante en la familia que hasta el momento no ha podido resolverse, motivo por el cual tuve que hacerme cargo de la familia. Y ahí fue cuando comenzó, digamos, la parte amarga del año para mi. No tanto por tener que dejar mis actividades, sino por otros hechos y detalles que no vienen al caso. Derivado de lo anterior, comenzaron los detalles con mi familia, enojos, regaños, gritos, peleas y demás mugres. Aunado a ello, surgieron igualmente problemas con mi novia, por tiempos, actitudes y demás cosas que venía arrastrando por obvios motivos.

A pesar de todo, creo que de toda la situación obtuve grandes cosas. Tuve que madurar todo lo que no había madurado antes, aprendí a escuchar, a calmarme, a tomar decisiones fuertes de las que otras personas dependen, aprendí a administrar mis finanzas(y de la familia) y me empapé de mundos nuevos para mi.

Hasta hace unas semanas me acomodé a mi nueva situación, si, apenas después de meses y meses de no saber como actuar y organizarme. El fin de año me cayó de lujo, vino a darme cierta paz que no encontraba dados los radicales cambios en mi vida. Y todo gracias a la ayuda, entendimiento y soporte de mi familia, de mi novia y de mi nueva y renovada Fe en Dios(no, no fui a pare de sufrir, sigo siendo, como siempre, Católico).

A pesar de todo y de las situaciones que aún tengo que manejar, espero y tengo mucha Fe en que el 2010 será un buen año para mi y los mios. Siento que así será, tal vez por el cansancio de cargar con todo lo malo de mi segunda mitad de 2009, tal vez porque estoy harto de eso, quiero pensar que así será éste nuevo año… sé que así sera.

Un saludo a todos y mis mejores deseos para el año que comienza, que esté plagado de logros y alegrías para todos ustedes.

Signing Java Applets

When you need that your applet uses some features like access to client machine files or remote files outer applet base directory it’s mandatory to configure the client virtual machine to allow this(craziest thing) or sign our applet and hope that the user click over «Run» button that appears after the applet loads. Of course the last one option it’s best just because practical reasons.

Now, imagine that we already finish our applet, now we have to pack it to a jar file, that’s just a zip format file with the extension jar. How do that?, simple!, imagine that we gonna pack the ImageViewer applet:

$ jar cf ImageViewer.jar ImageViewer.class ImageTest.jpg

Remember that $ it’s your terminal, command line or whathever prompt, so, don’t write it. The command it’s so simple jar, and the options are «c» that means create a new jar file and «f» means that we gonna indicate the name of the new jar file, in this case «ImageViewer.jar». Next we have ImageViewer.class and ImageTest.jpg which are the files that our applet needs to run. That’s all! now we have a jar file. An important thing to do it’s modify our html page(here just the applet tag) that used to be:

<applet code="ImageViewer.class" width="320" height="240"></applet>

Now become:

<applet code="ImageViewer.class" archive="ImageViewer.jar" width="320" height="240"></applet>

Notice that just added the «archive» stuff, it says to web browser where to find the jar file.

But still we have an unsigned applet, to sign we need first to generate a key, yep, just like our ssh keys and that.

$ keytool -genkey -alias "deathwarrior"

The keytool app it’s provided with the JDK and the options are genkey to(guess what?) generate key and alias which it’s a name that identify that new key, next several data are asked as well a password to secure our keystore and a password for the new key(yes, could be the same).

Now our key is created, let’s sign our applet:

$ jarsigner ImageViewer.jar deathwarrior

Again, jarsigner it’s JDK provided, ImageViewer.jar it’s the jar file that we want to sign and «deathwarrior» it’s the alias of the key which will be used to sign the jar file.

We already done!. Now the applet could be authorized by the user just clicking on the «Run» button and we have access to certain options limited by default.

Hope be helpful.

Greets.

El Orden de los Factores

@cliente: ¿De qué jabón tienes?.
@tendera: Ahorita nada más tengo Maestro Kilo de a Limpio.

Es verídico… LOL

Now we are back to the Applet’s World, Yay!. Let’s write some little app which just load an image and show us.

If you don’t know which’s the basic structure of a Java Applet, please read this first.

First of all, we need to import our basic libraries to work, so, the begin of your file, let’s say ImageViewer.java needs to looks like:

import java.applet.*;
import java.awt.*;

Next it’s needed to declare our class, remember that Java just allows one class per file and the class must be named exactly like file(or file like class), then you now have next thing:

import java.applet.*;
import java.awt.*;

public class ImageViewer extends Applet
{
}

The extends Applet thing it’s just a manner to say: hey!, Applet it’s my daddy and because of him I got his whole properties and habilities.

In this specific case, we gonna need three applet specific methods: init, start and paint, but before that, let’s declare the variables that we are gonna use.

import java.applet.*;
import java.awt.*;

public class ImageViewer extends Applet
{
    int maxX, maxY;
    Image image;
    MediaTracker mt;
}

The two integer variables are used to store the image width and height respectively. The Image class variable are used to store the information of the image that can be painted on the screen. And the MediaTracker variable is used to “track” some aspects of media, you’ll see it’s utility after.

Going to our first method: init().

As you can remember, init() method is executed when the applet is created, so we can look it like a “contructor”.

public void init()
{
    showStatus("Getting image...");
    mt = new MediaTracker(this);
    image = getImage(getDocumentBase(), "ImageTest.jpg");
    mt.addImage(image, 0);
}

The showStatus thing show us a message in the web browser status bar.
MediaTracker stuff creates a new object of the named class, and the only parameter to the constructor is this, if we read the java documentation says that MediaTracker contructor receives an ImageObserver variable type, but… let’s leave that for another season, in this case(and in every Applet AFAIK) just pass this.
The image line says that obtain an image with absolute path based on getDocumentBase() (this is a URL, not a String) and relative path “ImageTest.jpg”. Here it is an important thing, the getImage method returns inmediatly and it doesn’t care if the image exists, is loaded and other important things that really matters, and that’s the reason of MediaTracker to be, besides we can always use images without MediaTracker but it’s not really sane.
mt.addImage(image, 0) adds the image that just said to load into MediaTracker so we don’t loose the clue of it, the second argument it’s an integer used as a “group identifier”, normally set to zero.

Next is start() method, this is called afted init() method.

showStatus("Loading image...");
try
{
    mt.waitForAll();
}
catch(Exception e)
{
    e.printStackTrace();
}
while(!mt.checkAll(true))
{
}
imageX = image.getWidth(this);
imageY = image.getHeight(this);
showStatus("Resizing Applet image size: " + imageX + "x" + imageY);
resize(imageX, imageY);

showStatus() again.
Inside the try block we can find mt.waitForAll() which starts to load all images registered into MediaTracker.
The while loop with the mt.checkAll(true) check if all images are loaded and the parameter true said that if some are not loaded, then load!, that’s why inside the loop, to wait until every image are ready.
Next lines just store the width and height of the image then we paint in status bar the dimensions and then resize the applet to fit the image to it.

paint() method do that: paint the image on the screen, of course, first we inform to user that we’re going to paint it, and then paint the image.

That’s all!. Now you have complete code:

import java.applet.*;
import java.awt.*;

public class ImageViewer extends Applet
{
    Image image;
    int imageX, imageY;
    MediaTracker mt;

    public void init()
    {
	showStatus("Getting image...");
	mt = new MediaTracker(this);
	image = getImage(getDocumentBase(), "ImageTest.jpg");
	mt.addImage(image, 0);
    }

    public void start()
    {
	showStatus("Loading image...");
	try
	    {
		mt.waitForAll();
	    }
	catch(Exception e)
	    {
		e.printStackTrace();
	    }
	while(!mt.checkAll(true)){}
	imageX = image.getWidth(this);
	imageY = image.getHeight(this);
	showStatus("Resizing Applet image size: " + imageX + "x" + imageY);
	resize(imageX, imageY);
    }

    public void paint(Graphics g)
    {
	showStatus("Drawing image...");
	g.drawImage(image, 0, 0, this);
    }

}

It’s fun to look the applet doing nothing but painting an image, but it’s a nice start, maybe you can figure out how to make a simple game.

Greets.

Hi again fellows. Well this time bringing to you the marvelous method to upload a file through Ruby CGI, yep, as you seen on… well I don’t know where.

If you dont know how to make a basic CGI app in Ruby, please read this.

Now, if we have the next HTML form to upload files:

<form method="POST" enctype="multipart/form-data" action="uploader.rb">
<label>File:<input type="file" name="file" size="100"/></label> <br />
<input type="submit" value="Go!" />
</form>

It’s easy to know which that form sends the data to uploader.rb. So let’s take a look into that Ruby script.

#!/usr/bin/env ruby

cgi = CGI.new
puts cgi.header
params = cgi.params

So far nothing new. But now lets check if someone send us a file:

if params.has_key?"file"
 #do something with that
end

Again, nothing new. Now comes funny part.

file = params["file"].first
server_file = 'files/' + file.original_filename

First line takes a Ruby object of a class StringIO(not String!) that’s something like a mutant, a mix between an IO object and a String, but none of them… weird class, here is the file that user uploads.

Second line it’s the name(path included) which we are to save the file into the server, yes, this is just a String.

Now we want to save the file in the server, to do that we just take the original file and write it’s content to the server file:

File.open(server_file.untaint, "w") do |f|
    f << file.read
end

Now the job it’s done, your code now looks like:

#!/usr/bin/env ruby

cgi = CGI.new
puts cgi.header
params = cgi.params

if params.has_key?"file"
    file = params["file"].first
    server_file = 'files/' + file.original_filename
    File.open(server_file.untaint, "w") do |f|
        f << file.read
    end
end

Now you can do something with that file.

Happy hacking!.

Ruby CGI’s

Hi all. After a long time without publish any tech doc, I’m back!.

Today will see how to use Ruby(yes, Ruby) to make our CGI tools. As you already know, CGI’s are traditional written in Perl, but if we check some Ruby’s history we can find next statement:

Ruby takes best of several worlds: Perl, Python and SmallTalk

So if we have best of Perl I think we have powerful CGI’s.

First of all we need to know that just a few free hosting services provide Ruby as an allowed scripting language, but we can always get cheap hosting(I got mine into 1 USD per month). Besides you can use your own webserver.

Suppose that we already configure our webserver to execute CGI programs, so let’s write code!.

Every script that you write into an interpreted language begins with a line like this:

#!/usr/bin/env ruby

which says: hey! run my amazing code with Ruby(this specific case).
Now you can start write your pages in a similar way what you do into PHP, except you have to require an specific library to make the work less painful: cgi(hard to figure out, isn’t?).

#!/usr/bin/env ruby

require 'cgi'

cgi = CGI.new

Last line of code it’s just used to create a new object of class CGI.

Now, as HTTP protocol requires, our script must send the headers to web browser, if we need a custom headers must read some RFC’s and that boring stuff, instead just tell Ruby to send “standard” headers doing:

puts cgi.header

By the way, if we need to print some to the webpage just do like if you print something into terminal, I mean puts, print, printf and a lot of functions which Ruby provides.

At this point your code looks like:

#!/usr/bin/env ruby

require 'cgi'

cgi = CGI.new
puts cgi.header

Now let’s try something more interesting, assume that we got some parameters from a webform, let’s say we asked to user… mmmh, name and email, classic fields in a webform.

In HTML code the form looks like:

<form method="GET" action="myRubyScript.rb">
<label>Name: <input type="text" name="name" /></label>
<br />
<label>Email: <input type="text" name="email" /></label>
</form>

If the above form sends data to our script, then we need to catch and do something with it. So do the next thing:

params = cgi.params
name = params["name"][0]
email = params["email"][0]

May you think what if I need to check the existence of some params?, well we can do that:

params = cgi.params
name = params["name"][0] if params.has_key?"name"
email = params["email"][0] if params.has_key?"email"

Nice, isn’t?. But now you can think… Yep, params it’s a Ruby hash(like an associative array in PHP), why are we processing it first like a hash and then like an array?. Well, the answer comes really faster and hits you hard…

What happened if the parameter values are several to the same parameter name?. Well, Ruby can manage that stuff, that’s why Ruby stores an array as a value of a hash. So if someone passes several names like Sheldon, Raj, Leonard and Howard we can access pretty easy:

params = cgi.params
name1 = params["name"][0]
name2 = params["name"][1]
name3 = params["name"][2]
...

Some of you can ask how Ruby figures out if the request was made by POST method or GET method, well, at this point Ruby takes every request type as the same. But if you wanna look which type of request the client did you can check it like this:

case env_table['REQUEST_METHOD]
when "GET"
#Do something with GET
when "POST"
#Do POST stuff
end

So, do you think that Ruby CGI stuff is really hard?.
Please take a look into Ruby CGI Library Documentation

Greets folks!

Adicción

@dw: Eres una adicta a internet.
@la: No soy adicta…
@la: …sólo lo necesito

Miyagi Designer

I’m trying to figure out if Mr. Miyagi was really one of the designers of the marvelous game Tumblepop. My little bro told me that Miyagi’s real name(Noriyuki Morita) appears at final credits of the game, I ran to play and finish it so I can take a nice screenshot. Just look at it!.


Mayito…

Sé que ahora estás mejor, sé que ahora no sufres más y sé que le ibas a «La Piedá». También hoy es cumpleaños de mi hermano; mi papá(tu hermano) no está aquí, pero sé que lo siente y que no se olvidará nunca de ti. Ayer viniste a visitarnos, algo sentías, lástima que yo no estuve, espero que nos podamos encontrar algún día.

«¡¿Qué, quieres que te rompa tu madre?!»

M.P.G.

Hay un ejercicio interesante dentro de un libro de física moderna[1], del cual tomaremos la siguiente información:

El ojo humano, bajo condiciones favorables, puede detectar una energía de E=10^{-18} J . Pero… ¿qué tanto es eso?. Bueno, veamos, se supone que una dieta «normal» debe ser de más o menos 2000   calorías. Pero, hay un detalle con el término caloría usado en alimentos. Ellos llaman caloría a lo que en realidad es una «Caloría Grande» es decir, 1000 calorías de esas que enseñan en la escuela, por lo que si la dieta es de 2000 cal , en realidad son 2000x1000=2000000cal o lo que es lo mismo, 2 millones de calorías. Poniéndolo en términos de notación científica sería 2000000cal = 2x10^{6}cal . Pero en el SI(Sistema Internacional), la energía se mide en Joules, donde 1cal = 4.18J , por lo que 2x10^{6}cal = 8.36x10^{6}J , o sea, casi 8 millones y medio de Joules.

Ahora comparemos el dato de la energía que puede detectar el ojo humano 10^{-18}J con lo que debemos ingerir en una comida, que son 8.36x10^{6}J tenemos \frac{8.36x10^{6}J}{10^{-18}J} = 8.36x10^{24} que es 836 seguido de 22 ceros, que puesto en letras sería «ocho cuatrillones trescientos sesentamil trillones» de veces. Es decir, el ojo humano puede detectar una «cuatrillonésima parte» de la energía que ingerimos en una comida. ¿Interesante, no?.

El ojo humano detecta longitudes de onda de entre 400 y 700 nanómetros, si tomamos el promedio, sería \lambda = 550nm . Ahora bien, tomando un poco de física moderna, sabemos que la energía está dada del siguiente modo: E = h \nu . Donde h = 6.63 x 10^{-34}Js es la constante de Planck y \nu es la frecuencia, en éste caso específico, de la luz. Pero también sabemos, del estudio básico de ondas, que \nu = \frac{c}{\lambda} , donde c = 3x10^8 m/s es la velocidad de la luz y \lambda la longitud de onda, por lo que, sustituyendo en la fórmula de la energía, tenemos E = \frac{hc}{\lambda} . Ahora supongamos tratamos con un solo fotón, y que ese fotón tiene una longitud de onda en el rango de funcionamiento del ojo humano, llamémosle a esa energía E_{\gamma} por estar los rayos gamma compuestos de fotones. Por lo que la energía de un fotón con \lambda = 550nm = 5.5x10^{-7}m es E_{\gamma} = \frac{hc}{\lambda} y sustituyendo los valores tenemos

E_{\gamma} = \frac{(6.63x10^{-34}Js)(3x10^8m/s)}{5.5x10^{-7}m}

y resolviendo la operación se obtiene que la energía del fotón es

E_{\gamma} = 3.6x10^{-19}J

Y sabíamos ya que la energía mínima que puede detectar el ojo humano es de E_{T} = 10^{-18}J donde E_{T} es la energía total que puede captar el ojo y ésta tiene que ser un múltiplo de la energía de un solo fotón, ya que, al menos, la luz que ve el ojo tiene eso, un fotón. Expresándolo de otro modo queda

E_{T} = nE_{\gamma}

Es decir, la energía total es «n veces» la energía del fotón. ¡Tan sólo nos queda despejar para saber cuantos fotones podemos ver!.

n = \frac{E_{T}}{E_{\gamma}}

Y sustituyendo las cantidades que obtuvimos

n = \frac{10^{-18}J}{3.6x10^{-19}J}

n = 2.7 \approx 3

una cantidad sin unidades. Traducción:

¡El ojo humano es capaz de detectar 3 fotones!.

Creo que éste hecho es bastante interesante. Lo único que no me queda claro, es de donde saca el libro que el ojo humano puede detectar 10^{-18}J, sería bueno encontrar una referencia por ahí.

Saludos.

Update: Gracias a Clmns por las correcciones de escritura.

[1]Concepts of Modern Physics. Beiser, Arthur. 1963, McGraw-Hill, USA. pp. 59.

Older Posts »