Realtime syntax checking with emacs
Note: this post is a web cache recover of a November 2010 post that got lost with the blog crash. I updated it to add C/C++ autocompletion.
One of the nice features of fat IDEs is that you get real time syntax checking. Some languages make it easy, some not.
For example Eclipse has access to the compiler as a service inside the IDE, and it checks the code as you type, even suggesting fixes.
I started to research what could be done on the emacs side to get a better experience, as when I am coding, I am usually thinking at the same time I write, and this means I make more syntax errors than the average guy.
So I found flymake, which is included by default in the emacs package. Copy pasting some snippets from the emacs wiki I got really nice real time checking for ruby:
Going forward with python was easy. A flymake extension that uses pyflakes (a python checking program) was already available.
It was with C/C++ where things started to get more complicated. Flymake has support for those hardcoded so that make with a special target is invoked. I wanted to check the current file only. Also gcc syntax errors are not that good.
So I started to modify the extensions I had seen to use clang (and clang++) from the LLVM project. Once it worked, I got nice error messages on C/C++ files:
I was so happy to have this working on C++ that I needed more to challenge my new acquired mastery. So I decided to try it with ycp. Not that I code with it that often, but I have colleagues who do. After adapting the extensions, here is the result:
You can find all the required files on my emacs setup repository. Follow custom.el which goes to custom-$lang.el to site-lisp/flymake-$lang.el.
Update 20.11.2010:
Thanks to this post I managed to get also Rails .erb templates working. Those are more tricky as they can’t be parsed directly by ruby, but they have to go first through erb -x and then through ruby -c. I ported the script to the style of loading (init and load functions) I was already using.
Update 30.08.2011:
Thanks to this autocomplete extension, I was able to setup autocompletion using clang for C/C++. Here is how it looks like:
Next! ruby autocompletion.
NVIDIA nightmare
NVIDIA continues to be a nightmare on my T410 hardware.
The proprietary driver does not resume correctly after the second suspend to ram. Not sure if it has something to do with the dock.
The nouveau driver continues to be affected by the famous bug 26980 which has been affecting for a while a set of GPUs, producing random freezes.
There was some hope in this comment, which points to this patch and stattes that using 2.6.38 with that patch improves the situation. I am trying to build Kernel:stable + this patch here.
openSUSE clients with Spacewalk
My team has been busy the last months with the release of SUSE Manager, which was received with very good reviews. There is lot of room for improvements, some of them specific to SUSE products/integration but others in Spacewalk itself.
There is lot of work to do and lot of patches being reviewed. Lot of them are already upstream.
One common question is: if I already have a Spacewalk server, how do I setup openSUSE clients?
Thanks to Michael Calmer, we submitted the required packages to a repository in the openSUSE Build Service. You can find the instructions looking for the SUSE section in the “Registering Clients” page of the official Spacewalk wiki.
New home for my blog
My blog was hosted at a non-for-profit hosting for years. They gave me
an excellent (free) service and never had any issues with my wordpress
installation.
Sadly one day they decided to delete old (unused) accounts, and they
did it with a script, that after detecting an account was not used,
proceeded to delete the account.
My account was flagged incorrectly as inactive. So the script deleted
the account.
I had backups, but as their claimed to have data redundancy and daily
backups, I only did those twice a year.
The worst part. The script had another bug: it also deleted the backups.
There goes my blog. I lost a bunch of posts which I (half) recovered
from google cache. I lost lot of images and the original markdown
source of the posts.
So there goes also my last motivation about administering anything. My
blog, as my email and pictures have done for years, moves to the
cloud.
I am still not 100% convinced with Posterous. But lets give it a try.
How to gain root in a HTC Hero (aka G2 Touch) phone
DISCLAIMER: I am not recommending you to root your phone and if you are not sure what for or what are the consequences of doing it (including your warranty), then don’t do it. This post is only an explanation on how to do it. Also I am not responsible for any damage to your phone, including bricking it.
First, download Android SDK 1.5 from here, unpack it and go to the tools/ directory.
My first problem:
./adb shell error: device not found
./adb devices List of devices attached
Reading around I found out how to fix it, and then realized it was documented here
Create a file /etc/udev/rules.d/90-android.rules with the following content:
SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb",ATTR{idVendor}=="0bb4",ATTR{idProduct}=="0c02",SYMLINK+="android_adb"
SUBSYSTEM=="usb",ATTR{idVendor}=="0bb4",ATTR{idProduct}=="0c01",SYMLINK+="android_fastboot"
And restart udev by doing killall -HUP udevd, then unplug and plug the phone.
Now, get Recovery-RA-HERO-v1.2.2.img and fastboot (unpack and chmod +x this one), and put them somewhere, or as this example assumes, in the same tools/ directory.
Now boot the recovery image:
./adb shell reboot bootloader ./fastboot boot Recovery-RA-HERO-v1.2.2.img
You can use the NDroid Backup option to backup your phone to the SDCard.
Get Superuser.zip (requires registration in the xda-developers phorum) and unpack it. You will get two files from there: “Superuser.apk” and “su”.
./adb shell mount /system ./adb push su /system/bin/ ./adb shell chmod 4755 /system/bin/su ./adb push Superuser.apk /system/app/ ./adb shell reboot
Now confirm that it worked:
./adb shell su
(Click Always allow on the phone)
And that is!.
If you need to restore your NDroid backup, I haven’t tried, but you can do it from the recovery image or manually pointing it to the images:
fastboot flash boot /boot.img fastboot flash system /system.img fastboot flash userdata /data.img fastboot reboot
La piratería de la que no se habla
La palabra piratería se utiliza sin mucho contexto para hablar de todo tipo de violaciones a las leyes de derechos de autor, de la misma manera que la palabra “propiedad intelectual” se utiliza para confundir a la gente discutiendo juntos temas tan distintos como patentes y derechos de autor.
En el mundo del software, se crearon grupos como la BSA (Business Software Alliance) o la local ADS, las cuales se publicitan como grupos en defensa de la causa misma, pero en realidad sólo trabajan para las empresas que las integran. Es por eso que no verás a estas agrupaciones condenar violaciones de copyright al software libre.
¿Piratear software libre? ¿No que es gratis?
El software libre es una obra como cualquiera otra. Está protegida por el derecho de autor, lo que significa que el autor es dueño y se reserva todos los derechos sobre la obra. Sin embargo, en el caso del software libre, este añade una “licencia” que permite ciertos usos. Hay varias licencias populares. En el caso del software distribuido bajo la licencia GPL, se permite la copia, venta, modificación y redistribución bajo la condición de que el que distribuye mantenga todas estas libertades. Esto incluye por ejemplo, acceso al código fuente modificado.
Si se incumple la licencia, entonces se pierde toda autorización sobre el software (entra el juego el “Todos los derechos reservados” del que disfruta el autor).
Dichos incumplimientos son más comunes de lo que se piensa. Hoy en día una gran cantidad de aparatos electrónicos de consumo llevan Linux dentro: celulares, reproductores de DVD, televisores LCD, Tablets etc. Algunos ejemplos:
- De los tablets con Android, se mostró como casi ninguno cumplía con las licencias libres.
- Skype estuvo involucrado en un juicio por similar infracción y fue declarado culpable.
No sólo a empresas les ha pasado. Tanto España como Portugal violaron las licencias un software utilizado en la implementación de sus documentos de identidad electrónicos.
Las infracciónes siguen un patrón. Una empresa u organismo desarrolla un nuevo producto. Utilizan software libre como base para ahorrarse costes, ignorando sus consecuencias. A veces sin saber, por ejemplo cuando subcontratan el desarrollo a un tercero. Es lo que le sucedió a Atari, que terminó llegando a un acuerdo con los autores del motor de videojuegos ScummVM , luego de que un juego que Atari subcontrató había sido desarrollado sobre este motor sin cumplir su licencia. Para peor, Nintendo prohibía explícitamente los juegos Wii con componentes de código abierto, por lo que Atari en un principio negó el problema, e incluso amenazó legalmente a los autores de ScummVM.
Muchas de estas condiciones son especificas a la licencia GPL. Otras licencias son más permisivas. Por ejemplo, el sistema OSX de Apple está basado en software abierto el cual no requiere que Apple publique sus modificaciones. Sin embargo, el motor que hacer funcionar su navegador Safari, sí está basado en códigos que obligan a Apple a publicar sus modificaciones.
Cabe destacar que la mayoría de las veces esto sucede por simple ignorancia. Es por esto que la estrategia de las organizaciones que representan a los autores en los litigios contra grandes empresas en general buscan solucionar el problema: que se respete la licencia (por ejemplo: que se publiquen los códigos modificados). Sin embargo, dado el efecto “David contra Goliat”, muchas empresas se dan el lujo de ignorar cualquier llamada de atención. Esto empieza a cambiar, dado que hoy en día los dueños de muchos derechos de autor en el mundo del software libre son también grandes empresas (IBM, Google, etc).
“Pato Cable”…. “Pato Programa” u “Hola Pato”
En Chile también hay casos. Hace varias semanas saltó a la luz que el programa Hola de VTR era en realidad una versión modificada de Qutecom, el cual se distribuye bajo la licencia GPL. El problema no es sólo la falta del código modificado, sino que VTR cambió el archivo donde estaba escrita la licencia y lo reemplazó con su propio texto legal, efectivamente cambiando la licencia original y borrando de paso todas las libertades, y por ende, perdiendo ellos todo permiso sobre el software.
Personalmente envié un correo a los contactos de prensa de VTR (Mireya Leyton y Ana Olate) y no recibí respuesta alguna. Un empleado de VTR comentó que había informado del tema a la gerencia correspondiente, pero el “Hola” pirata sigue allí.
Los autores de Qutecom están buscando ayuda legal, lo cual será difícil debido a que es una empresa muy pequeña, por lo que seguramente tendrán que recurrir a organizaciones internacionales que defienden la propiedad intelectual que no le interesa a la BSA o a la ADS. ¿Caso perdido?.
Al parecer no. Qutecom utiliza las bibiliotecas Qt, ahora propiedad de Nokia. La versión incluida en “Hola” es la 4.3 la cual tiene dos versiones: proprietaria (la cual hay que pagar) o GPL. VTR utilizó esta última, y al distribuir “Hola” bajo una licencia distinta a la GPL (al cambiar los textos) han pasado también a violar los derechos de autor de Nokia, lo cual lo hace una travesura bastante más peligrosa.
Copiar un sitio web … Yes we can!
El colmo de estos casos es cuando los infractores son los mismos que están a cargo de legislar.
Un caso que salió a la luz fue el del sitio web del diputado Nicolás Monckeberg:
el cual tenía cierto parecido con el sitio del presidente Obama!:
(update: lamentablemente mi blog no sobrevivió y perdí la foto. Obama entre tanto ya tiene un nuevo diseño)
Cabe destacar que aquí no estamos hablando de parecidos ni inspiraciones. Un análisis del código del sitio web del diputado revela que el sitio es una copia. Identificadores del sitio de Obama como “getinvolved_calltovolunteer” aparecen tal cual en el sitio de Monckeberg.
Contacté al diputado vía email y facebook, sin recibir respuesta alguna.
Conclusiones
Hace unas semanas, un jóven murió en el incendio de San Miguel (Cárcel en Santiago de Chile). El estaba allí por vender películas piratas. Cuando se trata de defender los intereses de ciertos grupos, la ley funciona muy rápido.
El software libre tiene derechos de autor, y el autor es dueño de la obra, la cual distribuye libremente con la condición de que sus condiciones sean respetadas.
Espero que en el futuro, cuando hablemos de piratería, no estemos sólo discutiendo acerca de alguien vendiendo DVDs en la calle, o a un jóven descargando música desde una red P2P, sino que también te imagines a los ejecutivos de grandes compañías, fabricantes de electrónica, e incluso parlamentarios. La diferencia esta en que ningun juez enviaría a estos últimos a la Cárcel de San Miguel.
openSUSE 11.3 and nVidia
I was going nuts because I could not get a sane configuration for my laptop, which has a nVidia NVS 3100M card.
The laptop is connected most of the time to a docking station, which has a external monitor. I want to use the external monitor when the machine is on the dock, and the internal LCD when it is not. No dual head.
openSUSE 11.3 ships with the nouveau driver. It has wonderful RandR support. KRandTray tool detected both displays and allowed me to turn one off and the other on with 3 mouse clicks. It was not perfect, as I had to do it on dock/undock, but also at boot time.
Sadly, nouveau is buggy. At the beginning I was affected by a random freeze bug which forced me to login from my phone to reboot the system. Deactivating acceleration made this go away, but then randomly you will see in your syslog:
[drm] nouveau 0000:01:00.0: no space while unhiding cursor
And the system will get extremely slow. Reboot needed. This was happening too often. My Linux experience completely ruined. I tried various kernels including Kernel:HEAD, but no luck. Known bug, there is a report in Novell bugzilla too.
On the other hand, the proprietary nvidia driver seemed to work well. But KRandTray did not showed two displays. The problem is that the nVidia driver has a proprietary system to support dual head configurations.
You could run the nvidia-settings tool as root (!!) and change the monitor, but this was a very complicated process. My use case is: I want to hack in a different room, 2 clicks and undock.
Today I found googling a tip that made it work like I expected. You need to configure metamodes. Yes, I have a xorg.conf again. My Screen section looks like this:
Section "Screen"
Identifier "Screen0"
Device "Device0"
Monitor "Monitor0"
DefaultDepth 24
SubSection "Display"
Depth 24
EndSubSection
Option "TwinView" "1"
Option "TwinViewXineramaInfoOrder" "DFP-0"
Option "metamodes" "DFP-0: null, DFP-2: nvidia-auto-select +0+0;
DFP-0: nvidia-auto-select +0+0, DFP-2: null"
EndSection
Each metamode disables one monitor. After relogin I noticed KRandTray still showed one display. But I realized I had two possible resolutions, and selecting between them switched the monitors!. Even less clicks than before, where I had to enable one and disable the other.
Lets see how stable it runs
.
You can even bind the switching to hotkeys using xrandr calls:
xrandr -s 0 xrandr -s 1
The future of KDE instant messaging is happening now
Almost nine years passed since the first lines of Kopete code started to take form, in a remote country in the south part of the globe.
Still today, looking at an old Kopete screenshot has a special meaning for me. I had so much fun. I learned hundred of tricks and certainly it shaped me as a developer. Working with brilliant hackers across the world brought this multicultural curiosity. Both things combined resulted in myself living in a different country, married to a woman from yet another one, and having friend parties where almost everyone was from a different place, and working in a company involved in this great hobby.
However the world was different by then. At that point the discussion was whether you ICQed or you sent viruses via MSN. And the most difficult challenge was to get file transfer done right. Nothing of that matters anymore.
Kopete was initially very innovative, at least in its goals: to communicate with people, while leaving the IM network as a channel. We brought the concepts of “metacontacts” (bad naming), but basically you say people in your contact list, no matter if they were available on MSN, ICQ, or both.
Today I have a telephone with internet 24/7 in my pocket and I can IM on the bus. I don’t choose IM networks as a soccer team, but rely on them because I have friends on various of them. Just like I use twitter for “geeky stuff” while Facebook is a more “relaxed” environment.
Sadly, at some point Kopete lost leadership, when all the strong opinionated and grumpy developers that shaped its core heart got busy with other stuff, while people contributing to it were mostly interested in features like being able to have sub-sub-sub-sub-sub-groups, or notifications per-contact-per-network-perl-daytime or concepts like identities which made sense but that were not designed, transforming Kopete in a kind of a very sophisticated “IM App Construction Kit” but at the same time some of its configuration looks like an IDE, which wording that not every user would understand: identity, account, contact, metacontact, etc.
The focus was on supporting every single feature of every single IM system and to expose it in the user interface somehow. Which was at the same time not easy, as we implemented various protocols from scratch, and keeping up with features or even protocol changes as lot of manpower.
I tried to motivate myself to do development again, but every proposal on the mailing list just seems a completely different direction of what I would even had energy to discuss. Yes. I don’t get motivated even to discuss if adding one tab per IM network to the user interface makes sense or not.
Linux gained a promising technology when Telepathy started to mature. While Telepathy is yet another abstraction layer, it is one built in a way that has proven to be successful on the Linux Desktop, by providing dbus based services that are desktop independent. And it has reached the point where is even used in production devices (AFAIK Nokia), and has features like conferencing and multimedia in its design. Not to mention the protocols code is reused across applications.
There is a group of KDE hackers bringing this forward for KDE under a project called Real Time Communication and Collaboration, partially sponsored by Collabora.
I personally think this is the future of Kopete. IM not as an app, but as a desktop level service where the chat window and the contact list is just something using this service. It fulfills the vision we tried to achieve lot of times with Kopete: like when KMail contact status was implemented, or KAddresbook integration.
A future where people is people (and no metacontacts), and the focus is communicating, listening and seeing them, and not sorting and classifying them. I believe this project has the chance to achieve that.
As any big application, you can’t kill it by rewriting it from scratch. Kopete is awesome and will serve us for a while. The strategy this team is taking by building blocks one by one in the most simple way, sometimes reusing Kopete pieces where possible, is the right one. And I have the feeling they will coexist in parallel for some time.
This group of hackers is meeting right now in Collabora offices for a 1st sprint (Hello Will!). They deserve all the support from the community. Because they are writing the future of KDE instant messaging.
Sobre la Licencia Gubernamental de Software
Pedro Huichalaf Roa publicó una columna donde explica más detalladamente la “Licencia Gubernamental de Software”, antes conocida con el (muy mal escogido) nombre de GPL-CL.
La columna nos dá el contexto que faltó cuando la información se comenzó a propagar por las redes sociales. Con su super-nombre (GPL-CL) estó sucedió más rápido de lo necesario, generando una polémica innecesaria.
Sin embargo, ahora que se ve que no era necesario polemizar, creo más que nunca que es un tema importante y que ojalá no se lleve a cabo como está.
Muchos de los puntos críticos de la licencia fueron muy bien explicados en la carta abierta que envió El Centro de Difusión de Software Libre (CDSL), el Portal Software Libre Chile, el Partido Pirata de Chile y Fundación GNUCHILE y en el análisis técnico publicado por eldiabloenlosdetalles.net, por lo que sólo voy a tocar los puntos que me tienen confundido.
También quisiera aclarar que no soy abogado. Sin embargo he publicado bastante código fuente bajo varias licencias (GPL, BSD, etc) siendo en algunos casos yo el dueño del copyright como la empresa donde trabajo en otros.
Citando el texto de Huichalaf:
Para entender este nuevo ecosistema, tenemos que partir de la base que la transferencia de tecnología se basa en aquella tecnología cuya propiedad le corresponde al Estado. Es decir, estamos hablando de aquellos software y desarrollos informáticos realizados “a medida” para organizaciones de la Administración Pública y cuya propiedad intelectual posea la entidad. Así, un ejemplo es un software desarrollado para gestión documental o calificación de personal.
En este parrafo, se deja claro que estamos hablando de desarrollos donde el Estado es el dueño del copyright.
Lo que ocurre actualmente en relación a este tipo de software a la medida, es que las entidades públicas para efectos de adquisición y desarrollo se comportan en forma autónoma sin que exista comunicación centralizada respecto a soluciones adquiridas.
¿En qué quedamos? ¿Son las agencias gubernamentales la misma organización: el Estado, o no?. El raciocinio se debe hacer sólo con una de ambas hipótesis.
Justamente en este sentido es que nace la idea de generar un repositorio centralizado de software desarrollado para la Administración Pública y cuyos derechos de autor le corresponden al Estado , lo que se concreta en softwarepublico.cl y al mismo tiempo, surge la Licencia Gubernamental de Software, que en términos simples, establece las condiciones de uso del software del Estado.
Aquí empieza la confusión. Si esta licencia es para uso interno del gobierno entre sus entidades, cada entidad puede hacer uso de los softwares sin mayor problema, a menos que el contrato por parte del desarrollador externo no deje al Estado como dueño del copyright, sino que como un mero usuario de una licencia, lo cual contradice el parrafo inicial de Huichalaf (Estado como dueño del copyright). El Estado no necesita entrar en un sistema de distribución de software. El problema de la distribución interna es algo organizacional y político, pero (repito no soy abogado) no algo legal.
Si el fin es compartir entre entidades, ¿Por qué la licencia es tan permisiva?, básicamente permitiendo la distribución de un modo muy similar a la GPL (sin restricciones más que conservar las condiciones, y una restricción agregada de registrarse en softwarepúblico.cl). Aquí surge la confusión, y pareciera que la licencia tiene un objetivo más abierto que el compartir entre entidades de una misma organización. Si esto no fuese así, y la idea es que sea permisiva, volvemos al ¿Por qué no usar la GPL?.
Cuando se trata de ser dueño del copyright, el Estado es uno. Cuando se trata de distribuirlo internamente, ya no es una sola entidad. ¿Cómo es la cosa?
Luego la segunda parte que no calza en el puzzle. ¿Para qué se publica en softwarepublico.cl y no se mantiene en una intranet del gobierno?. Si el objetivo es solo compartirlo entre entidades, esto es ilógico. Si el objetivo es compartirlo con la ciudadanía (lo cual no estaría mal, siendo que ella paga por él) esto tendría sentido.
Si este repositorio es accedido solo por entidades del estado, entonces no habría problema. El problema es cuando se comparte entre países, lo cual es una gran oportunidad, o cuando contratistas del Gobierno reciben este software como modo de externalizar un servicio. Ahí pasamos a la distribución, y por ende se activan las incompatibilidades con la GPL, y por ende no se podrá (por citar un ejemplo) usar la librería del lado “cliente” de MySQL.
Esto contradice ahora la estrategia de Alfredo Barriga de querer externalizar algunos servicios en la “nube”.
Por ejemplo, si un sistema de soporte IT desarrollado a medida bajo esta licencia, se externalizara a un contratista, se estaría incurriendo en distribución.
Hasta aquí tampoco entiendo por qué no utilizar una licencia absolutamente libre, ya que en efectos prácticos esta licencia permitiría a cualquiera que tenga acceso al software a seguir distribuyendolo como fuentes.
Resumiendo:
- Una licencia nueva es una pésima idea que trae consigo más problemas que soluciones, y estos problemas permanecerán ocultos hasta que una gran oportunidad se vea bloqueada por ellos.
- No se entiende por qué una licencia tan permisiva siendo el objetivo una distribución en un entorno cerrado, y por ende por qué no utilizar la GPL de una vez.
- La idea confunde licencia y distribución. Se podría utilizar la GPLv3 y simplemente no distribuir fuera del gobierno lo que no sea para distribuir, o dejarlo como propietario para uso exclusivo del gobierno (y controlar a los contratistas con el contrato, no con la licencia). Lo que se va a distribuir, se puede poner en http://www.gobforge.gob.cl/, el cual no se que rol tiene en todo este tema de la nueva licencia o que criterio se utiliza para poner software en un lado o en el otro (más confusión aún).
- Creo que el plan confunde el ordenar la casa, los contratos, las condiciones, etc., con una licencia nueva: Persiguiendo un objetivo que con sus mismos defectos destruye.
Me gustaría saber ¿Por qué no se podría usar la GPLv3 más un proceso y política clara y explícita respecto a distribución, contratos para contratistas, desarrollo externo, licencias a utilizar en cada caso, etc.
Yendo más allá, creo que la licencia no es el paso más importante. Siento más urgente y me hubiese gustado ver directivas. En especial cuando hablamos de desarrollo a medida por terceros:
- Que obliguen el uso de software libre en los softwares hechos a medida excepto en casos estrictamente justificados (costo, razones técnicas).
- Que regulen y expliquen el como los datos de los ciudadanos se van a almacenar en servicios externos. Aquí en Alemania está prohibido sacarlos del país por ejemplo.
- El uso de estándares: acceder a la información del gobierno, datos, etc en forma transparente: Las APIs de Obama, o la discriminación que uno sufre cuando te obligan a enviar datos en formato .doc.
openSUSE Build Service on Android
Release fast, release early. That is what I am trying this time so don’t get too excited. I only added one feature. Yes one.
You can list the pending submit requests related to you. Nothing else. And not with a very pretty layout
but it will get better.
However, I have an infrastructure in place that will allow me to consume the API very easily, and I will push new versions every time I add something.
What I want to add next?
- Improve the user interface so that it looks pretty
- Ability to act on a request and see the diff (colored!)
- Explore projects and packages
- A service that polls for build failures and show notifications. Same for requests.
I don’t plan to implement the whole user interface in a phone, but mostly the parts where a phone makes a good tool for the build service. Do you have an idea? Screen mockup? Share it with me!
To try it, just search “opensuse” in the market. The code is available here.











