Mostrando las entradas con la etiqueta linux. Mostrar todas las entradas
Mostrando las entradas con la etiqueta linux. Mostrar todas las entradas

viernes, febrero 22, 2008

Power management on linux

One of the biggest issues on linux is the power management, especially if you have laptop (that probably didn't came with linux preinstalled).

I always recommended the suspend2.net patch for the kernel, the patch now is called tuxonice, this comes with a pretty good set of scripts to interact with this (apt-cache search tuxonice), but the ugly part of this solution is that you must recompile a clean kernel, with clean i mean the kernel.org official release, because if you try to use the sources provided by your distribution you will have troubles applying the patch (offset isues) and it will be necessary that you change the source code manually, so this is a looong way, but i strong believe that the tuxonice is pretty good for strange hardware. But some days ago i recompiled the v2.6.24 kernel + tuxonice patch, it took me a few hours of cpu, and the result was a fully functional kernel, but with a very pour hard disk I/O performance:
v2.6.23-1-686:

# hdparm -t /dev/hda 
/dev/hda:
Timing buffered disk reads: 110 MB in 3.02 seconds = 36.37 MB/sec

v2.6.24tuxonice
# hdparm -t /dev/hda 
/dev/hda:
Timing buffered disk reads: 14 MB in 3.05 seconds = 4.59 MB/sec


so it became pretty useless, that make me dedicate time to make works the uswsusp way (integrated into the kernel.org and obviously present in the the debian kernel package, and probably in almost any distribution).

The simple way of do this in debian is

# apt-get install uswsusp pm-utils

with this we install the uswsusp support and associated tools, then it's necessary configure it with:
#dpkg-reconfigure uswsusp


if you use ndiswrapper for your wireless card, you need to tell to the power-management that unload the ndiswrapper module before it starts the hibernate, you can do this with the following line inside the /etc/pm/config.d/unload_modules file
SUSPEND_MODULES="ndiswrapper"


now you must test the kernel functionality with the following commands 's2disk' and 's2ram' (the first for suspend to disk and the second one for suspend to ram)

if it works, now you mus test the pm-utils with equivalent commands 'pm-hibernate' and 'pm-suspend', these tools are wrappers to the underlying kernel functions, if it worked now the last step is authorize the users to use these shiny new features, for this you just need to add the username to the powerdev group, for example if the user is foobar you must type the following command:
# adduser foobar powerdev


now you restart the session to let changes apply (maybe you will need to reboot your computer to the changes made to the kernel were refreshed) and try to use your {gnome | kde | any-other}-power-manager tool

martes, enero 22, 2008

Mouse usb en notebook

One of the things that are irritating is when you attached a usb mouse to the notebook y start to write something (like this entry) and the palm of the hand touch the touchpad y the focus change, so what for do i want keep my touchpad enabled if i am using the usb mouse?, well with the help of udev (thanks linux) i create a rule to avoid that ugly behavior


freyes@yoda:~$ cat /etc/udev/rules.d/01-touchpad.rules
ACTION=="add", SUBSYSTEM=="input", ID_CLASS="mouse", RUN+="/usr/bin/synclient TouchpadOff=1"
ACTION=="remove", SUBSYSTEM=="input", ID_CLASS="mouse", RUN+="/usr/bin/synclient TouchpadOff=0"


The first rule disable the mouse when some usb mouse is attached to the system, and the second one enable it when the usb mouse y removed.

Remember to put shared memory config option in your xorg.conf


Section "InputDevice"
Identifier "Configured Mouse"
Driver "synaptics"
Option "Protocol" "auto-dev"
Option "SHMConfig" "on"
EndSection

Of course, you can have a lot more tweks to your config, but the bold option must be present.

jueves, diciembre 27, 2007

Rascase, a very simple tool

I've not talk much about Rascase here, but now i'm gonna explain some things where i am working on.

Rascase is mainly two things, the first one 'is my project degree to obtain my title degree of ingeniero ejecución en computación e informática (aka computer engineer)', and the second one 'is a simple CASE tool for linux to design Entity-Relationship models'.

Currently I am finishing the document to present it for corrections, these are made by a group of designed teachers (correctors teachers), they will return it to me on march (probably at the end of march), then a apply the corrections to the document and then wait for defend my project.
On the software side, rascase currently is less than a drawing program, still there is a lot of things hardcoded, but in february it must be functional tool, a really CASE tool.

Rascase will use the philosophy 'just to use', because the time don't let me develop a complete and powerfull tool like 'powerdesigner' is, but this will be just a stop on the road, i mean this will be just the first release (and i hope not the last to), my expectations are huge :)

A few thecnical details about the technologies involved in the development of the project:

  • The interface is designed using glade (3.4), the are some parts made by code, especially the canvas setup and a minor details.
  • The pattern design is MVC++, a MVC based pattern, defined by Ari Jaaksi (part of the development group of nokia internet tablet n770, n800, n810, and others things inside nokia)
  • The programming language is Python :)
  • Libraries used
    • PyGTK, nothing to say about this :P
    • PyODF, a python library to make documents with OpenDocument Format, i'm using it to generate the data dictionaries in ODT format
    • PyGoocanvas, the bindings of goocanvas, and this is a canvas library is based in cairo

  • The source code is managed using git, the great distributed version control system


