miércoles, julio 14, 2010

plasma memory leak

Parece que no es un memory leak, pero sigue siendo feo y desagradable (sobre todo para gente como yo que no quiere ni me gustan efectos de degradados, dibujos, animaciones...)

Explicación análisis del consumo y una solución no trivial
http://aseigo.blogspot.com/2009/04/plasma-and-memory-usage.html

Este apaño es mucho más sencillo
http://postralphaelite.blogspot.com/2009/09/kde-4-memory-leak.html

Esta propuesta puede ser interesante
http://postralphaelite.blogspot.com/2009/09/kde-4-memory-leak-follow-up.html



plasma and memory usage

A long time bane of my Plasma life has been dealing with it ballooning in memory usage depending on the configuration.

Some of the leaks turned out to be related to certain graphics drivers, but that wasn't the majority.

Some were bona fide leaks in the Plasma code base, such as one I found and fixed the other day that, when the job tracking was turned on in the system tray, would result in a small allocation for each and every job (e.g. file transfer) started. This one wasn't easy to find because the allocations weren't huge and they were all parented QObjects meaning valgrind wasn't being very helpful. We've found and fixed a number of leaks of various sizes and things are feeling pretty good ... but there was still problems.

There was a bug report about memory usage jumping when the digital clock was set to update every second. This is a great example of a report that describes both the problem as well as a very well defined way to reproduce it. Now, I don't personally use a clock that updates every second, and Plasma tries its best not to update too much .. but when I ran `plasmoidviewer digital-clock` with it set to show seconds I watched the memory usage skyrocket with great sadness. :)

After hunting around in the clock code, in libplasma and in libplasmaclock for a number of hours I finally thought, "Maybe this isn't my bug after all." So I whipped up a small Qt only test app and was able to trigger the same problem in just a handful of lines of code. It turns out it's a problem with the caching in QGraphicsScene: it inserts pixmaps but never removes them from QPixmapCache. That shouldn't be a problem, however, since the cache should delete pixmaps when it gets too big and delete pixmaps when inserting using the same key. Unfortunately, for some reason, that isn't happening. By inserting a QPixmapCache::remove before both of the calls to QPixmapCache::insert in QGraphicsScene, the pixmap leaking stopped immediately.

I'm not sure that's the right fix, however, but at least I have an idea now of where we need to be looking. That it isn't in Plasma is nice (yay! not my fault!) but also a bit frustrating since it's slightly easier for me to fix things in Plasma. ;)

In any case, with all these patches applied on my system, a full on Plasma session is currently taking up 17,832k in resident memory and using 302 pixmaps that total 5904k in size on the X server. That's a total of 23736k of app and pixmap memory for my desktop, panel, widgets and wallpapers running using a full debug build.

Earlier tonight my Plasma had well in excess of 1000 pixmaps after running for not a very long time at all. Glancing at xrestop Plasma now has 292 pixmaps, or 10 less than when I wrote that last paragraph, so it certainly seems to not be leaking now. ;)

Yes, definitely headed in the right direction ...

282 pixmaps.... whee.

----


KDE 4 memory leak

For the last month or so my Kubuntu Linux box has been plagued by a particular problem: after running for a little while it would gradually become more and more unresponsive, to the point of unusability. I'm running Jaunty Jackalope on a pretty quick Intel chip, with 2 GB of memory. I've got a 256 MB NVidia video card to boot -- one previously purchased by youngest son (the gamer).

I'd walk away from my desktop and find when I came back it was stuck in molasses. Clicking on a button would do .... nothing. I'd have to hold the mouse button down and wait. And wait. And wait.

Usually I've found this sort of weirdness can be explained by overheating, but that didn't seem to be the case here. Couple that with the fact that I didn't see the problem when running another window manager and signs pointed to an issue with KDE 4.

After suffering through this for a while, I discussed the situation with clever youngest son (now a freshman computer science / information technologymajor at George Mason University) and he said it sounded like a memory leak.

Lo and behold, after some intensive research on line, I ran across several posts that discussed the fact that indeed, if certain desktop effects are enabled, there is a nasty memory leak in Kwin. The following posts reference it here and here. It's not just Linux that's affected: apparently FreeBSD has the same problem with KDE 4.

I'm a simple man: I'm looking for a simple fix.

Finally, I found this thread over at the Fedora forum.

To summarize, the problem is with compositing in Kwin. The easy way of dealing with it it to disable it. Rather than going in and screwing with all of my settings on the GUI, I jumped down to the command line and edited my config file for Kwin.

