Search Results: "Enrico Zini"

1 March 2007

Enrico Zini: suggestions-gz

Package suggestions I tried generating a list of 10 suggested packages for every package in the archive. You cat get it at http://people.debian.org/~enrico/Suggestions.gz and build nice things with it. Generation took two hours of a nice 18 process on the busy gluck, but it can be run in any faster/less busy machine that has a local copy of the unaggregated popcon data. This is (roughly) the generating algorithm:
  1. Take a package P.
  2. Query P on a Xapian index that indexes popcon submissions as documents and their packages as words.
  3. Get the first 20 resulting popcon votes.
  4. Score each package mentioned in those 20 results by a combination of how many votes mention it, its TFIDF scores in the various votes and the Xapian relevance score of the resulting votes.
  5. Take the top 10 packages as suggestions for P.
The code can be fetched with:
bzr branch http://people.debian.org/~enrico/2007-01/popcon/

27 February 2007

Enrico Zini: only-one-way

Python: "There's Only One Way To Do It"
import array
import numarray
import numeric
import numpy
They're all almost the same, but not quite. When google gives you an online piece of documentation, it's hard to say what it refers to. And different scientific modules use one or the other, more or less unpredictably. Maybe in the future numpy will replace them all. In the meantime, if I hear someone saying "There's Only One Way To Do It", I will spank their cheeks with a wet fish.

20 February 2007

Enrico Zini: maskedarray-performance

Performance of numpy masked arrays This is the code:
import time, numpy, MA
start = time.clock()
a = numpy.ones(1000000)
cur = time.clock()
print "numpy create", cur - start
start = cur
for i in xrange(1000000):
    a[i] = i
cur = time.clock()
print "numpy fill", cur - start
start = cur
a = MA.array(numpy.empty(1000000), mask=1)
cur = time.clock()
print "MA create", cur - start
start = cur
for i in xrange(1000000):
    a[i] = i
cur = time.clock()
print "MA fill", cur - start
start = cur
This is the output:
numpy create 0.01
numpy fill 0.39
MA create 0.15
MA fill 17.06
/me cries

5 February 2007

Enrico Zini: pmdraft-commandline

Second generation package manager - First shellish prototype As you know, I'd like to experiment with prototyping some new interface concepts for package managers. I put together a prototype backend and hacked a cmd-based shell interface for it. You should be able to fetch it with:
bzr branch http://people.debian.org/~enrico/2007-01/popcon/
The files involved are pm.py, pmnew and a very little bit of anapop.py. You run it with ./pmnew. The commands are: This can be an example session to try:
tags
search toy
tags
packages
tags
desired 1
packages
info 3
If you: then the list of available packages will be sorted using my recent web interface prototype for popcon-based suggestions. Matt Good and Thomas Viehmann volunteered to have a try at a GUI. This can only be fun.

2 February 2007

Enrico Zini: swig-doxygen-docstring

Generating Python docstrings from Doxygen with swig I found that there is a way to autogenerate Python docstrings from Doxygen documentation when creating bindings with swig:
  1. Instruct doxygen to output XML (this is different than GENERATE_TAGFILE):
    # If the GENERATE_XML tag is set to YES Doxygen will
    # generate an XML file that captures the structure of
    # the code including all documentation.
    GENERATE_XML           = YES
    
  2. Use either a python script or an XSLT transformation to extract information from the Doxygen XML into a swig .i file with %feature("docstring") commands.
  3. Include the resulting .i file in your master .i file:
    %include "../doc/dballe-doc.i"
    
This is all. Now you can fire up ipython, import your new library and get online help.

Enrico Zini: pmdraft