A shot of the curently state of rascase, just a functional interface without logical code. (aka mockup of prototype :P)

lunes, diciembre 24, 2007

Fucking ndiswrapper

Fucking ndiswrapper :-\

viernes, diciembre 07, 2007

Herramienta para Diagramas de secuencia

Hoy me cansé de las herramientas pussy (aka ide-all-in-one-use-just-the-mouse) y comencé a utilizar una herramienta a lo menos poco usual, pues consiste en que el diagrama de secuencia lo programas, es decir, escribes la logica del diagrama y la herramienta se encarga generar la gráfica :) con eso me olvidé de esos problemas malditos de 'quedó un poco corrido', 'quedo desalineado', etc..

Una muestra del primer diagrama que hice y me tomó solamente unos 10 minutos, entre cranearme la lógica del diagrama de secuencias y aprender la sintaxis (que por cierto un muy pequeña)
con el siguiente script

Usuario:Actor
x:ViewMainWindow ":ViewMainWindow"
y:y ":ControlMainwindow"
z:z ":Project"
a:a ":ControlSaveFileDialog"
b:b ":ViewSaveFileDialog"

Usuario:x.Abrir Proyecto
x:models=y.open_project()
y:a.ControlSaveFileDialog()
a:path=b.ViewSavefileDialog
y:path=a.get_path()
y:z.new Project()
y:models=z.get_model_list()


Para obtener como resultado esto otro


Definitivamente una herramienta que apunta a la productividad.

100% recomendada, el sitio de la herramienta es: http://sdedit.sourceforge.net

A pesar de que está en Java con swing, me gustó caleta :) quizás podria algún día reescribirla en pygtk xD e integrarla a mi herramienta case :D alguien se anota para esa feature :P

domingo, diciembre 02, 2007

Emacs recargado

I'm still fascinated with the power of Emacs, it's amazing how a big group of hackers (real hackers)could develop a wonderful multi purpose tool, especially oriented to programming tasks.

The key of emacs is elisp, a functional programming language (I really hate the functional languages, but this one it is not a pain-in-the-ass like SML).

I didn't read any elisp book or tutorial, but i could made some customizations of my environment, especially with the help of jonathan (a member of the rizoma-devel crew) and emacswiki.

Today i started to improve emacs for develop python scripts, and this is the result

That is a shot of a python script evaluated (at write-time) with pylint

Now if you are developing software, probably you will need the api documentation, wel with emacs you can have the python help embedded in the main window, so if you are on a word with simple customizable shortcut you can display it like in the image:


There are another tricks that I applied to my .emacs file, i'll let them available in some website soon.

martes, noviembre 27, 2007

Emacs con antialias

Hoy me tomé unos minutos para continuar con el tuning de mi emacs, ya antes había pasado por aplicar happyemacs que ayudó rápidamente a dejarlo apropiado a las necesidades de un programador. Pero esta vez opté por algo menos útil a primera vista, aunque sumamente agradable a la estética y al descanso de los ojos, pues esto es texto con suavizado de bordes, mejor conocido como antialias :)

Pues bien no hay nada mejor como un par shots para que noten la diferencia (parecerá publicidad de slim center xD)


Antes



Después


