Thursday, June 02, 2011

Writing binary files with bash

Hello,
I'm trying to see if I'm able to write some binary file using bash. So, when writing a binary file you often want to write a number into binary format. I ended up with this simple function for writing numbers in little endian:

function num2bin() {
printf $(printf %.$(($2*2))x\\n $1|
sed 's/\([0-9a-f][0-9a-f]\)/\\x\1/g')|
awk -F '' '{ printf $4$3$2$1 }'
}


The first parameter is the number to write, the second is the number of bytes (up to 4). For example "num2bin 40 4" will output a 4-byte long string containing the number 40 in little endian.

How do we use it? I wrote an example script for creating a wav file with noise (according to wav specifications) that you can read here.

Let me know if you have a simpler version of the num2bin function.

Friday, May 27, 2011

Complete variables with cd command in bash

Hello,
lately I've been searching for a way to complete variables containing directories with the "cd" command in bash. This is very helpful if you have something like "cd $mydir/". This is not actually working in debian bash-completion.
Then I've realized that other commands such as "ls" actually expand variables. I looked for some "complete" combo used for "ls" but not for "cd" in /etc/bash_completion and I came out with the following:

complete -F _longopt -o default cd

Luckily, this is exactly the command needed to enable variable expansion with the "cd" command. Put that in your .bashrc after loading bash_completion and you're done.

Sunday, May 22, 2011

Enforce facebook chat through SSL

Hello,

since a few days facebook is supporting SSL for the chat. The problem is that it can't be enabled.

Until facebook enables this you can use the SSLGuard plugin for firefox, which enforces SSL for a list of web sites, including all facebook pages and the chat as well.

We have some good ideas for sslguard that we'd like to get in for the next releases... stay tuned.

Saturday, May 14, 2011

Valag 1.2 released

Hello,
I've just released the 1.2 version of Valag, the graph generator for analyzing Vala code trees. Only relevant change is the fact that it now builds against libvala-0.14.

More information and download at the Valag homepage.

Thursday, February 24, 2011

Bubble sort for prolog

Hello again,
this time I've found a version of bubble sort here. I wanted to provide my version, which is less iterative and, I think, more intuitive. What it does is, simply, bubble until it's sorted:

bubblesort(L1, L2) :- bubblesort2(L1,L2,unsorted),!.
bubblesort2(L,L,sorted).
bubblesort2(L1,L2,unsorted) :- bubble(L1,L3,C), bubblesort2(L3,L2,C).
bubble([],[],sorted).
bubble([X],[X],sorted).
bubble([X,Y|L], [X|L1], C) :- X <= Y, bubble([Y|L],L1,C).
bubble([X,Y|L], [Y|L1], unsorted) :- X > Y, bubble([X|L],L1,_).

Yes, the exam is tomorrow so I will finally stop annoying you readers ;)

Saturday, February 19, 2011

Aptitude string for downgradable packages

Hello,
I'm lately doing some tests with Debian experimental packages thus I often upgrade some packages to experimental and downgrade them back to unstable.
WARNING: Downgrading in Debian is not supported etc.

aptitude search "?narrow(?installed,?archive(experimental))" -F %p|\
sed
's,\([^ ]*\),\1/unstable,'|xargs echo


This will give you a list of experimental packages installed on your system each concatenated with "/unstable". The output can go straight to "aptitude install". I don't directly use "xargs aptitude install" because it's not interactive.

Tuesday, February 15, 2011

Matrix transpose with Prolog

Hello,
an exam exercise requires me to write a matrix transpose method. I've written one and it took a little before I was able to define it completely in 4 rules.
I'm curious then I've found this on stackoverflow: the approach is to calculate first transposed column, then shift by one column and calculate the transpose of that new matrix.
This was one of the first solutions I've thought but I haven't realized it because I'm too lazy to create a rule for calculating the shifted matrix.

My approach is iterative thus less intuitive:
trans(M1, M2) :- trans2(M1, M1, [], M2, 0), !.

trans2([A|_], _, _, [], N) :- length(A, N).
trans2(M, [], H1, [H1|R1], N) :- N1 is N+1, trans2(M, M, [], R1, N1).
trans2(M, [H|R], L, [H1|R1], N) :- nth0(N, H, X),
append(L, [X], L1), trans2(M, R, L1, [H1|R1], N).

Ok, apart the fact that I haven't got the time to beautify it, the code will iterate columns and for each column it calculates a row of the transposed matrix (yes, exactly what you expect a transpose method to do :P). The key is "passing" around the nth column we're looking at.
After we finish calculating a row, we restart from the first row but looking at the nth+1 column. Recursion ends when there are no more resulting rows, i.e. when we reached the end of the columns.

Wednesday, February 09, 2011

Bluetooth simple one-line device connection pairing with Bluez

Hello,
I've written a simple Python script using the Bluez (version 4.66) stack (thanks to http://shr-project.org/trac/wiki/Using) with this usage:

python connect.py MACADDRESS PIN MOUNTPOINT

Snippet code for connect.py is here. If the device is paired, it will be removed and unmounted.

Disconnection is as easy with:

python disconnect.py MACADDRESS MOUNTPOINT

Snippet code for disconnect.py is here.

Feel free to use the code also for other services, in this case my primary concern was to mount the file system.

Rubik's Cube 3D Game in Vala/Clutter

Hello,
I've written a simple program for playing with a Rubik's Cube using Vala and Clutter.

It features:
  • high simplicity in rotating cube slices and rotating the cube itself in a very natural manner
  • shuffle the cube
  • autosave the game

Download and more usage information at the homepage... have fun :)

Friday, January 14, 2011

Base64 and Quoted-Printable GConverters for GMua

Hello,
lately I'm writing GMua for educational purposes and for evaluating Vala, whose purpose is to simplify writing Mail User Agents or simple scripts, ala Java Mail.
It currently parses IMAP (not yet complete) and has a graphical interface called Gutt (yes, inspired by Mutt) for testing.
In order to parse MIME parts with base64 or quopri content-transfer-encoding I chose to implement a couple of GConverter (will use GMime a day, maybe when they switch to gio, not yet needed) in Vala that you can find here:
I'm pretty sure there are bugs in these converters, by the way I wanted to share them :)