Drop to a shell and, from your home directory, go to the following directory:

.kde/share/config/

Make a backup (always make a backup!) of kwinrc

Find the section that says:

    [Compositing]
    Enabled=true
Change it to:
    [Compositing]
    Enabled=false

Save your changes. For this to take effect, you'll need to log out and restart your session so that Kwin has restarted. It is not necessary to reboot.

I did this and have had no more problems with my machine becoming unresponsive. Of course, I probably gave up some bit of window manager eye candy, but to be honest, eye candy is the functional equivalent of junk food. The alternative would be to switch to Gnome (gasp) or some other window manager, and I have to admit, even with all it's flaws, I'm a KDE man (although IceWM is not a bad light weight window manager).

Presumably this will be corrected at some point, although to read the forums, there is not universal agreement over exactly who is responsible for the problem. Thanks to StoneDragon at the Fedora Forums for this straight forward fix.

As always, your mileage may vary.



----


KDE 4 Memory Leak -- A Follow Up

Okay -- a follow up on my previous post about KDE 4's apparent memory leak. Despite following the steps I listed I found I was still prone to creeping molasses.

Here's what I ended up doing, which seems to have helped.

First, uninstalled all of the widget libraries I could locate (relax -- I reinstalled them). Then I went in and basically re-installed KDE 4, using Synaptic. I'll note for the record I don't have a lot of love for the newest release of Adept; it's a sorry downgrade of the version that came with KDE 3.

Next I installed OpenBox, which is an alternative window manager.

Once completed, I had the option, when logging in, of starting my session with KDE / OpenBox. This substitutes the OpenBox window manager forKwin, the default KDE window manager, while retaining the KDE look and feel.

Compared to Kwin, OpenBox is a light weight. I confess, I can see no discernible difference between the two once I've logged in -- other than the fact that OpenBox doesn't seem to eat up almost every remaining byte of memory over a 6 hour period (we are talking 98% of my 2 GB of physical RAM and 75% of my 2 GB swap file).

I've been using this configuration for about a week, checking memory usage with both System Monitor and top. So far, this seems to have corrected the problem.

Again, your mileage may vary.

lunes, julio 12, 2010

Unicode y UTFs

Esta es una respuesta parcial a un correo...


El problema por lo que no te deja editar el fichero, es por la codificación del mismo

¿qué es un fichero de texto plano (habitualmente llevan extensión txt en windows)?

Como sabes, las tablas de caracteres de 255 elementos, se quedaron cortas y eran una mala solución


Para solucionarlo surgieron varias ampliaciones.


En linux, unix y casi "too" lo que se menea optaron por UTF-8

El UTF-8 lo inventaron como parte de lo necesario en un nuevo sistema operativo (llamado Inferno) un par de tipos (uno de ellos fue uno de los padres de Unix y C, casi naaa)

Lo bueno de UTF-8, es que se utilizan símbolos ASCII válidos y no desperdicia mucho espacio

Un documento UTF-8 puede abrirse sin problemas con un editor ASCII no UTF-8 y sólo aparecerán secuencias extrañas en los códigos no ASCII


(Existe también UTF-16 y UTF-32)


Windows optó por UTF-16 y lo mal llamaron UNICODE

UTF significa Unicode Transformation Format

¿En qué consiste UTF-16?

En utilizar dos bytes por cada carácter siempre. Con esto tienes una lista de 65536 caracteres (que son menos de los definidos en Unicode que creo que son más de 170 mil)

UTF-16 desperdicia mogollón de espacio comparado con UTF-8 y además, no está codificado en ASCII


Por tanto, un documento con UTF-16, para un programa ASCII es un binario


Por cierto, en internet se utiliza casi al 100% UTF-8 (webs, correo,
ftp, etc...)


El caso es que tu documento ha venido en UTF-16 de windows

Tu linux estará configurado para trabajar con UTF-8 (se puede configurar para trabajar con cualquier otra cosa, pero no es sencillo y nada, nada recomendable)

Entonces kate abre el documento y ve un montón de símbolos raros que no son ASCII

Así que te muestra lo que puede, te oculta el resto y para que no rompas nada, no te deja modificar


Fíjate que en kate te muestra las letras siempre separadas por un espacio. Eso es el otro byte de utf-16 (que no es ascii)



He probado a abrirlo con kword y con OpenOffice


Con kword, pregunta el formato, le dices que es utf-16 y voalá, todo bien