Second generation package manager I have created many prototypes for advanced package manager features. Erich Schubert also made a tag cloud prototype. Recently, I wrote:
We have lots of interesting, usable metadata; we have algorithms; we have prototypes; we have ideas for lots of cool, implementable features. The question is, are we able to write applications that just combines what is needed from all this treasure to provide the right interface(s) for our base(s) of users?
Most of the back-end code is already implemented in Python, and I'm thinking of putting it together into a working prototype for a new concept of a file manager. This could be even implemented quickly, if someone joins me who is good at: What follows is a sketch description of what I have in mind. The user
Debora is 34, working as a web designer in a small enterprise. She has a laptop running Debian which she uses both for work and at home. She likes Debian for the wide range of software, that allows her to be always able to access the best tools for the job, even in a highly changing environment like the one of web design. At home she enjoys the various tools for photo editing and management, and of course, having a husband and a 6 years old son, the selection of games.
The tasks Looking for new software Use the smart tag search for searching: it allows a Google-like search interface, which afterwards allows categories to be used to semantically refine the results. This last step is conceptually very simple, as it maps to a sequence of "more like this" and "less like this". The search results can be sorted using popcon suggestions, that are very effective at showing software not in the system that many other people use. Looking at what is installed Let's see if this package does what I need Given an installed pacakge, show the contents of its bin/ directories and showing manpages as the details for the bin/ file: thanks to the Debian Policy, executables are all in /(usr/)?s?bin/ and they must have manpages. For packages that are tagged as interface::3d, interface::text-mode or interface::x11, allow to run them directly from the interface. Also show the contents of /usr/share/doc/pkgname and /usr/share/doc/suggested-and-recommended-pkgnames and allow to open documentation with the appropriate software. If there is an html directory which contains an index.html, only show that and not all the other HTML files. Find info documentation and allow to open it into a proper info browser. If there are manpages that don't have a corresponding executable, show them as extra documentation. What was that nice package I installed yesterday? List installed packages sorted by when was the last time they have been installed. Let's get rid of the cruft There are also some "unusefulness" scores one can compute, but I haven't yet been playing with them yet: Task filter Have a look at the popcon suggestion page: there is a "Suggestion type" box. Of course the same idea can be used in a package manager to restrict it to a significant subset of the packages. More filters, as you can imagine, can be easily created. This is how it is implemented:
case "any": $filter = "'!role::shared-lib'"; break;
case "gui": $filter = "'!role::shared-lib && role::program && (interface::x11   interface::3d)'"; break;
case "devel": $filter = "'!role::shared-lib && devel::*'"; break;
case "game": $filter = "'!role::shared-lib && role::program && game::*'"; break;
default: $filter = ""; break;
The same filter can be gived to Debtags:
debtags search '!role::shared-lib'
debtags search '!role::shared-lib && role::program && (interface::x11   interface::3d)'
debtags search '!role::shared-lib && devel::*'
debtags search '!role::shared-lib && role::program && game::*'
Conclusion As I said:
There is so much really cool stuff to be written, just within reach.
So?

31 January 2007

Enrico Zini: popcon-play

Playing with popcon data Check out http://people.debian.org/~enrico/popsuggest.php. You can upload there the popcon results of your system and have them compared with all the other submissions. It will show the results grouped by the most relevant tags found in your system, and you can filter the results based on various package types that map to debtags expressions. Credits also go to Eric Evans, for the continuous very useful and supportive discussions during all the development. As I said, there is so much really cool stuff to be written, just within reach. Some random notes taken during the development:

26 January 2007

Enrico Zini: pkgwalk

A stroll among Debian packages Can Debtags be used to show a list of packages similar to a given one? Yes it can:
#!/usr/bin/python
#
# Copyright (C) 2007  Enrico Zini <enrico@debian.org>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
# From python-debian
from debian_bundle import debtags
# From python-apt
import apt
aptCache = apt.Cache()
pkg = 'debtags'
# Read the debtags database 
db = debtags.DB()
tagFilter = re.compile(r"^special::.+$ ^.+::TODO$")
db.read(open('/var/lib/debtags/package-tags', "r"), lambda x: not tagFilter.match(x))
# Get the tags of the package
tagset = db.tagsOfPackage(pkg)
# Get the list of packages that have some tag in common with pkg
nextpkgs = set()
for pkg, tags in db.iterPackagesTags():
    if tagset & tags:
        nextpkgs.add(pkg)