Sunday, December 19, 2010

Valag 1.1 released, graph generator for the Vala AST

Hello,
a new version of Valag, a graphviz generator for the Vala language AST, has been released.

Changes since 1.0 version:
  • Add --format and --prefix options.
  • Update to latest libvala-0.12.
  • Bug fixes.
This new version also distributes the xdot.py program as a viewer for the generated graphs.

More information and download at the Valag homepage.

Friday, December 17, 2010

Maja - The Vala to Javascript compiler

Hello,
I've just released the first version of Maja, the Vala to Javascript compiler. The mapping is not quite complete but you can do pretty much everything you could do with javascript directly. There are (still incomplete) bindings for the qooxdoo framework and the demo browser is being ported to vala successfully.
Maja can be used in any environments, not only web browsers.
Programming in Vala saves you from lots of type safety troubles (Javascript), lot of typing (Java) and the syntax is really enjoyable as it is quite close to the Javascript model.

Usage and download at the homepage.

Wednesday, September 15, 2010

DuckDuckGo search engine

Hello,
in this post I'd like to hint you a very nice search engine: DuckDuckGo. I've been pointed out to this by a post here on why both Google and Yahoo suck (and why Google search does more).
In older posts of mine you can find some examples on how Google search can miserably fail a search.
The main problem with the two approaches is: Google (and Bing too) sorts by popularity, Yahoo by match. So, what can happen is: Google finds something completely unrelated to what you need, Yahoo is much sensible to the keywords you put.

This DuckDuckGo search engine instead, looks up the search keywords and asks you for the meaning of the words (Yahoo phase), and then sorts it by popularity (Google phase). Especially with web 2.0 and publicity, popularity of web sites loses much more importance over the actual relationship between the meaning of the search and the web page itself.

So, as usual the conclusion is: don't use only one search engine, use multiple ones because implementation matters; don't say people "Google is your friend" because it can happen to be offensive, say instead "use your favourite search engine (YFSE)".

Monday, August 16, 2010

Debian Appreciation Day

Hello,
today is the Debian birthday. For this event a Debian Appreciation Day has been prepared to thank all the Debian organization, all the contributors, developers, teams and everything related to the universal operating system. If you want to thank Debian and make developers feel loved :P here's the page: thanks.debian.net.



Thursday, July 29, 2010

Using Mash with Vala

Hello,
recently Mash has been released. It is a library for reading models in PLY format and creating Clutter actors from them. For reference, Blender is able to export to PLY. It means you can draw your models with Blender and use Clutter as rendering engine.
Clutter is a 3D canvas and animation toolkit while Blender is a 3D modelling suite.

What I've tested so far is porting the Monkey Viewer C example to Vala: code snippet and monkey PLY here.



That is going to be awesome, stay tuned!

Mipsdis MIPS32 disassembler

Hello,
I've written a MIPS32 (Release 2) disassembler for ELF files. It is not a simple disassembler, it's mostly made for reverse engineering proprietary boxes for educational purposes. It has been successfully tested on Vodafone Station which has Broadcom binaries. These boxes don't have a sections table, therefore normal disassemblers don't work. Mipsdis instead will guess the bounds of those sections (most important ones are TEXT and RODATA for strings).

This console program outputs a friendly assembly code, whose each instruction is commented (comments copied directly from the mips specification). It also features labels for branches and symbol resolution for strings, global variables and functions.

More information and downloads here.

Friday, June 18, 2010

Idea duplicated again

Hello,
I'd like to point you to this firefox extension HTTPS Everywhere (June 17th, 2010) and SSLGuard which is also a firefox extension (first released Oct 14th, 2009).

The code of the former extension is a lot more complicated and the result is not always quite the same as SSLGuard. In fact, while they support secure cookies and per-website custom rules, SSLGuard lets you add custom websites to be secured directly from a friendly graphical dialog.

You could even install both of them, apparently they don't conflict.

It's the second time decrew ideas are being duplicated. This happened sometimes ago with SSLtoHTML (ettercap plugin) and sslstrip (standalone application), but they released the code before us. Funny isn't it?

I'm not complaining about anything (I'm not saying "copy", I say "duplicate"), just clearing things out. Of course, better have more choice and more works.

Sunday, May 02, 2010

Google Reader Fail

Hello,
Google Reader has just wiped out my subscriptions list, which made me scream like a crazy monkey (other than cleaning up the list).Now I'm using bloglines, which looks pretty good except there's nothing like "read all items", but you must clean on each feed to see the items (any alternative to bloglines supporting this?).

But as far as I can see, I'm not the only one that lost the feeds, the difference is that I just opened the reader without any other operation.

I've also heard of MyYahoo! being a good aggregator, the only problem is that Epiphany/Webkit is broken with yahoo (no css), anybody experiencing this?

Friday, April 02, 2010

Valagtkdoc 1.0

Hello,
yes... this is the nth program I'm writing in this period. I hope this is the last one :)

Valagtkdoc is a tool that integrates Vala with GTK-Doc for documentation generation.

You can find download and example usage at the homepage.

I think it's far from being perfect, and actually I haven't tried integrating it with autotools, but it shouldn't be that hard. Unfortunately, you have to somehow break the gtk-doc rule "do not run it manually" because valagtkdoc goes in the middle between gtkdoc-scan and gtkdoc-mkdb.

If anybody has a better solution, please tell me :)

Tuesday, March 16, 2010

Tdpkg troubleshooting and some news

Hello,
lately I've received some feedback, thanks for this.

1) Is it compatible with apt? Can I use dpkg back again after using tdpkg?
The answer is... yes! You can use what you want in the order you want, and use tdpkg when you want. Take in consideration that after using dpkg (or apt) without tdpkg, then you use tdpkg the cache will be rebuilt for consistency.