Con OpenOffice es un poco peor, porque te pregunta el formato, le dices Unicode y todo bien.


En realidad no es Unicode (UTF-8 también es una forma de codificar unicode). Insisto en que en realidad es UTF-16, pero Mocochoft, ya se sabe, le pone el nombre que le da la gana o el que le interesa.


Pos eso, que lo puedes abrir con uno de esos dos programas o convertir con otros


http://en.wikipedia.org/wiki/Unicode_Transformation_Format
http://en.wikipedia.org/wiki/Unicode
http://msdn.microsoft.com/en-us/library/dd374081(VS.85).aspx

http://www.cl.cam.ac.uk/~mgk25/ucs/utf-8-history.txt



Subject: UTF-8 history
From: "Rob 'Commander' Pike"
Date: Wed, 30 Apr 2003 22:32:32 -0700 (Thu 06:32 BST)
To: mkuhn (at) acm.org, henry (at) spsystems.net
Cc: ken (at) entrisphere.com

Looking around at some UTF-8 background, I see the same incorrect
story being repeated over and over. The incorrect version is:
1. IBM designed UTF-8.
2. Plan 9 implemented it.
That's not true. UTF-8 was designed, in front of my eyes, on a
placemat in a New Jersey diner one night in September or so 1992.

What happened was this. We had used the original UTF from ISO 10646
to make Plan 9 support 16-bit characters, but we hated it. We were
close to shipping the system when, late one afternoon, I received a
call from some folks, I think at IBM - I remember them being in Austin
- who were in an X/Open committee meeting. They wanted Ken and me to
vet their FSS/UTF design. We understood why they were introducing a
new design, and Ken and I suddenly realized there was an opportunity
to use our experience to design a really good standard and get the
X/Open guys to push it out. We suggested this and the deal was, if we
could do it fast, OK. So we went to dinner, Ken figured out the
bit-packing, and when we came back to the lab after dinner we called
the X/Open guys and explained our scheme. We mailed them an outline
of our spec, and they replied saying that it was better than theirs (I
don't believe I ever actually saw their proposal; I know I don't
remember it) and how fast could we implement it? I think this was a
Wednesday night and we promised a complete running system by Monday,
which I think was when their big vote was.

So that night Ken wrote packing and unpacking code and I started
tearing into the C and graphics libraries. The next day all the code
was done and we started converting the text files on the system
itself. By Friday some time Plan 9 was running, and only running,
what would be called UTF-8. We called X/Open and the rest, as they
say, is slightly rewritten history.

Why didn't we just use their FSS/UTF? As I remember, it was because
in that first phone call I sang out a list of desiderata for any such
encoding, and FSS/UTF was lacking at least one - the ability to
synchronize a byte stream picked up mid-run, with less that one
character being consumed before synchronization. Becuase that was
lacking, we felt free - and were given freedom - to roll our own.

I think the "IBM designed it, Plan 9 implemented it" story originates
in RFC2279. At the time, we were so happy UTF-8 was catching on we
didn't say anything about the bungled history. Neither of us is at
the Labs any more, but I bet there's an e-mail thread in the archive
there that would support our story and I might be able to get someone
to dig it out.

So, full kudos to the X/Open and IBM folks for making the opportunity
happen and for pushing it forward, but Ken designed it with me
cheering him on, whatever the history books say.

-rob

Rust, propuesta de nuevo lenguaje de programación


http://wiki.github.com/graydon/rust/language-faq No es fácil ver una propuesta de un lenguaje de programación que aporte algo intersante sobre lo que hay Ejemplos... Java, C#, python, ruby, etc... Ahora el mundo de la programación se enfrenta a un enorme problema y nadie está preparado. La programación concurrente. Llevamos más de 30 años trabajando con un modelo de programación concurrente equivocado y malísimo Hace 30 años (o más) tenían dos opciones y eligieron la mala: 1.- Mayor rendimiento 2.- Se utilizará poco Ahora el punto 2 se ha vuelto del revés con los ordenadores de múltiples núcleos. Los programas escalan fatal en varios procesadores. Pero eso no es lo peor, lo peor es que son los propios lenguajes de programación los que no escalan porque trabajan con el modelo equivocado. ADA podría haber ayudado bastante, pero... ahora se utiliza muy poco El lenguaje recién inventado por Google (Go), no aporta demasiado Este lenguaje (Rust) sí tiene unas ideas interesantes, aunque está muy verde Aunque el mejor lenguaje (de los que conozco) para ejecución paralela es Erlang Y curiosamente no fue diseñado para tener un lenguaje de ejecución paralela. Mi lista de lenguajes interesantes (no necesariamente en este orden son) LISP Erlang C++ Scala Haskell Groovy