# Score every package by the number of tags it has in common with pkg
def pkgscore(pkg):
    score = 0
    for tag in db.tagsOfPackage(pkg):
        if tag in tagset:
            score += 1
    return score
# Show the top 20 related packages in reverse score order
display = sorted(nextpkgs, key=pkgscore, reverse=True)[:20]
for num, pkg in enumerate(display):
    aptpkg = aptCache[pkg]
    desc = aptpkg.rawDescription.split("\n")[0]
    print "%2d) %s - %s" % (num + 1, pkg, desc)
Now, imagine an application that allows you to move from package to package using the list of similar packages. You are using this application and moving from tag to tag. Can the list of previous packages you visited be used when computing similar tags to make the selection even smarter? Have a look:
#!/usr/bin/python
#
# Copyright (C) 2007  Enrico Zini <enrico@debian.org>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
# From python-debian
from debian_bundle import debtags
# From python-apt
import apt
aptCache = apt.Cache()
# Read the Debtags database 
db = debtags.DB()
tagFilter = re.compile(r"^special::.+$ ^.+::TODO$")
db.read(open(options.tagdb, "r"), lambda x: not tagFilter.match(x))
# Maximum number of previous packages to remember 
maxlen = 3
# Initial package selection
trail = [ 'debtags' ]
# Loop until the user chooses to quit
done = False
while not done:
    # Compute a package weight according to how old it is in the
    # trail
    pkgweight =  
    for idx, pkg in enumerate(trail):
        pkgweight[pkg] = 1.-(idx/maxlen)
    # For every tag, find the number of packages in trail that have the tag
    tagscores =  
    for pkg in trail:
        for tag in db.tagsOfPackage(pkg):
            if tag in tagscores:
                tagscores[tag] += pkgweight[pkg]
            else:
                tagscores[tag] = pkgweight[pkg]
    # Divide every tag score by the number of packages in the trail,
    # obtaining a 'tag weight'.  A package can be later scored by summing
    # the weight of all its tags.
    for tag in tagscores.iterkeys():
        tagscores[tag] = float(tagscores[tag]) / float(len(trail))
    # Find the merged tagset of the packages in trail
    trailtags = set(tagscores.keys())
    # Get the list of packages whose tagsets intersect the trail tagset
    nextpkgs = set()
    for pkg, tags in db.iterPackagesTags():
        if trailtags & tags:
            nextpkgs.add(pkg)
    # Score every package by the sum of the weight of its tags
    def pkgscore(pkg):
        score = 0.0
        for tag in db.tagsOfPackage(pkg):
            if tag in tagscores:
                score += tagscores[tag]
        return score
    # Show the first 20 packages in reverse score order
    display = sorted(nextpkgs, key=pkgscore, reverse=True)[:20]
    for num, pkg in enumerate(display):
        aptpkg = aptCache[pkg]
        desc = aptpkg.rawDescription.split("\n")[0]
        print "%2d) %s - %s" % (num + 1, pkg, desc)
    # Ask the user to choose a new package
    while True:
        ans = raw_input("> ").strip()
        if ans[0] == 'q':
            done = True
            break
        elif ans.isdigit():
            num = int(ans) - 1
            if num < len(display):
                # TODO: on a different kind of interface, display the full
                # description of pkg
                trail = [display[num]] + trail[:maxlen]
                break
            else:
                print "The number is too high"
Who wants to make a GUI out of this?

24 January 2007

Enrico Zini: package-managers

Improving package managers I noticed two posts on improving package managers none of which mentions Debtags. Daniel Burrows mentions various issues: David Nusinov mentions that the ideal package manager should look like Google, where you search for things using just a simple one line text entry and pick from the results what you want to install. I should probably do a bit of recap of things that have been going on. I'll go through that list again:
  • The current sections in Synaptic are useless
Agreed. This used to be a bug about this, which has been closed by Debtags more than one year ago. We now have much more useful category data for about 73% of the archive (including experimental), but what we lack is software using it. Here's a quick trick to try:
  1. install debtags, and this gives you an easy to read text file in /var/lib/debtags/package-tags.
  2. from that file, pick packages that have the tags role::program, scope::application and interface::x11.
  3. display the results, and use the tags works-with::* and use::* to navigate the results.
