Moving color spot

Enero 4, 2010

This one draws a moving spot where the pointer is at. The color changes with the position.
This is done by writing the circle code as a method of the class and passign as circle position paremeters the
pointer coordinates.


import gtk
import math

class Spot(gtk.DrawingArea):
def __init__(self):
gtk.DrawingArea.__init__(self)

self.connect("expose_event", self.expose)
self.connect("motion_notify_event", self.expose)
self.connect("motion_notify_event", self.draw)
self.connect("expose_event", self.draw)

def expose(self, widget, event):
self.context = widget.window.cairo_create()

self.context.rectangle(event.area.x, event.area.y,
event.area.width, event.area.height)

self.context.clip()

self.draw(self.context, event)
self.queue_draw()
return False

def spot(self, context, event, x, y , radius):

self.context.arc(x, y, radius, 0 , 2 * math.pi)
a ,b = self.get_pointer()
r2 = a*a + b*b
self.context.set_source_rgb(.1 + 100.0 /(a + .1), .1 + 100.0 /(b + .1) , .1 + 100 /(r2 + .1))

def draw(self, context, event ):

rect = self.get_allocation()
a ,b = self.get_pointer()
x = rect.x + rect.width / 2
y = rect.y + rect.height / 2
self.spot( self, context, a, b , 50)
self.context.fill()
self.context.set_source_rgb(0, 0, 0)
self.context.stroke()

def main():
window = gtk.Window()
spot = Spot()

window.add(spot)

window.connect("destroy", gtk.main_quit)
window.show_all()

gtk.main()

if __name__ == "__main__":
main()


Cairo polar coordinates and line width

Enero 2, 2010

This one changes line width of a circle if we pass near circle path.

import gtk
import gtk.gdk
import math

class Circulo(gtk.DrawingArea):
def __init__(self):

gtk.DrawingArea.__init__(self)

self.connect("expose_event", self.expose)
self.connect("motion_notify_event", self.expose)
self.connect("motion_notify_event", self.draw)

self.connect("expose_event", self.draw)

def pressing(self, widget, event):
self.pressing_x = event.x
self.draw(self.context)

self.queue_draw()

def expose(self, widget, event):
self.context = widget.window.cairo_create()

self.context.rectangle(event.area.x, event.area.y,

event.area.width, event.area.height)
self.context.clip()

self.draw(self.context, event)
self.queue_draw()
return False

def draw(self, context, event ):
rect = self.get_allocation()
xc = rect.x + rect.width / 2
yc = rect.y + rect.height / 2
x ,y = self.get_pointer()

x = x - xc
y = y - yc
ang = math.atan( x / y) * (math.pi/180.0)
rad = math.sqrt(x**2 + y**2)

self.context.set_source_rgb(0, 200 , 0)

radius = 80.0;
angle1 = 0.0 * (math.pi/180.0);
angle2 = 360.0 * (math.pi/180.0);
self.context.arc ( xc, yc, radius, angle1, angle2);

if math.floor(rad) in range (radius - 10, radius + 10) :

self.context.set_line_width ( 10.0)
else:
self.context.set_line_width ( 1.0)
self.context.stroke ()
self.context.fill()

self.context.stroke()

def main():
window = gtk.Window()
circulo = Circulo()
window.add(circulo)

window.connect("destroy", gtk.main_quit)

window.show_all()

gtk.main()

if __name__ == "__main__":
main()


SSH tunneling tip

Diciembre 28, 2009

When you have your router access denied fron Internet you can’t connect by HTTP to configure your router, but
there is a way to open your router Web interface by SSH tunneling(If you have an SSH server in your home LAN):

On your machine:

ssh -L 9999:192.168.1.1:80 user@your.router.internet.address

Now set up your browser to use 127.0.0.1:9999 as a proxy.

Now you can go to http://192.168.1.1 and you are in your router’s Web interface.


Simple piano keyboard in cairo

Diciembre 17, 2009

This is the cairo code of the simple piano interface shown in the figure. Its simple because keys are not
exactly disposed as in a real keyboard.