La receta para esto es la siguiente (para ubuntu):
Agregar el repositorio de AlexandreVassalotti:
deb     http://ppa.launchpad.net/avassalotti/ubuntu feisty main
deb-src http://ppa.launchpad.net/avassalotti/ubuntu feisty main


Aplicar
# apt-get update && apt-get install emacs-snapshot emacs-snapshot-el


con eso instalarán la versión de cvs empaquetada, con soporte de Xft, que es el que dá el soporte de antialias.

Ahora es necesario darle unos pequeños tweaks al Xresources para indicarle a emacs la tipografía que debe usar, si activar o no el antialias, etc..
Aquí está mi Xresources

freyes@yoda:~$ cat .Xresources
Emacs.font: DejaVu Sans Mono-10
Xft.antialias: 1
Xft.dpi: 96
Xft.hinting: 1
Xft.hintstyle: hintfull

Habla por sí sola, para mayor información dirigete a tu buscador favorito.

Una vez que terminaste de editar tu Xresources debes recargar el archivo para que la X tome esta nueva configuración y eso se hace de la siguiente manera:
xrdb -merge ~/.Xresources


Y ahora puedes ejecutar emacs :)

Estadistica con postgresql

Postgresql es una potente base de datos relacional orientada a las transacciones, es decir, si quieres hacer BI tas cagao :-D
Dentro de las cosas más rulez que tiene postgresql está su capacidad de para hacer procedimientos almacenados que dentro del mundo postgres son conocidas simplemente como funciones (un procedimiento es una función que retorna void :) just like in C), probablemente estés pensando "la media wa con mi sql server de 5 millones de pesos puedo hacer lo mismo con un lindo TransactSQL", pues tienes razón, pero a medias, porque las funciones en postgresql las puedes programar con plpgsql que es el lenguaje nativo para hacer funciones, pero además si consideras que puede ser lento o simplemente no se ajusta a tus necesidades es posible programar las funciones con C, Python, TCL, Java, Perl, R y otros más, traten de hacer eso son Sql server xD

quisiera determe en R, porque cuando tienes una base de datos y deseas obtener _información_ a partir de esos datos debes comenzar a aplicar métodos estadisticos, pues bien ahora eso se vuelve tribial si usas R :) tiene funciones para todas las cosas de estadistica que se te puedan ocurrir percentiles, mediana, etc...es como el equivalente a python para el mundo de la estadistica

Totalmente recomendado aprender a usar R desde postgres para que puedan hacer lindos reportes para sus jefes y por cero peso, y quizás como los hacen ahorrar en licencias usen ese dinero para enviarlos a capacitación en gringolandia o algún otro lugar XD

Como una muestra del nivel de R es que en la nasa lo usa.

nota: hoy mientras tenia estacionado mi nick en el canal #postgresql-es de freenode un tipo pegó este link -> http://pastebin.ubuntu.com/2279/ nada que decir :D solamente hilarante jajaaj

jueves, noviembre 15, 2007

Banco de chile de y su servicio internet

Hoy activé mi cuenta de banco para acceder a los servicios internet y todo bien hasta que el asistente telefónico me dijo que debia usar internet explorer para dar de alta mi cuenta y ahi saqué mi carta bajo la manga y le dije que usaba otro navegador (sin entrar en detalles filosofales que no venian al caso), pero que no se preocupara ya que habia usado el portal internet del banco con navegadores 'alternativos' y funcionaba todo bien, pero el me contrataca diciendome 'lo que pasa es que cuando se de de alta la cuenta se le hacen preguntas de seguridad y luego al finalizar debe aparecerle un mensaje avisandole que el cambio de clave fue exitoso, mensaje que _solamente_ se puede ver en internet explorer, los otros navegadores no lo muestran ycuando trata de entrar con su nueva clave no podrá hacerlo, ni tampoco con la clave vieja", lo cual provocó un "WTF?" del porte de un buque.

Primero, dedito para abajo que la cuenta quede en el limbo al usar otro navegador, eso muestra claramente que la transacción que se procesa para activar la cuenta no es atómica.

Segundo, doble dedito para abajo el hecho que sepan el bug, esté documentado el bug, y no sean capaces de repararlo.