There is a python-debian package in experimental that has a debtags module you could play with. Why is that that so far noone has written a simple package manager just for gamers, which uses only the game::* tags? Do you think Debtags gives you too many tags? Then check out: To summarise so far, we not only do have better categories, but also a number of cool algorithms to use them, and some interface prototypes as well. Just don't expect me to write a package manager as well: that's a job that so far I decided to leave to someone else. adept gave it a try, with positive results.
  • there are better keyword search technologies than strstr()
Indeed, Xapian for example. I use it as part of the backend of the Debtags smart search, and here's our Xapian-powered normal keyword based package search interface which does stemming, indexing and all you want to ask from a serious full text index. In that page you don't see all the nice features of Xapian, but only the ones that I needed for my Debtags evil plans. Have a look at the documentation and give it a try. Here is a way to see Xapian's similarity matching in action:
  1. go to the Go tagging! page
  2. click on a random untagged package
  3. the system gives you a rather relevant selection of tags
  4. look at it again: the package was untagged: how could the web engine possibly figure those tags out?
What is happening under the scenes is that:
  1. I ask Xapian: "what packages are similar to this one?".
  2. I aggregate the tags of the resulting packages.
  3. I rank the tags by how many resulting packages have them.
While we are on this topic, why don't we decide that we maintain a Xapian index of our package descriptions in, for example, /var/lib/apt/fulltext/, so that various applications can share it? Indeed. Anyone would like to implement this little "popcon" tool? Having the data easily accessible locally can encourage people to use them. The Debtags Go tagging! page already uses popcon data to show the most common untagged packages at the top, with double reason: it shows packages that more people are likely to know (and therefore likely to categorise) and it pushes for the most common packages to be tagged more urgently. Indeed. Anyone volunteers to implement a prototype? The full unaggregated (but anonymised) popcon data are accessible to every Debian Developer on the host gluck.debian.org in the directory /org/popcon.debian.org/popcon-mail/all-popcon-results. Ideally one can do many interesting things with this concept: besides tag suggestions, one could identify the packages that are most representative of an installed system, and also offer negative suggestions like: "people who have packages like yours usually don't have this package: would you like to remove it?". There is more than all this that could be done. Recently, almost by accident, I had the idea of querying packages by example, like pointing to a file and find packages that can work with it. I've asked Jeroen to have Mole collect info on all files that could possibly get installed in /usr/lib/mime/packages/ (as suggested by Bernhard R. Link), to see if that prototype can be made more accurate. Query by similarity would be nice: I don't like this program, but what else do we have that does the same job? This is best implemented using Debtags data, since it directly maps to semantic properties. Note that you don't have to show a single tag to the user to implement this kind of interface. Do we have a way to point at the X window of an application and get the name of the package that installed it? Wouldn't it be about time to have it? Why don't we have a system updater utility that shows the Debian weather? Why aren't more people playing with semantic web? But more generally, the problem with package managers is that we seem to be irrationally compulsive in wanting to make the one and only big easy and complete interface for everyone. Other more reasonable people would tell you that if you have two very different kinds of users you may want to consider having two different user interfaces. Ubuntu for example installs by default 3 package manager interfaces: Synaptic; the thing that you access from the application menu to add applications to it; and the update manager. Does it sound like a waste? To me it makes lots of sense. We have lots of interesting, usable metadata; we have algorithms; we have prototypes; we have ideas for lots of cool, implementable features. The question is, are we able to write applications that just combines what is needed from all this treasure to provide the right interface(s) for our base(s) of users? Even if my English in 2004 wasn't easy to understand, a read here might still be useful. There is so much really cool stuff to be written, just within reach.

21 January 2007

Enrico Zini: avoid-flamewars