#! /usr/bin/env python
import framework
#from math import pi

class Transform(framework.Screen):
    def draw(self, cr, width, height):
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

        cr.translate(20, 20)
        cr.scale((width + 50) / 5, (height - 100) / 1.0)
        self.white_key(cr, .1)
        self.black_key(cr, .2)
        self.white_key(cr, .3)
        self.black_key(cr, .4)
        self.white_key(cr, .5)
        self.white_key(cr, .7)
        self.black_key(cr, .8)
        self.white_key(cr, .9)
        self.black_key(cr, 1.0)
        self.white_key(cr, 1.1)
        self.black_key(cr, 1.2)
        self.white_key(cr, 1.3)
        self.white_key(cr, 1.5)
        self.black_key(cr, 1.6) 

    def white_key(self,cr,pos):

        cr.set_line_width(0.01)
        cr.set_source_rgb(0, 0, 0)
        cr.rectangle(pos , 0,  .2,  1 )
        cr.stroke()
        cr.set_source_rgb(1, 1, 1)
        cr.rectangle(pos , 0,  .2,  1 )
        cr.fill()

    def black_key(self,cr,pos):

        cr.set_line_width(0.01)
        cr.set_source_rgb(0.0, 0.0, 0.0)
        cr.rectangle(pos  , 0 , .1 , .6  )
        cr.fill()
        cr.stroke()

framework.run(Transform)

Selecting Figures with PyCairo

Diciembre 15, 2009

The following code hilights the figure the pointer is on by changing the color.

El código siguiente cambia el color de la figura sobre la que se sitúa el puntero.


import gtk
#import gtk.gdk
import math

class SemiCirculo(gtk.DrawingArea):
        def __init__(self):
                gtk.DrawingArea.__init__(self)

                self.connect("expose_event", self.expose)
                self.connect("motion_notify_event", self.expose)
                self.connect("motion_notify_event", self.draw)
                self.connect("expose_event", self.draw)

        def expose(self, widget, event):
                self.context = widget.window.cairo_create()

                self.context.rectangle(event.area.x, event.area.y,
                                event.area.width, event.area.height)

                self.context.clip()

                self.draw(self.context, event)
                self.queue_draw()
                return False
        def arc_on(self, x, y, radius ):
                self.context.fill()
                self.context.set_source_rgb(0, 1, 0)
                self.context.arc(x - radius  , y , radius, 0  , 2 * math.pi)

                return False
        def rect_on(self, x ,y ):
                self.context.fill()
                self.context.set_source_rgb(0, 1, 0)
                self.context.rectangle(x, y , 40, 40)

        def draw(self, context, event):
                rect = self.get_allocation()
                x = rect.x + rect.width / 2
                y = rect.y + rect.height / 2
                radius =  50          

                self.context.set_source_rgb(1, 0, 0)
                self.context.arc(x - radius  , y , radius, 0  , 2 * math.pi)
                self.context.rectangle(x, y, 40, 40)

                R1 = radius
                a ,b = self.get_pointer()

                a = a - x + radius
                b = b - y
                dist = a**2 + b**2
                if dist < R1**2 :

                        self.arc_on( x, y, radius)
                if b in range( 0 , 40)  :
                        if a - radius in range ( 0, 40):
                                self.rect_on(x, y)

                a = a - 2 * x
                b = b - 2 * y

                self.context.fill()

                self.context.set_source_rgb(1, 0, 0)
                self.context.stroke()

def main():
        window = gtk.Window()
        circle1 = SemiCirculo()

        window.add(circle1)
        window.connect("destroy", gtk.main_quit)
        window.show_all()

        gtk.main()

if __name__ == "__main__":
        main()


Generando nombres de usuario

Diciembre 12, 2009

Me cansa perder el tiempo en estar pensando un nombre de usuario original cada vez que tengo que hacer un alta nueva así que mediante este script se pueden generar nombres de usuario combinando letras y vocales de manera que genera N palabras
de n sílabas. Las sílabas son de la forma . El siguiente paso sería hacerlo mediante combinaciones de sílabas pronunciables en Español.