sábado, julio 10, 2010

c++ casque valgrind

Programa C++ con warper en Qt

El programa se ejecuta sin problemas, es un programa sencillo

Pero muy de vez en cuando, el programa explota

No es fácil reproducirlo y generar ese casque

Después de bastante tiempo de observación, veo que explota después de dejarlo inactivo duranto un periodo de tiempo. Curioso

Reproduzco el error haciendo un volcado de memoria con la tabla de símbolos.

El resultado es incoherente, si ningún sentido.

Así que le paso valgrind y...


vaya, parece que hay unos cuantos errores y uno de ellos es AL INICIAR el programa

Es un error de punteros (acceso a una memoria borrada)

La librería que estoy preparado, intenta que estas cosas no puedan pasar fácilmente

* Captura y gestiona el error de división por cero de enteros
* Utiliza siempre countptr. No tienen aritmética de punteros, no se puede pedir la dirección del puntero si este no es válido...
* Contenedores con verificación de límites y validad de iteradores
* ...

Aún así hay un error en el arranque

El problema viene por un sutil cambio en el orden de un par de señales

Una señal indica el cambio de estado y la otra gestiona la acción a realizar en este cambio

¿Se debe cambiar el estado y luego generar la acción? ¿o al revés?

Supongamos que generamos la acción primero, y como consecuencia de esa acción, se genera una petición a la máquina de estados. SE HARÁ SOBRE UN ESTADO INCORRECTO (caducado, obsoleto)

Entonces, tenemos que cambiar el estado primero y luego generar la acción

Lo malo, es que al cambiar el estado, sale de ámbito el estado anterior MIENTRAS SIGUE EJECUTÁNDOSE código de dicho estado

La solución es muy sencilla, pero esa no es la cuestión. La cuestión es porqué se pueden cometer este tipo de errores sin darse cuenta, siendo estos errores tan difíciles de localizar (si no fuera por valgrind)
Y sobre todo, la cuestión es qué se puede hacer para evitarlo

Un consejo frecuente con los eventos o los signal-slot, es que se llamen al final del método

No siempre es posible

Creo que tener un signal-slot asíncrono, sería de gran ayuda para evitar estas situaciones y simplificar otras

Un signal-slot asíncrono podría trabajar fácilmente entre hebras, aunque eso no me interesa en este momento

En un sistema no paralelo, sería mejor que el sistema de signal-slot asíncronos (funcionarían de forma muy parecida a mensajes) despachara en el mismo orden en que se producen

Un sistema de signal-slot asíncrono con tipado fuerte, parece que sería caro
Con tipado débil, sería una implementación mucho más sencilla, menos memoria para datos y programa, pero sin verificación de tipos en compilación y más lento en ejecución