Fourteen ways in which you can avoid starting a flame war on a Debian mailing list On an IRC brainstorming on what talk I should give at FOSDEM, liw suggested:
"Fourteen ways in which you can avoid starting a flame war on a Debian mailing list".
In the end I went for something more technical, but I've never stopped thinking about liw's challenge. I ended up writing talk notes about such a potential talk. Here they are. The classics The radicals The radicals, applied selectively The From tricks The naggers The conscience ticklers The subtle The subtle, 1 week later

Enrico Zini: python-module-commands

Python "commands" module The standard python library has a module called commands with three nice simple functions to run a command and get its output and its status. The first one is called commands.getstatusoutput(cmd), it runs the given command and returns its exit status and its output. The second one is called commands.getoutput(cmd), it runs the given command and returns its output, ignoring the exit status. The third one is called commands.getstatus(cmd), it runs the given command and returns its exit status, ignoring the output. Actually, no. The third one is called getstatus(file), it runs the command ls -ld file (with proper shell escaping) and returns its output. Seriously.
>>> commands.getstatusoutput("echo ciao")
(0, 'ciao')
>>> commands.getoutput("echo ciao")
'ciao'
>>> commands.getstatus("echo ciao")
'ls: echo ciao: No such file or directory'
>>> commands.getstatus("/bin/echo")
'-rwxr-xr-x 1 root root 19304 2006-08-31 14:25 /bin/echo'
Every time I think of this getstatus, I quickly convince myself that I misread the documentation. Then I rerun the example above.

19 January 2007

Enrico Zini: tagminer

Cute things one could do with debtags While answering to a long message in the debtags-devel mailing list I accidentally put together the pieces of a fun idea. This is the bit of message I was answering:
  • It would be very useful if the means for indicating the supported
    data formats was more comprehensive. This could mean a lot of
    expanding in the "works-with-format" section of the vocabulary, which
    doesn't even include formats such as gif or mpg at the moment. I don't
    know how feasible it is to alter underlying debtags functionality, but
    perhaps it would be the easiest to make "works-with-format" a special
    case tag which allows for formats not listed in the vocabulary.
This is my answer:
Good point. The idea has popped up in the past to list supported mime types among the package metadata, so that one could point to a file and get a list of all the packages that can work with it. I'm not sure it's a good idea to encode mime types in debtags and I'd like to see something ad-hoc for it. In the meantime works-with-format is the best we can do, but we should limit it to the most common formats.
This is the fun idea: if works-with-format is the best we can do, what can we do with it? Earlier today I worked on resurrecting some old code of mine to expand Zack's ls2rss with Dublin Core metadata extracted from the files. The mime type scanner was ready for action. Some imports:
import sys
# Requires python-extractor, python-magic, python-apt
# and an unreleased python-debtags from http://bzr.debian.org/bzr/pkg-python-debian/trunk/
import extractor
import magic
from debian_bundle import debtags
import re
from optparse import OptionParser
import apt
A tenative mapping between mime types and debtags tags:
mime_map = (
        ( r'text/html\b', ("works-with::text","works-with-format::html") ),
        ( r'text/plain\b', ("works-with::text","works-with-format::plaintext") ),
        ( r'text/troff\b', ("works-with::text", "works-with-format::man") ),
        ( r'image/', ("works-with::image",) ),
        ( r'image/jpeg\b', ("works-with::image:raster","works-with-format::jpg") ),
        ( r'image/png\b', ("works-with::image:raster","works-with-format::png") ),
        ( r'application/pdf\b', ("works-with::text","works-with-format::pdf")),
        ( r'application/postscript\b', ("works-with::text","works-with-format::postscript")),
        ( r'application/x-iso9660\b', ('works-with-format::iso9660',)),
        ( r'application/zip\b', ('works-with::archive', 'works-with-format::zip')),
        ( r'application/x-tar\b', ('works-with::archive', 'works-with-format::tar')),
        ( r'audio/', ("works-with::audio",) ),
        ( r'audio/mpeg\b', ("works-with-format::mp3",) ),
        ( r'audio/x-wav\b', ("works-with-format::wav",) ),
        ( r'message/rfc822\b', ("works-with::mail",) ),
        ( r'video/', ("works-with::video",)),
        ( r'application/x-debian-package\b', ("works-with::software:package",)),
        ( r'application/vnd.oasis.opendocument.text\b', ("works-with::text",)),
        ( r'application/vnd.oasis.opendocument.graphics\b', ("works-with::image:vector",)),
        ( r'application/vnd.oasis.opendocument.spreadsheet\b', ("works-with::spreadsheet",)),
        ( r'application/vnd.sun.xml.base\b', ("works-with::db",)),
        ( r'application/rtf\b', ("works-with::text",)),
        ( r'application/x-dbm\b', ("works-with::db",)),
)
Code that does its best to extract a mime type:
extractor = extractor.Extractor()
magic = magic.open(magic.MAGIC_MIME)
magic.load()
def mimetype(fname):
    keys = extractor.extract(fname)
    xkeys =  
    for k, v in keys:
        if xkeys.has_key(k):
            xkeys[k].append(v)
        else:
            xkeys[k] = [v]
    namemagic =  magic.file(fname)
    contentmagic = magic.buffer(file(fname, "r").read(4096))
    return xkeys.has_key("mimetype") and xkeys['mimetype'][0] or contentmagic or namemagic