2) It's not working here (Ubuntu, other distro...), doesn't create the cache.
First of all you have to be root when first running tdpkg in order to create the cache. If this didn't solve the problem you are maybe using an untested platform. Debian uses eglibc and tdpkg has been tested on i386 and amd64. Since tdpkg does wrapping around glibc calls it might happen to not wrap the right functions. If you want tdpkg to be ported to your platform please comment here with the result of these commands:
objdump -T /usr/bin/dpkg|grep open
objdump -T /usr/bin/dpkg|grep stat
objdump -T libtdpkg.so|grep open
objdump -T libtdpkg.so|grep stat

3) Should I put the alias also for apt-get and aptitude?
Yes you have to. Aptitude and apt-get bypass the shell so the only alias for dpkg won't work.

Another thing I'd like to say is that dpkg/experimental has a patch that speeds up a lot database reading by asking the kernel to cache .list files... i.e. dpkg will avoid cold start. This brings timing from 14 seconds to about 3 seconds! At all, using tokyocabinet you get 1 second. Think that including a cache inside dpkg would mean even less than 1 second.

Have fun... :)

Monday, March 15, 2010

Tdpkg 1.0 - speed up reading dpkg database

Hello,
you may have noticed that dpkg takes a long time reading the database the first time you run it (e.g. through apt). This is because of the huge number of /var/lib/dpkg/info/*.list files (1700+ on my desktop machines). It can take up to 14 seconds and more at cold start to install/remove a single package.
Since 2007 in dpkg mailing list a first proposal (by Sean Finney) to using sqlite as cache has been posted, then a couple of weeks ago I reproposed it. No reply since then from the maintainers.

My first idea was to fork dpkg and only change the part about reading the list files. This means you had to install another dpkg version, and I haven't done it for two main reasons: most of people wouldn't have replaced dpkg and it'd have been too hard to maintain it.
The solution is tdpkg, a shared library that wrappes around glibc function calls of dpkg. You'll find in README to backup your /var/lib/dpkg/info but tdpkg is robust enough to not fuck it up.

Tdpkg comes with tokyocabinet (faster) and sqlite (handles concurrency better) cache backends. I've managed to bring cold startup time from about 14 seconds down to about 2 seconds. I will definitely have fun installing and removing applications back again.

Sunday, March 14, 2010

Vala and Graphviz

Hello,
it's often useful for Vala hackers to have a graphical representation of the code tree and control flow blocks. Therefore I've created a simple application called Valag which generates four types of diagrams using Graphviz for each state of the Vala compiler.

This is the first release, there're many things to fix and enhance (like command line options) but it is working quite good already to give support when hacking Vala.

Homepage, screenshots and download here.

Friday, March 05, 2010

Google search wrong again

Hello,
sometimes ago I posted twice about google search having wrong results.
Now it happens again after a few months (it's like google breaks page weights like every 4-5 months).
The search is "debian dpkg list", I really expect the mailing list info page but after 3-4 pages of google search (and also bing this time) I couldn't find it. With yahoo search it's at the first position (lists.debian.org/debian-dpkg).

Like for the previous posts, using different search engines matters and matches your needs.

Wednesday, March 03, 2010

Debian/GNOME bug triage ended

Hello,
I'm writing about the work done in the bug triage weekend of the Debian/GNOME team, started at 27th Feb and ended in 28th Feb.
The result is great, 167 bugs have been closed and many more have been triaged and forwarded upstream.

Thanks to everybody who contributed, especially to whom has done it for the first time (well, you can still continue working on the remaining bugs ;) ).

Tuesday, February 16, 2010

Secure and Decentralized Chat

Hello,
I'm writing to let you know of the first release of SDChat.
It is a protocol with libraries and programs to create secure IM networks using GPG and RSA.
All the stack is written in Python but the page says it will be rewritten from scratch to provide a C API.

It features a GTK+ interface with many plugins (unfortunately audio and video are being broken due to gstreamer updates) and a simple server for routing. No installation is required.

Wondering if this can be any useful for Iranians.

Thursday, February 04, 2010

Vala 0.7.10 released

Hello,
I'm lately following the Vala development and finally we got a new release with plenty of bug fixes and enhancements which makes Vala even more interesting and usable as general purpose language.

Here's the announcement.
I'd like to point you to the new Vala journal, a good resource to stay tuned with Vala changes periodically.

News:
* Support coalescing operator ??.
* Support to_string and bitwise complement with enums.
* Return handler id when connecting signal handlers.
* Support struct comparison.
* Support constructor chaining in structs.
* Enforce protected member restrictions.
* Improve performance of flow analysis.
* Support automatic line continuations in Genie.
* Improvements to the .gir reader and writer.
* Add --enable-mem-profiler commandline option.
* Many bug fixes and binding updates.

Sunday, January 24, 2010

Fetch web page with Vala and Soup

Hello,
I'm lately using the Vala language widely. I find it a great and well designed language.
You may know I'm the maintainer of Freespeak. This program is written in Python. Now I'm rewriting it in Vala, both for providing a good and really simple API in C and for learning Vala.

I will now paste a snippet from the new freespeak code that I use for creating a cancellable asyncronous operation for fetching a web page using libsoup either with a GET or a POST method.

Friday, December 25, 2009

Happy Holidays

I wish you all a Merry Christmas and a Happy New Year!

Monday, December 14, 2009

Facebook and Berlusconi

Hello,
today many people are getting subscribed (with NO authorization) automatically to this group: Sosteniamo SILVIO BERLUSCONI contro i FAN di massimo tartaglia. You have NO notification that you've been subscribed to this group.

Also consider the geographic position (screenshot) of the group contact.

Also consider that the group can't be signaled to facebook, because the feature looks like out of service.

It's clearly a mafia group, beware of!

Lua for Pythoners - Dictionary

Hello,
as promised this is the second post, this time for dictionaries. The most important thing to notice is that tbl[key]=nil means deleting the entry from the table, while in python dict[key]=None is still a valid entry with None value.

Here's the snippet you can launch in a lua interpreter and this is the catalog of python dictionary examples.

Sunday, December 13, 2009

Lua for Pythoners - Lists

Hello,
lately I'm discovering Lua as general purpose language. Many people don't agree with lua being used as a general purpose language, many others (including a newbie like me) think Lua has such a simple syntax and powerful tables to become a full fledged language.
I use a lot of Python, so I start from here: what Python does that Lua can't do almost in the same way? Read the question as it is, don't read "what Python does that Lua can't do", it's different.

This is the first of several post series I'm writing. I'm trying to "translate" python pills in Lua + Penlight

Please consider that many things can be done really better in Lua. As I said, this is a kind of "translation". You will understand that Lua does better than Python in other things that will not be shown because the examples are made in Python.

Here's the snippet, you can run it with a stand-alone Lua interpreter.

If you know better ways of doing things like in Python please comment. Comments like 'Hey, it's inefficient! This is not the way you do things in Lua' are accepted of course but not related to the post.

Errata:
I've had some important feedback thanks to #lua people in IRC:
- Variables in Lua are globally assigned, so at least in functions you must use local
- Using table.insert in loops is slow, better use tbl[#tbl+1] assignment, and even better remember the next free position tbl[next] = element; next = next + 1

Friday, November 27, 2009

Mimaggia, cairo tester

Hello,
From GNOME

I've created a simple pygtk project for testing cairo statements. It includes a sort of terminal where you write statements in a simple language. It features immediate preview of what you write.

Say it's a new format for images.
If you want to test it and see the code, ask me.

Saturday, November 14, 2009

Python and RSA


There are many Python toolkits for crypto, so I hope I've done the best choice (at least for now). This is a simple utility class for managing RSA keys, a sort of wrappera to the m2crypto class.

import M2Crypto
class RSA (object):
def __init__ (self, bits=1024, padding=M2Crypto.RSA.pkcs1_padding, exp=65537):
self.bits = bits
self.padding = padding
self.exp = exp
self.rsa = None

def generate (self):
self.rsa = M2Crypto.RSA.gen_key(
self.bits, self.exp, lambda x: None)

def encrypt (self, s):
c = ""
bytes = self.bits/8-11
for i in range(0, len(s), bytes):
c += self.rsa.public_encrypt (s[i:i+bytes], self.padding)
return c

def sign (self, s, algo="sha1"):
dgst = M2Crypto.EVP.MessageDigest (algo)
dgst.update (s)
return self.rsa.sign (dgst.digest (), algo)

def verify (self, s, sign, algo="sha1"):
dgst = M2Crypto.EVP.MessageDigest (algo)
dgst.update (s)
try:
self.rsa.verify (dgst.digest (), sign, algo)
except:
return False
return True

def decrypt (self, c):
s = ""
bytes = self.bits/8
for i in range(0, len(c), bytes):
s += self.rsa.private_decrypt (c[i:i+bytes], self.padding)
return s
Example usage:

rsa = RSA ()
rsa.generate () # generate key pair
s = "a"*2000 # test data
edata = rsa.encrypt (s)
sign = rsa.sign (s)

ddata = rsa.decrypt (edata)
assert rsa.verify (ddata, sign) == True

Friday, October 09, 2009

Debian+Apache+Tomcat+Axis

Hello,
one of the courses I'm following at the university is "Laboratorio di reti
di calcolatori" which uses the technologies (really technologies?????)
listed in the post title. This is a little tutorial for making them works,
with a little script for registering .wsdd files.

- aptitude install apache2 tomcat6
- download the binaries of axis 1.x (latest is 2.x, it's not used in our course) and xerces then unpack them.
- copy *.jar of xerces into the "lib" dir of axis.
- create "/etc/tomcat6/policy.d/99axis.policy" with:
grant codeBase "file:/var/lib/tomcat6/webapps/-" {
permission java.security.AllPermission;
};

- copy the "axis" directory found under webapps of the axis binaries into /var/lib/tomcat6/webapps
- invoke-rc.d apache2 restart
- invoke-rc.d tomcat6 restart

Now go to http://localhost:8080 to make sure that Apache-Axis works.

Finally, this is the script for deploying web services (call it deploy.sh):
export AXIS_HOME="/home/lethal/ingegneria/reti/axis/axis-1_4"
export AXIS_LIB="$AXIS_HOME/lib"
export AXISCLASSPATH="$AXIS_LIB/axis.jar:$AXIS_LIB/commons-discovery-0.2.jar:$AXIS_LIB/commons-logging-1.0.4.jar:$AXIS_LIB/jaxrpc.jar:$AXIS_LIB/saaj.jar:$AXIS_LIB/log4j-1.2.8.jar:$AXIS_LIB/xml-apis.jar:$AXIS_LIB/xercesImpl.jar"
java -cp "$AXISCLASSPATH" org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService "$1"

In the script, you must tweak the AXIS_HOME variable to point to the unpacked axis binaries: avoid using spaces in this variable or you'll encounter several errors in terms of classpath.
Usage of the script:
sh deploy.sh file.wsdd

We're done!

Wednesday, October 07, 2009

Speeding up zsh completion

Hello,
since I've started using zsh, a great shell with great out of the box completion, one of the most boring issues was having a really slow completion. I can understand it could be slow to get a list of packages, remote files or command line options, but also paths were often slow to be completed. After lots of searches I've ended up in adding this magic line to my ~/.zshrc:
zstyle ':completion:*' accept-exact '*(N)'
This way you tell zsh comp to take the first part of the path to be exact, and to avoid partial globs. Now path completions became nearly immediate.

Another important speed up is using the cache for packages and other stuff:
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache
If you know how to boost up options/remote files, please share :)

Saturday, August 29, 2009

New GPG key

Hello,
due to some synchronization problems between my desktop and laptop, unfortunately I've lost my GPG secret key. I was planning to renew my key after the SHA issues, but this way I can't neither revoke the old key nor sign the new key. So I please anybody having my pubkey to delete it:
gpg --delete-key C29A9371

I've uploaded my new key as usual so you can get it:
gpg --keyserver pgp.mit.edu --recv-keys D2C27B6B

Sunday, August 09, 2009

Spadi source code

Hello,
after I've written really a few docs, and cleaned up some stuff, I've published the code of both Spadi and Corraza on gitorious here. In the while, I've added support for floors and closeable views.
Help... help is needed.

Stay tuned.

Thursday, August 06, 2009

Constructing a free ArchiCAD alternative

Hello,
together a couple of university mates we talked about a possible free (as in freedom) ArchiCAD alternative. There are several free CAD out there but none is free for architects/engineers. The project is too big and ambitious, but I wanted to give OpenGL a shot with this excuse to learn something new.

I've started two projects:
  • Corraza, the OpenGL framework for editing 3d objects and exporting the scene graph to ray tracing software... think about a very very very minimal blender but as library
  • Spadi, the GTK+ application that runs on top of Corraza

You can find a video here to see what it can do now, after a week of development.
There's no code published at the moment, contact me if you would like to join the development.

Stay tuned.

Tuesday, July 21, 2009

Aruanne, pdf reporting framework

Hello,
a while ago I've been talking about pango cairo and how to generate pdf with a couple of tables.
In the meantime I've worked on it, improving and enhancing new kinds of elements. This has lead to the creation of a small project, a library providing a simple framework for generating mostly PDF reports (I haven't tried to generate SVG or something else yet).

After a couple of release requests, I've found finally the time to publish a sort of working code.

Here's the git repository and here you can download the snapshot tarball.

Any patches welcome.

Saturday, June 20, 2009

The less consuming radio player ever

Hello,
multimedia always killed desktop performance, also audio with all such effect-based players out there. I've been using deezer for a long time, but sometimes I'm tired to see my desktop lagging.
I don't need that, I need random music from internet while I'm either programming or studying, and my computer has only 512mb ram and 2.4ghz amd64 (onLY??? yes nowadays it's a little amount).

Let's see what we can do using gst-launch:

while [ 1 ]; do wget -q -O - http://66.250.45.112:80/hard.ogg|gst-launch fdsrc fd=0 ! decodebin ! audioconvert ! alsasink; done

The URL above is a hard rock station :) The while ensures re-connection. I think performances are great, 6% cpu and 2% ram.

But there's yet a bettere solution (see comments):

mplayer http://66.250.45.112:80/hard.ogg

Friday, May 29, 2009

Syx changes web and git hosting

Hello,
I'm officializing the change of web hosting and git hosting from googlecode to berlios:

The new website is up!
For several reasons, including reliability, we switched both the website and git hosting to berlios. Also the purpose of this change is to rewrite the website backend using Syx.
The mailing list and the bug tracker are still hosted at googlecode.

Some progress news in the while
We're working on a new memory management, object representation and garbage collector. On the other side the lack of time is making things harder for releasing the new version. Together with the above changes, new Smalltalk standard pieces will implemented as usual. I remind you the new code is in
the object branch.


Wednesday, May 27, 2009

Render tables with pangocairo like reportlab

Hello,
lately I was wondering if there was any alternative to the well known reportlab python software for creating PDF reports. I immediately thought about Cairo. The only two problems are:
  • Cairo doesn't create multiple pages
  • No support for creating tables containing text, necessary for table-based reports
I still can't realize how to achieve the first feature, but the second one could be solved using Pango layouts.
The idea is to create the cells of the table using such layouts, so that the text get wrapped etc.

Here's the Pango tables code snippet containing the necessary classes for achieving the job. Notice that the methods in the snippet often make use of Pango units instead of pixels.
Now let's use the Table class as follows: create a table with two rows and two columns, then show it twice with different background colors.

surface = cairo.PDFSurface ("test.pdf", 300, 400)
cr = cairo.Context (surface)
cr = pangocairo.CairoContext (cairo.Context (surface))

sizes = [pango.SCALE*12*10, pango.SCALE*12*10]
data = [["first test with pango tables", "seems to work correctly"],
["though it needs", "support for borders and spans"]]

table = Table (cr, sizes, data, pango.FontDescription ("Sans 12"))
cr.rectangle (0, 0, pango.PIXELS(table.get_width ()), pango.PIXELS(table.get_height()))
cr.set_source_rgb (0.8, 0.8, 0.8)
cr.fill ()
cr.set_source_rgb (0, 0, 0)
table.show_table (cr)

cr.translate (0, 200)
cr.rectangle (0, 0, pango.PIXELS(table.get_width ()), pango.PIXELS(table.get_height()))
cr.set_source_rgb (0.4, 0.5, 0.7)
cr.fill ()
cr.set_source_rgb (0, 0, 0)
table.show_table (cr)

Here's the result test.pdf:


Monday, May 18, 2009

Blogging from Epiphany WebKit

Hello,
I've been using Midori for a while. It's a great browser: innovative and light. However all my bookmarks and data are in Epiphany. Last week the new epiphany-webkit version has been uploaded in Debian Sid and I couldn't wait to test it. I'm currently using it instead of gecko; it has still some issues but I begun living without it.

Sunday, April 26, 2009

Create a GdkPixbuf from cairo surface

Hello,
here's the inverted code snippet of the previous post.

w, h = surface.get_width(), surface.get_height()

pixmap = gtk.gdk.Pixmap (None, w, h, 24)

cr = pixmap.cairo_create ()

cr.set_source_surface (surface, 0, 0)

cr.paint ()

pixbuf = gtk.gdk.Pixbuf (gtk.gdk.COLORSPACE_RGB, True, 8, w, h)

pixbuf = pixbuf.get_from_drawable (pixmap, gtk.gdk.colormap_get_system(), 0, 0, 0, 0, w, h)

Saturday, April 25, 2009

Create a cairo surface from a pixbuf

Hello,
sometimes in the code of a couple of projects I see some hard algorithms to transform a pixbuf in a cairo surface.
Maybe most of people don't know that GdkCairoContext, contrarily to cairo_t, is created against a cairo context not a cairo surface:

surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())

cr = cairo.Context (surface)

gdkcr = gtk.gdk.CairoContext (cr)

gdkcr.set_source_pixbuf (pixbuf)

gdkcr.paint ()


Notice gtk.gdk.CairoContext (cr), which cr is not the surface. That's the key of the code snippet.

For instance this can be applied on a ClutterCairoTexture to render pixbufs in the canvas.

Friday, February 27, 2009

Awesome/other wrong keyboard layout

Hello,
due to the high resource usage by Eclipse (I have to use that unfortunately because of my professor) I've temporarly dropped GNOME and now I'm using Awesome for a while.

Ok let's say the problem: the keyboard. Do you have different languages, layouts and so on among several configurations (GNOME, X, ...) and your keyboard layout is messed up with awesome?
Just do it:

setxkbmap -layout YOURLAYOUT


Where YOURLAYOUT for me is it.

I've found this utility in this mailing thread. Yet you can read that awesome is still too young and lacks some keyboard configuration features.

Have fun!

Tuesday, February 24, 2009

JMF and MPEG

Hello,
I'm recently writing a game with Java AWT/Swing/SwingX/JMF for a university exam.
If you are using the Java Media Framework and most of the formats (all the well known and used formats) can't be handled by the library here's your definitive solution to the problem.
You will usually get "Unable to handle format: MPEG" or something like that.

How do you get rid of that and make things work? There's a great plugin named jffmpeg which handles a huge number of audio and video formats (including ogg/vob).
Just follow the instructions on the project website to install the plugins.

Alternatively you can register only the codec and demux you use from within your application code as follows (e.g. only handle MPEG video format on input):

Format[] inFormats = { new VideoFormat ("MPEG") };

PlugInManager.addPlugIn ("net.sourceforge.jffmpeg.VideoDecoder", inFormats, null, PlugInManager.CODEC);

PlugInManager.commit ();

Saturday, January 10, 2009

FreeSpeak 0.3.0 has been released

FreeSpeak is a free (as in freedom, developed and released under the terms of GPL) frontend to online translator engines (such as Google, Yahoo, etc.). It is written in Python, it uses the GTK toolkit and some GNOME infrastructure features.

This is a major enhancemenfts release.



Overview of Changes from FreeSpeak 0.2.0 to FreeSpeak 0.3.0
===========================================================

* Project is now hosted at BerliOS.de: http://freespeak.berlios.de

* Support for cancellating operations has been added

* Translation suggestions (open-tran) have been added

* A menubar has been added and the toolbar has been cleaned up

* The behavior of language/translation selection has been fixed and improved

* GNOME documentation has been added

* Dependencies in the configuration have been cleaned up

* Support for global keybindings has been added through python-xlib

* An introduction widget for the main window has been created

Friday, December 26, 2008

Mailbox-to-mbox

Hello,
lately I've been looking for a way to convert a mailman archive to an mbox format so that I could open with mutt.
I then found a couple of scripts, but the one I've found simpler and working for my needs is mailbox2mbox.pl.
Sample usage:

$ gunzip YourArchive.txt.gz
$ perl mailbox2mbox.pl < YourArchive.txt > mbox
$ mutt -f mbox

And it simply works!
Does anybody know a method as simple as the above one but more powerful?

PS: Happy holidays!

Sunday, December 21, 2008

Global keybinding on X

Hello,
lately I've been looking for a way to create a desktop-wide keybinding for FreeSpeak.
I first looked into Tomboy and Deskbar source codes but the egg was too huge to be adopted, and it would have brought C dependency which isn't always nice for a Python project.
Then fargiolas pointed me to a blog post where I could find about gnome keybindings owned by gnome control center. Well that was only a mirage as it doesn't really grab the key but it's only a visual entry in the keyboard shortcuts preferences.
After a few days I've finally found a not-so-hackish solution in about one hundred lines of Python code.

Here is the snippet (download), only using Xlib and GTK+ Python bindings.

Sample usage:

def callback (keybinding):
print 'Callback!'
gtk.main_quit ()

gtk.gdk.threads_init ()
keybinding = GlobalKeyBinding ("/apps/appdir", "key_binding")
keybinding.connect ('activate', callback)
keybinding.grab ()
keybinding.start ()
gtk.main ()


The only problem is that it doesn't make use of GDK filters because PyGTK doesn't provide such function wrappers and there's no GDK-to-Xlib mapping available.
But yes, it works very good.

Monday, December 01, 2008

Aptitude-gtk progress

Hello,
I was curious to see if aptitude-gtk was making some progress. I haven't followed the project since it's been merged into aptitude.
Well, I found it more functional and complete. Here's a screenshot showing pending packages for upgrade after an update:
From GNOME

The team is definitely doing a good job. Hopefully I'll find the time to give some help as I'm really interested in such full-featured GUI frontend.
Keep going on!

Sunday, November 30, 2008

FreeSpeak gains translation suggestions

Hello,
it hasn't been a long time since FreeSpeak 0.2.0 has been released. One of the TODOs for the next release was to support open-tran, and more over translation suggestions for development.
This is a screenshot of what's been included in the repository today:
From GNOME
FreeSpeak is a GNOME frontend to online translator engines.

Friday, November 28, 2008

FreeSpeak 0.2.0 has been released

Hello,
after some work in these weeks now I have released a new version of FreeSpeak.

FreeSpeak is a free (as in freedom, developed and released under the terms of GPL) frontend to online translator engines (such as Google, Yahoo, etc.). It is written in Python, it uses the GTK toolkit and some GNOME infrastructure features



.
It's been rewritten almost from scratch so I think there's no need to post release notes here. Anyway you can always read what changed from the old version released a couple of years ago here.

Notice that the project homepage has been changed. The project has now moved to BerliOS.de.

Sunday, November 23, 2008

Replace GTK+ with Clutter for fun

Hello,
lately I was having fun with Clutter and Python. I've started by creating some Gtk-like widgets (such as GtkWindow, GtkBox, and GtkButton) in Clutter.
Well, this is the result... it's a simple example of a very poor toolkit, but it works:

Try it, it's only one .py file source code

Sunday, November 16, 2008

Single app instances, Python and DBus

Hello,
I'm working on FreeSpeak lately and I needed to run the application once per session, as it's got a trayicon and a notebook (maybe windows with an applet is better?)
I decided to use DBus for making the application run only a single instance; when you try to open it again it won't start another process, instead it will use the already running one.

This is how I would create a generic single app instance with dbus-python:
import dbus
import dbus.bus
import dbus.service
import dbus.mainloop.glib
import gobject

class Application (dbus.service.Object):
def __init__ (self, bus, path, name):
dbus.service.Object.__init__ (self, bus, path, name)
self.loop = gobject.MainLoop ()

@dbus.service.method ("org.domain.YourApplication",
in_signature='a{sv}', out_signature='')
def start (self, options={}):
if self.loop.is_running ():
print 'instance already running'
else:
self.loop.run ()

dbus.mainloop.glib.DBusGMainLoop (set_as_default=True)
bus = dbus.SessionBus ()
request = bus.request_name ("org.domain.YourApplication", dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
if request != dbus.bus.REQUEST_NAME_REPLY_EXISTS:
app = Application (bus, '/', "org.domain.YourApplication")
else:
object = bus.get_object ("org.domain.YourApplication", "/")
app = dbus.Interface (object, "org.domain.YourApplication")

# Get your options from the command line, e.g. with OptionParser
options = {'option1': 'value1'}
app.start (options)
How it works?
  1. Setup the mainloop for dbus
  2. Request a session bus name, so that other applications (in our case another instance of the same application) can connect to it
  3. Create a new instance at path / if the bus name doesn't exist (so we are the primary owner). If it exists, then obtain the object from dbus and call the method on the remote Application object using the known interface.
  4. The Application.start method checks if it's already running then decide what to do in both situations.
Creating a GTK+ application this way is really easy. It only needs to use the GTK+ mainloop.
Let's suppose we want to present() the GtkWindow when the user tries to open another instance of the application:
import dbus
import dbus.bus
import dbus.service
import dbus.mainloop.glib
import gobject
import gtk
import gtk.gdk
import time

class Application (dbus.service.Object):
def __init__ (self, bus, path, name):
dbus.service.Object.__init__ (self, bus, path, name)
self.running = False
self.main_window = gtk.Window ()
self.main_window.show_all ()

@dbus.service.method ("org.domain.YourApplication",
in_signature='', out_signature='b')
def is_running (self):
return self.running

@dbus.service.method ("org.domain.YourApplication",
in_signature='a{sv}i', out_signature='')
def start (self, options, timestamp):
if self.is_running ():
self.main_window.present_with_time (timestamp)
else:
self.running = True
gtk.main ()
self.running = False

dbus.mainloop.glib.DBusGMainLoop (set_as_default=True)
bus = dbus.SessionBus ()
request = bus.request_name ("org.domain.YourApplication", dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
if request != dbus.bus.REQUEST_NAME_REPLY_EXISTS:
app = Application (bus, '/', "org.domain.YourApplication")
else:
object = bus.get_object ("org.domain.YourApplication", "/")
app = dbus.Interface (object, "org.domain.YourApplication")

# Get your options from the command line, e.g. with OptionParser
options = {'option1': 'value1'}
app.start (options, int (time.time ()))
if app.is_running ():
gtk.gdk.notify_startup_complete ()
How it works?

Let's say we're running the Application for the first time, the loop begins and when it ends running is set to False, so gtk.gdk.notify_startup_complete() won't be called. Instead, if the application is already running, start() will be called on the remote object running the loop. The method then returns immediately so gtk.gdk.notify_startup_complete() will be called.
If you don't notify to the launcher that the startup is complete... guess what happens to your mouse and to your taskbar panel...

If the loop is running, the window is presented to the user with a little delay. If you don't use any timestamp, the UI interaction won't let the window have the time to be presented.

Of course, you can use DBus for many more things, like both setting options from the command line, as explained in the above code, and let other applications communicate with yours and viceversa.
Nowadays almost all systems use DBus, so it won't be a pain to add such dependency. In my opinion, it would be much more painful to use lock files, FIFO, unix sockets or whatever. FreeSpeak used such old technologies and it was a very poor emulation of what DBus already offers.

Monday, October 20, 2008

ping.fm is dead

Hello,
lately I've been using ping.fm for a couple of weeks because I've found it really useful.
Today I've tried to update my status through sending a mail but I received delivery failures... I then discovered that ping.fm is dead!

Tuesday, October 14, 2008

FreeSpeak, a GTK+/GNOME translator

Hello,
I've worked on FreeSpeak a couple of years ago, a Python/GTK+/GNOME project to translate text and web pages by querying already existing online translation tools.
PRO: It has been packed for Ubuntu and it has been publicized by a journal in Italy.
CONS: It has been discontinued until now. In fact I restarted the project and I'm doing a huge refactoring because of the ugly code I wrote in the past.



It's already working, but some features are still missing.
The new approach will allow applications to use FreeSpeak as a Python library to embed the translation widgets.



Contact me if you intend to help the project with suggestions, bug reports, critiques and coding.

Thursday, September 11, 2008

Debian Get Satisfaction


Hello,
lately I've found getsatisfaction, a social web2 free customer support for all companies and products.
Of course, what have I done is to look for the Debian company. Well it's there, but unused.

  1. Easy for novice users to ask and find answers there.
  2. You can share you ideas and get help
  3. Report problems and get help on bug reporting
  4. General and specific discussion
  5. Subdivide the service in variuos products (for examples ports and distributions)

Monday, September 08, 2008

GTK Apps to replace Gnome Files

Hello,
everyone knows that gnomefiles has went offline with that boring redirect to osnews.com.
Now many people is looking toward gtk-apps.org, I didn't know it before. It's looking really good.
The only problems is that I had (and I guess I'm not the only one) a few unmaintained projects on gnomefiles and they are now lost.
I'm wondering if it will be publicized a day by gtk.org to be something more official.

Saturday, August 23, 2008

Where are you? Yahoo! Fire Eagle

Hello,
the Twitter question was "What are you doing?". The new question is now "Where are you?"

Yahoo! has launched a sort of social application called Fire Eagle for updating your location and share it across other web services.

Saturday, August 16, 2008

Cincom Industry Misinterpretations reached the 100th podcast


Hello,
I'm listening to the Industry Misinterpretations podcasts (though my English is so poor to understand only a few words) and now they reached the century mark. They're managing an account on Podcast Alley.

Stay tuned!

Interviewed by Clubsmalltalk

Hello,
lately I've been interviewed by the new clubsmalltalk. Hey, I know, I'm not so good with English ;)
I'm glad of this, thanks to Hernan Galante.

Vagalume, GTK+ and Last.fm

I've found this great gstreamer application to listen to the last.fm stations. It works perfectly, fully functional and up-to-date. Features several IM status updates, including telepathy. It's definitely good-looking with my dark theme.
Homepage: http://vagalume.igalia.com/
Last.fm group: http://www.last.fm/group/Vagalume

Monday, August 11, 2008

Compiz with ATI RS480 on Debian

Hello,
after years that compositing has been introduced in our desktop, it's finally come the time to try it.

Uninstall fglrx
My video card is not supported very well with Mesa 7.0.x, in fact I've been using the fglrx driver for a long time.... until now!
I had to manually dpkg --purge all the related packages.
Now it's better to rmmod fglrx.

Install mesa 7.1 from experimental
On #compiz-fusion some guys hinted me I should have used Mesa 7.1rc because of recent improvements on my video card. The only way to get such version was to include experimental sources.
Ok, no problem, if it doesn't work I can downgrade back to the previous one.

Upgrade xorg to experimental
But there're still problems, I had to upgrade to the latest xorg in experimental because of mesa compatibility. In fact AIGLX couldn't load DRI drivers because of missing symbols.
I had to dpkg -l|grep xorg the install the one by one. I did pray for everything to work, really.
Now backup xorg.conf and go ahead with X -configure.

Install compizconfig-settings-manager and compiz-fusion-plugins-extra
For some reason, the first time I've tried running compiz it's gone Segmentation Fault. On the IRC channel they hinted me to install the crash handler plugin to back track the error. After installing such packages, magically compiz --replace worked!
Now I have a GNOME Desktop with the Blue-Joy theme and the Avant Window Navigator.

Everything both nice and unuseful, but now I understand how eye-candy fancy stuff can change your desktop.

Before the war:


After:

Thursday, August 07, 2008

iStream


iStream
Originally uploaded by Lethalman
Very useful applet for listening to the radio. It lacks a perferences dialog, but it's still nice.

Gnome main menu


Gnome main menu
Originally uploaded by Lethalman
Hello,
while I was playing with apt-cache I've discovered a new kind of main menu in GNOME. It's being developed by SuSE. It feels nice, robust and innovative.
The screenshot is showing the documents tab.
To install, aptitude install gnome-main-menu and add the new applet.

kqemu on Debian amd64

Hello,
I've been using qemu a lot lately because I'm creating an usb hdd with debian live.
The image contains a system running postgresql, development packages for gtk and python and gnome-core . All this ends up loading in more than 5 minutes, this is really boring.

Then I begun looking for a faster virtualization system, and found KVM. Unfortunately my processor hasn't the right flag for it.

Finally I found kqemu, which is a module for the kernel that speeds up a lot qemu. I never thought it could speed up things...... so.... much!
Let's install it:
m-a a-i kqemu
modprobe kqemu
That's it, for those who owns an amd64 processor, this is the right way to use kqemu:
qemu-system-x86_64 -kernel-kqemu [your options]
You shouldn't get any error, if you do... boh.

The image now boots in 33 seconds down to the bottom init scripts, and GNOME works only with a slight delay but it's definitely a great speed up. With the real machine, I enter gnome in about 40 seconds.

Keep going the good work Qemu team, and thanks as usual to everyone who helped me on IRC.

Wednesday, August 06, 2008

Debian and zd1211 wifi

Hello,
I'm using debian lenny and I've got these two problems:

  • With versions of the linux kernel prior to 2.6.20 (maybe) I could install zd1211 firmware using the module-assistant which has been now dropped from testing and unstable.
  • Boot process slowed down by 30 seconds and couldn't plug-in the usb pen because udev/hal screw up

What I've done is to remove the source and its created firmware, with the one shipped with testing and unstable (bug #411912):

aptitude remove --purge zd1211-firmware zd1211-source
aptitude update
m-a clean zd1211
aptitude install zd1211-firmware

Now let's fix the hotplug part, open /etc/udev/rules.d/z25_persistent-net.rules and remove similar lines:
# USB device 0ace:1215 (zd1211rw)
SUBSYSTEM=="net", DRIVERS=="?*", ATTR{address}=="00:1d:0f:b3:66:f7", NAME="eth2"
Now try to detach and reattach your usb pen and everything should magically work.

Thanks to Nss (#debianizzati), dcbw NetworkManager developer and gsimmons (#debian).

Sunday, July 13, 2008

Syx gaining more stability and speed

Hello,
in the new branches of Syx (an open source Smalltalk-80 implementation) we're working to try a new kind of memory management and add many features that have been missed until now to focus on other stuff.

The new faster and more modern v0.1.8 release will contain the following refactoring:
  • Objects will be variable-length (minumum 12 bytes on 32-bit processors and 16 bytes on 64-bit processors)
  • By changing the objects also the GC changed to a mark and compact GC
  • Threaded-switch statement to run processes
  • More efficient method cache (maybe a simple global cache lookup for this release)
API for primitives will only change slightly.

Suggestions for any new particular technologies are welcome.

Thursday, July 03, 2008

identi.ca is worse

Hello,
I'm using Twitter in this week and the API works "almost" perfectly while the website is down most of the time.
I've recently heard about identi.ca, so I decided to try it.
My first impression was bad, because I've seen many redirects of the page, and DNS changes sometimes.
But ok, I tried to register and again... I had problems. When I submitted the registration twice it just did nothing.
I then waited for a couple of hours then I've been registered to identi.ca.

Once I tuned all my account settings, the service has gone down. What happened? Too many twitterers have switched and now identi.ca is out of service? In the while Twitter has magically reopened its gate.