En chile, desde mi punto de vista, siempre han sido relativamente neutrales frente a los ojos de los clientes, es la primera vez que vivo una situación así, si bien no es tan grave como si me hubiera dicho que no puedo ocupar el portal sin explorer (recuerdan el caso DEMRE+PSU+firefox?)
creo que cuando tenga tiempo mandaré un mail al soporte del banco para noten la molestia.

Escuchando: OST The lord of the rings

martes, noviembre 13, 2007

Ares nativo en linux

para los que usan ares, o les gustaria usarlo en linux (JP?, nico?) les recomiendo que lean ares en ubuntu-kubuntu sin wine, ya que existe un plugin de gift que implementa el protocolo de ares

viernes, octubre 26, 2007

Linus habla sobre git

A todas las personas que les interesa interiorizarse sobre los SCM (Source Code Management) les recomiendo ver la charla de que dio linus en google (en inglés of course :P)
Gracias a ese video pude entender la manera en que está configurado git para gestionar el kernel, ahora sé algunas utilidades que dá el DSCM versus un sistema centralizado.

el problema que me ha provocado es "que mierda uso para gestionar el código de mi proyecto de título" :(

SVN es simple, lo conozco y sería sencillo conseguir hosting para el código (linuxdiinf, sf.net, berlios, etc), PERO es molesto que los branchs sean globales y no se pueda hacer branches locales para trabajar, además que debes estar conectado para hacer los commits y otras operaciones

GIT es relativamente simple, pero no lo conozco, no sé en donde podría conseguir hosting para git

oh!, dear lazy web, conoces algún servicio de hosting de git? :P

sábado, septiembre 29, 2007

Cosas que un desarrollador debe saber

Es habitual que cuando uno aprende a programar (ya sea educación formal o autodidacta) en lo que se pone énfasis es en el lenguaje, es decir, la controles de flujo, las iteraciones, etc. Luego cuando uno domina eso y comienza a desarrollar programas más grandes y comienzan a aparecer errores difíciles de encontrar lo que uno instintivamente hace es comenzar a poner print's (printf(), writeln, etc.) de la variables de interés, luego cuando son problemas más complejos y que hacen uso intensivo de cpu y uno busca mejorar el rendimiento (algoritmos golosos, dividir para conquistar, programación dinámica, etc.) nuevamente se echa mano a los print's y más o menos calcula en que parte se tarda más en pasar el flujo (los más avezados imprimen la hora y los aún más avezados hacen un difftime), PERO ¿por que mierda, los profesores, no nos dicen que existen herramientas para hacer lo mismo?. Yo en la universidad nunca le escuché a hablar a un profe del profiling, de usar un debugger, etc.

Pues bueno aquí va un pequeño esbozo de en que momento usar que cosas:

Si tu programa tiene errores y hace cálculos absurdos, lo que debes utilizar es un debugger, con eso puedes hacer lo mismo que con los print's (pero sin contaminar el código con print's) y muchas otras cosas más, como por ejemplo cuando tu aplicación se va de sgfault puedes imprimir el stack, puedes ver los valores que habian en las variables antes del segfault, puedes poner breakpoints (un breakpoint es un punto del código donde se queda en pausa el código y puedes comenzar a ejecutar step-by-step o hasta el siguiente break, etc.). Traten de hace eso con solamente print's XD. La primera vez que usen el debugger les quitará harto tiempo en aprender las cosas básicas (en especial si usas gdb como los machitos, aka sin-gui :P), pero a largo plazo el beneficio es enorme. (si usas python te puede interesar ver Introducing the pydb Debugger)

Si tu programa ha crecido y comenzó a ponerse un devorador de memoría y/o cpu, pues entonces haz profiling de tu aplicación :) y el profiling es aplicable también a la red (en caso de que tu software haga uso de ella), los datos obtenidos los podrás graficar y análizar los casos en que tu aplicación se pone lenta etc. (si les interesa el tema les recomiendo el video Linux.conf.au Profiling Desktop Apps)

Eso fue el consejo del día de hoy :P

PD: se dice que el profiling en linux es algo limitado debido a la falta de hooks en el kernel, pero eso no me consta empíricamente :P
PD2: más información en wikipedia: Performance analysis y Debugging

viernes, septiembre 21, 2007

Haz tus documetos OpenDocument desde Python