Command line parser:
parser = OptionParser(usage="usage: %prog [options] filename",
        version="%prog "+ VERSION,
        description="search Debian packages that can handle a given file")
parser.add_option("--tagdb", default="/var/lib/debtags/package-tags", help="Tag database to use (default: %default)")
parser.add_option("--action", default=None, help="Show the packages that allow the given action on the file (default: %default)")
(options, args) = parser.parse_args()
if len(args) == 0:
    parser.error("Please provide the name of a file to scan")
And here starts the fun: first we load the debtags data:
# Read full database 
fullcoll = debtags.DB()
tagFilter = re.compile(r"^special::.+$ ^.+::TODO$")
fullcoll.read(open(options.tagdb, "r"), lambda x: not tagFilter.match(x))
Then we scan the mime type and look up tags in the mime_map above:
type = mimetype(args[0])
#print >>sys.stderr, "Mime type:", type
found = set()
for match, tags in mime_map:
    match = re.compile(match)
    if match.match(type):
        for t in tags:
            found.add(t)
if len(found) == 0:
    print >>sys.stderr, "Unhandled mime type:", type
else:
If the user only gave the file name, let's show what Debian can do with that file:
    if options.action == None:
        print "Debtags query:", " && ".join(found)
        query = found.copy()
        query.add("role::program")
        subcoll = fullcoll.filterPackagesTags(lambda pt: query.issubset(pt[1]))
        uses = map(lambda x:x[5:], filter(lambda x:x.startswith("use::"), subcoll.iterTags()))
        print "Available actions:", ", ".join(uses)
If the user picked one of the available actions, let's show the packages that do it:
    else:
        aptCache = apt.Cache()
        query = found.copy()
        query.add("role::program")
        query.add("use::"+options.action)
        print "Debtags query:", " && ".join(query)
        subcoll = fullcoll.filterPackagesTags(lambda pt: query.issubset(pt[1]))
        for i in subcoll.iterPackages():
            aptpkg = aptCache[i]
            desc = aptpkg.rawDescription.split("\n")[0]
            print i, "-", desc
\o/ The morale of the story:

15 January 2007

Enrico Zini: latex-beamer