Volviendo al problema, un error en punteros al iniciar el programa, genera que este explote pasado bastante tiempo. Además, es necesario dejar el programa inactivo un buen rato y hacer otras cosas (lo que generará reordenación de la memoria del proceso por parte del sistema operativo)
Sin valgrind, este error sería imposible de localizar y corregir (sus efectos están demasiado lejos del punto donde se produce un error

miércoles, julio 07, 2010

espectacular animación de la carrera nuclear

http://www.wired.co.uk/news/archive/2010-07/6/japanese-artist-nuclear-weapons

Japanese artist maps 1945-1998's nuclear explosions

By Duncan Geere |06 July 2010 |Categories: Culture
Japanese artist maps 1945-1998's nuclear explosions

A Japanese artist named Isao Hashimoto has created a series of works about nuclear weapons. One is titled "1945-1998" and shows a history of the world's nuclear explosions.

Over the course of fourteen and a half minutes, every single one of the 2053 nuclear tests and explosions that took place between 1945 and 1998 are is plotted on a map.

A metronomic beep every second represents months passing, and a different tone indicates explosions from different countries. It starts out slowly, with the Manhattan Project's single test in the US and the two terrible bombs dropped on Hiroshima and Nagasaki that ended World War II.

After a couple of minutes or so, however, once the USSR and Britain entered the nuclear club, the tests really start to build up, reaching a peak of nearly 140 in 1962, and remaining well over 40 each year until the mid-80s.

It's a compelling insight into the history of humanity's greatest destructive force, especially when you remember that only two nuclear explosions have ever been detonated offensively, both in 1945. Since then, despite more than 2,000 other tests and billions of dollars having been spent on their development, no nuclear warheads have been used in anger.

Born in Japan in 1959, Hashimoto worked in the financial industry for 17 years before studying in Toyko in the department of Arts, Policy and Management, and then getting a job as a curator at the Lalique museum in Hakone, Japan.

He began the piece in 2003, with the aim of showing, in his own words, "the fear and folly of nuclear weapons". Hashimoto says: " I created this work for the means of an interface to the people who are yet to know of the extremely grave, but present problem of the world."

As the timescale on the animation only reaches 1998, it doesn't include North Korea's two nuclear tests in October 2006 and May 2009.

Here's the video:

Photo Credit: Isao Hashimoto

lunes, julio 05, 2010

metodologías de desarrollo no comunes

Aunque no son comunes, son las que mejor se adaptan en muchos casos.

http://es.wikipedia.org/wiki/No_vas_a_necesitarlo_(YAGNI)
http://es.wikipedia.org/wiki/Principio_KISS
http://es.wikipedia.org/wiki/Rápido_y_sucio
http://es.wikipedia.org/wiki/Programación_extrema


No vas a necesitarlo (YAGNI)

De Wikipedia, la enciclopedia libre

En ingeniería de software la filosofía de desarrollo de programas: No vas a necesitarlo o YAGNI (en inglés 'You Ain't Gonna Need It') consiste en que no se debe nunca agregar funcionalidad excepto que sea necesario. La tentación de escribir código que no es necesario, pero que puede serlo en un futuro tiene las siguientes desventajas:

  • Cuando se desarrollan nuevas funcionalidades se suele sacrificar el tiempo que se destinaría para la funcionalidad básica.
  • Las nuevas características deben ser depuradas, documentadas y soportadas.
  • Una nueva funcionalidad impone límites a lo que puede ser hecho en el futuro y puede prevenir implementar una característica necesaria en el futuro.
  • Hasta que está definido para qué se puede necesitar es imposible decir qué debe hacer. Puede suceder que si son necesitadas no funcionen correctamente.
  • Puede derivar en un código inflado: El programa se vuelve grande y complicado pero que tampoco provee mayor funcionalidad.
  • Excepto que haya algún tipo de control de revisión, esta característica puede no ser conocida por los programadores que pueden utilizarla.
  • Puede inducir a que se agreguen nuevas funcionalidades y como resultado puede llevar a un efecto 'bola de nieve' que puede consumir tiempo ilimitado y recursos, a cambio de ningún beneficio.


Principio KISS

De Wikipedia, la enciclopedia libre

El principio KISS es aquel que recomienda el desarrollo empleando partes sencillas, comprensibles y con errores de fácil detección y corrección, rechazando lo enrevesado e innecesario en el desarrollo de sistemas complejos en ingeniería.

Este término es un acrónimo que corresponde a la frase en inglés «Mantenlo simple, estúpido» (Keep It Simple, Stupid). Para evitar ser tosco, el acrónimo se hace corresponder con otras expresiones tales como «Manténgalo breve y simple» («Keep It Short and Simple») u otras similares, pero que mantienen la misma idea del principio.

Este dicho empezó a usarse en los años sesenta en Estados Unidos, quizás relacionado con el proyecto Apollo[cita requerida]. Posiblemente pasó al español, al ser citado en algunas obras de ingeniería, en especial ingeniería en informática.



El siguiente lo considero imprescindible para las soluciones de emergencia (que son el primer paso de resolución de un problema, de un total de 3 pasos)

Rápido y sucio

De Wikipedia, la enciclopedia libre

Rápido y sucio (del inglés Quick-and-dirty) es un término usado en referencia a una forma sencilla de implementar un problema. Este uso es popular entre los hackers, que lo usan para describir una solución primitiva o una implementación que es imperfecta, poco elegante, o incluso inadecuada, pero que resuelve o enmascara el problema, y generalmente es más rápida y sencilla de usar que buscar una solución apropiada.

Las soluciones Quick-and-dirty a menudo se centran en un caso concreto de un problema en lugar de arreglar la causa del problema general. Por eso, se usan algunas veces para mantener una parte del software o hardware funcionando temporalmente hasta que se pueda encontrar una solución adecuada.

La frase también se usa frecuentemente para describir documentos o tutoriales que sólo dan una visión general de cómo hacer algo, sin entrar en demasiados detalles sobre por qué o cómo funciona.