#! /usr/bin/env python

import sys
import random

vowels = 'aeiou'
letters  = 'bcdfghjklmnpwrstvwxyz'

def get2rand(n, N):
	for i in range (0, N):
 		word = ''
		for i in range(0,n):
			letter = random.randint(0,  len(letters) -1 )
			vowel =  random.randint(0,  len(vowels)  -1 )
			word =  word +   letters[letter] + vowels[vowel]
		print word

#get2rand(3, 20000)
get2rand( int(sys.argv[1]), int(sys.argv[2]))

Un ejemplo de la salida del programa:


ruben@lap:~/src/python$ python names.py 4 30
yiwewuse
werorogo
biwoyici
wuromuye
jibikuro
rutuzaga
zizigefe
goninote
wubujuwa
jixopewa
hunozuzo
cesotuwi
yecujawo
xowunexe
biwoligu
faseziwa
fugirapo
hodehele
rahajemi
totecuwa
cupaleyu
pasimefi
jocexoyu
lawupogu
jiboneri
jebudeko
vozotuti
bizutofa
tawopope
paxoyuso


Generating usernames

Diciembre 12, 2009

I’m tired of thinking original user names anytime I have to make a new account so I made this script that generates user names
by combining N user names of n sylabes.


#! /usr/bin/env python

import sys
import random

vowels = 'aeiou'
letters  = 'bcdfghjklmnpwrstvwxyz'

def get2rand(n, N):
	for i in range (0, N):
 		word = ''
		for i in range(0,n):
			letter = random.randint(0,  len(letters) -1 )
			vowel =  random.randint(0,  len(vowels)  -1 )
			word =  word +   letters[letter] + vowels[vowel]
		print word

#get2rand(3, 20000)
get2rand( int(sys.argv[1]), int(sys.argv[2]))

Sample result:


ruben@lap:~/src/python$ python names.py 4 30
yiwewuse
werorogo
biwoyici
wuromuye
jibikuro
rutuzaga
zizigefe
goninote
wubujuwa
jixopewa
hunozuzo
cesotuwi
yecujawo
xowunexe
biwoligu
faseziwa
fugirapo
hodehele
rahajemi
totecuwa
cupaleyu
pasimefi
jocexoyu
lawupogu
jiboneri
jebudeko
vozotuti
bizutofa
tawopope
paxoyuso


Pygtk color changing widget

Diciembre 5, 2009

This widget changes its color whit the pointer movement.

import gtk
import math

class SemiCirculo(gtk.DrawingArea):
	def __init__(self):
		gtk.DrawingArea.__init__(self)

		self.connect("expose_event", self.expose)
		self.connect("motion_notify_event", self.expose)
		self.connect("motion_notify_event", self.draw)
		self.connect("expose_event", self.draw)

	def expose(self, widget, event):
		self.context = widget.window.cairo_create()

		self.context.rectangle(event.area.x, event.area.y,
				event.area.width, event.area.height)
		self.context.clip()

		self.draw(self.context, event)
		self.queue_draw()
		return False

	def draw(self, context, event ):
		rect = self.get_allocation()
		x = rect.x + rect.width / 2
		y = rect.y + rect.height / 2

		radius = min(rect.width / 2, rect.height / 2) - 5

		self.context.arc(x, y, radius, 0  , 2 * math.pi)
		a ,b = self.get_pointer()
		r2 = a*a + b*b
		self.context.set_source_rgb(.1 + 100.0 /(a  + .1), .1 + 100.0 /(b + .1) , .1 + 100 /(r2 + .1))
		self.context.fill()

		self.context.set_source_rgb(0, 0, 0)
		self.context.stroke()

def main():
	window = gtk.Window()
	clock = SemiCirculo()

	window.add(clock)
	window.connect("destroy", gtk.main_quit)
	window.show_all()

	gtk.main()

if __name__ == "__main__":
	main()

Changes color with pointer movement.


MANIFIESTO EN DEFENSA DE LOS DERECHOS FUNDAMENTALES EN INTERNET