Some latex-beamer tips Using with source-highlight source-highlight's latexcolor output uses colors that are not available in latex-beamer. Normally one would have to include them with \usepackage[usenames,dvipsnames] color , but under latex-beamer it does not work. One solution is to include the relevant colours from /usr/share/texmf-tetex/tex/latex/graphics/dvipsnam.def:
%% For source-highlight's output
% This unfortunately does not work
%\usepackage[usenames,dvipsnames] color 
% Therefore, I will copy them from /usr/share/texmf-tetex/tex/latex/graphics/dvipsnam.def
\DefineNamedColor named Blue            cmyk 1,1,0,0 
\DefineNamedColor named BrickRed        cmyk 0,0.89,0.94,0.28 
\DefineNamedColor named Brown           cmyk 0,0.81,1,0.60 
\DefineNamedColor named ForestGreen     cmyk 0.91,0,0.88,0.12 
\DefineNamedColor named Purple          cmyk 0.45,0.86,0,0 
\DefineNamedColor named Red             cmyk 0,1,1,0 
\DefineNamedColor named Black           cmyk 0,0,0,1 
\DefineNamedColor named RoyalBlue       cmyk 1,0.50,0,0 
After this is done, including a source is just a matter of:
# In the shell
$ source-highlight -f latexcolor filename.ext
# In the latex-beamer frame
\input filename.ext.tex 
Proportional columns In the latex-beamer documentation I have only seen columns with fixed sizes. \textwidth luckily works:
\begin frame 
  \frametitle Correzione dei compiti 
  \framesubtitle Il programmino da Fortran. 
  \begin columns 
  \column .5\textwidth 
   \tiny
  \input fortran/01-inizio.f77.tex 
   
  \column .5\textwidth 
   \tiny
  \input fortran/02-inizio.py.tex 
   
  \end columns 
\end frame 

Enrico Zini: suspend-on-asus-u5f

Suspend on ASUS U5F I have suspend. The acpi4asus developers now added support for the U5F. I pulled their code and now I can control the screen brightness writing numbers into /etc/acpi/asus/brn. I also discovered that the problem I had on suspend was that the laptop wakes up with some weird brightness setting that causes the light not to turn on. Writing to /etc/acpi/asus/brn I can now manage to turn it on again, and I added trivial script that save /etc/acpi/asus/brn on suspend and restore it on resume. \o/

12 January 2007

Enrico Zini: python-scoping

Python scoping How do you create a list of similar functions in Python? As a simple example, let's say we want to create an array of 10 elements like this:
a[0] = lambda x: x
a[1] = lambda x: x+1
a[2] = lambda x: x+2
...
a[9] = lambda x: x+9
Simple:
>>> a = []
>>> for i in range(0,10): a.append(lambda x: x+i)
...
...but wrong:
>>> a[0](1)
10
What happened here? In Python, that lambda x: x+i uses the value that i will have when the function is invoked. This is the trick to get it right:
>>> a = []
>>> for i in range(0,10): a.append(lambda x, i=i: x + i)
...
>>> a[0](1)
1
What happens here is explained in the section "A Jedi Mind Trick" of the Instant Python article: i=i assigns as the default value of the parameter i the current value of i. Strangely enough the same article has "A Note About Python 2.1 and Nested Scopes" which seems to imply that from Python 2.2 the scoping has changed to "work as it should". I don't understand: the examples above are run on Python 2.4.4. Googling for keywords related to python closure scoping only yields various sorts of complicated PEPs and an even uglier list trick:
a lot of people might not know about the trick of using a list to box variables within a closure.
Now I know about the trick, but I wish I didn't need to know :-(

9 January 2007

Enrico Zini: bts-utils

A couple of BTS utilities I had the idea of creating a script that would tell me which bug numbers have unanswered mails. The idea is simple: get me all the bug numbers for which the last message posted has not been sent neither by me nor by any of the comaintainers. Firstly, I needed a script that gives the e-mail address of the sender of the last message received for a given bug:
$ mkdir cache
$ ./getlast 370102
enrico@debian.org
Then I needed a srcipt that gives the bug numbers currently in open state for a given source package:
$ ./getopen debtags
246678
277626
290457
[...]
Finally I needed to correlate the information from a maintainer database with the results of the previous scripts:
$ ./show-unanswered enrico@enricozini.org enrico@debian.org
Buffy comaintained by xxxxxxx@debian.org, xxxxxxxxx@xxxxxxxx.xx
  bug #269386 answered by me
  bug #293898 answered by me
  bug #294436 answered by comaintainer xxxxxxx@debian.org
  bug #300444 answered by me
  bug #372513 answered by comaintainer xxxxxxx@debian.org
  bug #383610 answered by comaintainer xxxxxxx@debian.org
  bug #384108 unanswered message from xxxxxxxx@debian.org
  bug #384116 unanswered message from xxxxxxxx@debian.org