Eso, mediante una libreria llamada odfpy es posible generar archivos ODF, la libreria está construida sobre el parseador XML clásico de Python y se encarga de validar el xml generado (para generar archivos odf válidos), es sumamente útil si necesitan generar reportes y cosas así.
El clásico helloworld con odfpy


from odf.opendocument import OpenDocumentText
from odf.text import P

textdoc = OpenDocumentText()
p = P(text="Hello World!")
textdoc.text.addElement(p)
textdoc.save("helloworld", True)

easy, no?.



PD: la libreria está _muy_ bien documentada, con buenos ejemplos, está en un archivo odt (no podia ser de otra forma :P)

miércoles, septiembre 19, 2007

Moviendo un cuadrado :P

Jugando con GooCanvas logre finalmente mover un elemento (item) sobre el canvas :)

video

Here is the code (python code, using pygoocanvas)


import goocanvas
import cairo
import gtk

def boton_presionado(item, target_item, event):
print "boton presionado"
fleur = gtk.gdk.Cursor(gtk.gdk.FLEUR)
canvas = item.get_canvas ()
canvas.pointer_grab(item,
gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_RELEASE_MASK,
fleur, event.time)
return True

def on_button_release(item, target, event):
canvas = item.get_canvas ()
canvas.pointer_ungrab(item, event.time)
return True

def on_enter_notify (item,target,event):
item.props.fill_color = "red"
return True

def on_leave_notify(item, target, event):
item.props.fill_color = "black"
return True

def on_motion(item, target, event):
canvas = item.get_canvas ()
change = False
if not event.state == gtk.gdk.BUTTON1_MASK:
return False

y = event.y
x = event.x
item.props.x = x - 5.0
item.props.y = y - 5.0

return True


def main():
window = gtk.Window();
window.set_title("titulo")
window.set_default_size(640,480)

window.connect("delete-event",gtk.main_quit)

scrolled_win = gtk.ScrolledWindow()
window.add(scrolled_win)

canvas = goocanvas.Canvas()
canvas.set_size_request(600,450)
canvas.set_bounds(0,0,1000,1000)

scrolled_win.add(canvas)

root = goocanvas.Group()

rect_item = goocanvas.Rect(parent=root,x=100, y=100,
width=200, height=100,
stroke_color="red", fill_color="blue",
line_width=5.0)

rect_item.connect("enter_notify_event", on_enter_notify)
rect_item.connect("leave_notify_event", on_leave_notify)
rect_item.connect("button_press_event", boton_presionado)
rect_item.connect("button_release_event", on_button_release)
rect_item.connect("motion_notify_event", on_motion)
#rect_item.connect("key_press_event",tecla_presionada)

text_item = goocanvas.Text(parent=root,text="Hello, World!",
x=250, y=150,
width=200, anchor=gtk.ANCHOR_SE,
fill_color="blue")

text_item.rotate(45, 300, 300)
canvas.set_root_item(root)

window.show_all()
gtk.main()

if __name__ == "__main__":
main()

nota: por desgracias los tabs se pierden en el blog, si alguien quiere el .py deje un comentario.

viernes, septiembre 14, 2007

Netbeans over Debian

Siempre dentro de las distribuciones de linux con una filosofia en la espalda ha estado Debian GNU/Linux, es por eso que hoy cuando me decidí a instalar netbeans (habia bajado el .bin hace unos días) se me ocurrió buscar si había algún como el clásico make-java (set de scripts que permitia crear un .deb a partir del .bin de JRE o JDL bajado de sun), así que apliqué la búsqueda y grande fue mi sorpresa al encontrar con lo siguiente:


freyes@yoda:~$ apt-cache search netbeans
libswing-layout-java - Extensions to Swing layout
libswing-layout-java-doc - Extensions to Swing layout - contains Javadoc API documentation
netbeans-ide - IDE for Java Development and More
netbeans-platform - IDE for Java Development and More (platform foundation)


así que le dí apt-get install y voilá, ya lo tenía en mi equipo up-n-running (está el repositorio contrib de debian)

martes, septiembre 11, 2007

OOXML debate in Miguel de Icaaza blog

El gran debate de las dos semanas pasadas ha sido OOXML, si debe o no adjudicarse el estado de 'estándar ISO' (estado que ya ostenta ODF).