Diciembre 3, 2009

Ante la inclusión en el Anteproyecto de Ley de Economía sostenible de modificaciones legislativas que afectan al libre ejercicio de las libertades de expresión, información y el derecho de acceso a la cultura a través de Internet, los periodistas, bloggers, usuarios, profesionales y creadores de Internet manifestamos nuestra firme oposición al proyecto, y declaramos que:

1. Los derechos de autor no pueden situarse por encima de los derechos fundamentales de los ciudadanos, como el derecho a la privacidad, a la seguridad, a la presunción de inocencia, a la tutela judicial efectiva y a la libertad de expresión.

2. La suspensión de derechos fundamentales es y debe seguir siendo competencia exclusiva del poder judicial. Ni un cierre sin sentencia. Este anteproyecto, en contra de lo establecido en el artículo 20.5 de la Constitución, pone en manos de un órgano no judicial -un organismo dependiente del ministerio de Cultura-, la potestad de impedir a los ciudadanos españoles el acceso a cualquier página web.

3. La nueva legislación creará inseguridad jurídica en todo el sector tecnológico español, perjudicando uno de los pocos campos de desarrollo y futuro de nuestra economía, entorpeciendo la creación de empresas, introduciendo trabas a la libre competencia y ralentizando su proyección internacional.

4. La nueva legislación propuesta amenaza a los nuevos creadores y entorpece la creación cultural. Con Internet y los sucesivos avances tecnológicos se ha democratizado extraordinariamente la creación y emisión de contenidos de todo tipo, que ya no provienen prevalentemente de las industrias culturales tradicionales, sino de multitud de fuentes diferentes.

5. Los autores, como todos los trabajadores, tienen derecho a vivir de su trabajo con nuevas ideas creativas, modelos de negocio y actividades asociadas a sus creaciones. Intentar sostener con cambios legislativos a una industria obsoleta que no sabe adaptarse a este nuevo entorno no es ni justo ni realista. Si su modelo de negocio se basaba en el control de las copias de las obras y en Internet no es posible sin vulnerar derechos fundamentales, deberían buscar otro modelo.

6. Consideramos que las industrias culturales necesitan para sobrevivir alternativas modernas, eficaces, creíbles y asequibles y que se adecuen a los nuevos usos sociales, en lugar de limitaciones tan desproporcionadas como ineficaces para el fin que dicen perseguir.

7. Internet debe funcionar de forma libre y sin interferencias políticas auspiciadas por sectores que pretenden perpetuar obsoletos modelos de negocio e imposibilitar que el saber humano siga siendo libre.

8. Exigimos que el Gobierno garantice por ley la neutralidad de la Red en España, ante cualquier presión que pueda producirse, como marco para el desarrollo de una economía sostenible y realista de cara al futuro.

9. Proponemos una verdadera reforma del derecho de propiedad intelectual orientada a su fin: devolver a la sociedad el conocimiento, promover el dominio público y limitar los abusos de las entidades gestoras.

10. En democracia las leyes y sus modificaciones deben aprobarse tras el oportuno debate público y habiendo consultado previamente a todas las partes implicadas. No es de recibo que se realicen cambios legislativos que afectan a derechos fundamentales en una ley no orgánica y que versa sobre otra materia.


Pygtk Window Coordintates

Diciembre 1, 2009

This widget displays a tooltip label whith the coordinates where the pointer is at.


#!/usr/bin/env python
# coordinates.py

import gtk

class Coordinates(gtk.Window):

    def __init__(self):
        gtk.Window.__init__(self)
        self.connect("expose_event", self.expose)
        self.connect("motion_notify_event", self.expose)

    def expose(self, widget, event):
        self.tooltips = gtk.Tooltips()
        x ,y = self.get_pointer()
        self.set_tooltip_text( str(x) + ',' + str(y))
        return False

def main():
    window = Coordinates()
    window.connect("destroy", gtk.main_quit)
    window.show_all()

    gtk.main()

if __name__ == "__main__":
    main()