[...]
This could make some people happy. You can get it with bzr branch http://people.debian.org/~enrico/bts-utils

26 December 2006

Enrico Zini: amis-input-and-charset

Amis and Paiwan input method and character set Arne G tje ( ) created: The scripts, especially Amis, make heavy use of Unicode combination characters. They should display well at least with the Dejavu Sans font in many applications. Try it out: if it displays correctly, you should see: Update: there is now a wiki page on i18n.debian.net.

Enrico Zini: pcmanfm-nautilus

Replace nautilus with pcmanfm I'm sponsoring the upload of pcmanfm and I think it's a very interesting piece of software. There's a new upload coming, and I'd like it to have some instructions on how to replace nautilus with pcmanfm, and possibly how to go back to nautilus. Here's the best I found. Replacing nautilus with pcmanfm To have pcmanfm start instead of nautilus:
  1. Go to Desktop -> Preferences -> Session manager
  2. Go to the 'Current Session' tab
  3. There's an entry like 40 Restart nautilus --sm-config-prefix /nautilus-SoMeThInG/: remove it
  4. Go to the 'Startup Programs'
  5. Add an entry to run pcmanfm
Alternatively:
  1. Run gnome-session-remove nautilus
  2. Go to Desktop -> Preferences -> Session manager
  3. Go to the 'Startup Programs'
  4. Add an entry to run pcmanfm
To configure pcmanfm to draw the background:
  1. Run pcmanfm
  2. Go to Edit -> Preferences
  3. Go to the Desktop tab
  4. Enable "Show file icons on desktop"
  5. Customise wallpaper as you wish
Alternatively, I wrote a little script that will generate a ~/.pcmanfm/main configuration file from you taking some settings from gconf:
#!/bin/bash
# Generate a pcmanfm configuration file reading values from gconf
echo "# ~/.pcmanfm/main configuration file generated by $0"
echo
echo '[General]'
echo 'terminal=gnome-terminal'
echo
echo '[Desktop]'
echo 'showDesktop=1'
# Detect wallpaper setting
WALLPAPER= gconftool-2 --get /desktop/gnome/background/picture_filename 
if ! [ -z "$WALLPAPER" ]
then
    echo 'showWallpaper=1'
    echo "wallpaper=$WALLPAPER"
fi
# Detect color setting (doesn't really work: I could not find significant keys)
#COLOR= gconftool-2 --get /desktop/gnome/background/primary_color 
#if ! [ -z "$COLOR" ]
#then
#   R=$(( $(printf %d 0x$ COLOR:1:2 ) * 65536 / 256 ))
#   G=$(( $(printf %d 0x$ COLOR:3:2 ) * 65536 / 256 ))
#   B=$(( $(printf %d 0x$ COLOR:5:2 ) * 65536 / 256 ))
#   echo "Bg1=$R,$G,$B"
#fi
Getting nautilus again
  1. Kill pcmanfm
  2. Run nautilus: it will register itself with the session manager
Open questions Originally, I had nautilus registered in the session manager as something like nautilus --sm-config-prefix /nautilus-SoMeThInG/. After removing it and having it reregister itself, I have it only as nautilus. I have not been able to find out what is the difference. It would also be cool to have a little program that registers pcmanfm as a 'Restart' entry with priority 40, just like nautilus.

Enrico Zini: earthquake

Shakey Interesting experience.

24 December 2006

Enrico Zini: paiwan-character-list

Character list for the Paiwan language We mapped the available glyphs and accents for the Paiwan language. The letters in alphabetical order:
a b c d e f h i j k l m n p q r s t u v w y z   n       
No uppercase. All the characters are in Unicode except n , which already needs to be requested for the Amis script. We need to design an input method to enter the underlined letters and the n .

Next.

Previous.