Como noticia les paso el dato de que gracias a algunas personas que tienen contactos con gente del gobierno (para mayor detalle revisen el historial de la lista de mundoOS) lograron cambiar el voto de Chile, para que pasara de votar un 'Sí, acepto' a una 'abstención', lo cual es mejor seguir de novios con el diablo (aka microsoft).

Volviendo al tema central, Miguel de Icaza escribió un post en una lista de googlegroups dedicada a comentar los articulo de su blog, si les interesa pueden ver el thread, en el thread salen trapitos al sol relacionadas con Moonlight, como por ejemplo que si sacas moonlight de un lugar que no sea el server de novell podría caerte el fantasma de las patentes, además encontré un post de asbjornu en donde increpa a Miguel acerca de como puede catalogar de 'superb' el estándar de MS teniendo una tan pobre definición, teniendo un diseño tan malo, una falta de explicaciones para que sea implementarlo, además ni siquiera apegarse a estándares reconocidos y existentes hace mucho tiempo (como el relacionado con el calendario gregoriano). Les recomiendo leer el thread es bastante interesante como han comenzado a salir al sol el bullado acuerdo Novell-MS

Miguel de Icaza dijo:

OOXML is a superb standard and yet, it has been FUDed so badly by its competitors that serious people believe that there is something fundamentally wrong with it. This is at a time when OOXML as a spec is in much better shape than any other spec on that space.

Besides, it is always better to have two implementations and then standardize than trying to standardize a single implementation.




Escuchando: Freak on a leash

domingo, septiembre 02, 2007

Liberado a Win32 al 90%

Anoche acabo de finiquitar la muerte de la partición windos xp profesional de mi equipo :)

Ahora hago uso solamente de un windows virtualizado que contiene 1 programa solamente instalado que es uno que necesito para mi proyecto de título (more news coming soon about it).

A que se debió esta decisión radical?, la primera razón es que habia formateado hace como un mes la particion windows (posteriormente instalé windows) y no la volví a ocupar, ni siquiera me digné a instalar los drivers; segunda razón, yo manejaba mi colección de música en esa partición ntfs (para no desperdiciar el espacio) y anoche estaba editando unos tags de un par de mp3's y el ntfs-3g se volvió loco (ocupando en promedio 40% de cpu con peaks de 90%) y además el exaile en una oportunidad se colgó debido a esto me dieron los 5 minutos, agarré el hd externo, hice un backup con el siguiente comando:

# tar cf - | split -b 2000m - ruta/al/destino/particion.tar

Luego rehice las particiones y restaure mis archivos a la partición, edité el /etc/fstab para que apuntara correctamente las particiones, lo mismo se debe hacer con el menu.lst y reinstalar grub posteriormente (en caso de ser de la vieja escuela y aún usar lilo el procedimiento es el mismo)

El siguiente es mi esquema de particiones actual :)

yoda:/home/freyes# fdisk -l /dev/hda

Disco /dev/hda: 50.0 GB, 50018393088 bytes
255 heads, 63 sectors/track, 6081 cylinders
Units = cilindros of 16065 * 512 = 8225280 bytes
Disk identifier: 0x16121612

Disposit. Inicio Comienzo Fin Bloques Id Sistema
/dev/hda1 * 1 1460 11727418+ 83 Linux
/dev/hda2 1461 6081 37118182+ 5 Extendida
/dev/hda5 1461 1583 987966 82 Linux swap / Solaris
/dev/hda6 1584 6081 36130153+ 83 Linux

domingo, julio 29, 2007

Firefox 3

estoy usando firefox 3 y una de las mejores cosas es que ahora los controles de las páginas son widget nativos de GTK+2 :D pretty cool

domingo, julio 01, 2007

XFCE4, my new desktop

The Friday I saw the desktop of manuel (a friend of the usach), and he was using XFCE4.4and it was very good, very light, I did not tried xfce since the 4.2 release, so I decided to use a gnome-style configuration of XFCE4.4 (I like the configuration of gnome) and this is the result:

Am gonna try it for a while and then I'll post my impressions

viernes, junio 08, 2007

vim+miscrosoft=?_?

Si Vim fuera desarrollado por la empresa de Redmond, el resultado sería el siguiente:

Marigan's weblog