/* no comment */

14 Dicembre 2009 di vrde

E Gabriella Carlucci, parlamentare del Pdl, rilancia:

«Internet e i social network stanno diventando, ogni giorno di più, canali e strumenti di diffusione di odio e veleno. È giunto il momento di eliminare definitivamente l’anonimato in rete».

[via Corriere della Sera]

Grazie a folengo ecco qua anche il post della Gabry: Il problema dell’anonimato in rete.

python-wave-surfer aka “a simple wave API”

10 Dicembre 2009 di vrde
Outdated! Please refer to the wiki in Bitbucket
pywave-notify in action

Here is my simple implementation for a google wave API — deeply inspired by hiroshi’s work and from a folengo’s idea.

The API module, wave.py, implements only the login and two functions to retrieve your waves. The API module uses the Python Standard Library so just import it (on GNU/Linux, mac os, win and… Symbian maybe?) and play :)

>>> import wave
>>> wave.login('user@gmail.com', 'password')
>>> wave.get_unread_waves()
[{'url': u'googlewave.com!w+xxxxxxx', 'total': 37, 'unread': 5, 'title': u'OT'}, {'url': u'googlewave.com!w+xxxxxxx', 'total': 26, 'unread': 3, 'title': u'ciao pythonisti!'}, {'url': u'googlewave.com!w+xxxxxxx', 'total': 2, 'unread': 2, 'title': u'Automation in InDesign'}]

You can clone the repo from Bitbucket or download the tarball.

On top of this minimal API I wrote a notifier using pynotify (so it runs on Gnome and KDE without any problem), this is the code:

import sys
import time
import getpass
import pynotify
import wave

pynotify.init('pywave-notifier')

if len(sys.argv) != 2:
    print 'usage: notifier.py youraccount@gmail.com'
    sys.exit(0)

wave.login(sys.argv[1], getpass.getpass("password: "))
lastmsg = u''

while True:
    unread = wave.get_unread_waves()
    msg = u''

    for item in unread:
        msg += '%(title)s (%(unread)s/%(total)s)\n'\
            % item

    # yep, not so perfect (:
    if msg != lastmsg:
        n = pynotify.Notification(
            "%s unread waves" % len(unread), msg)
        n.show()
        lastmsg = msg

    time.sleep(3*60)

Caro Candidato @ LinuxDay 2009

28 Ottobre 2009 di vrde

Sabato 24 ottobre, in occasione del LinuxDay, ho presentato l’iniziativa Caro Candidato (sì, sempre quella!).

Devo ringraziare moltissimo i ragazzi di OpenLabs che sono riusciti a trovare, all’ultimo momento, 30 minuti per farmi presentare l’iniziativa.

Queste sono le slide che ho presentato:

download pdf

(ho anche sistemato la percentuale errata, avevo scritto qualcosa tipo:
50 aderenti -> 6 eletti -> 8.3%
alla slide #8 trovate la versione corretta)

checc’avevo un po’ ddansia, devo ancora farmi le ossa per presentare davanti al pubblico ma non mi sembra sia andata male :P

La scuola deve formare cittadini e non consumatori (cit.)

8 Ottobre 2009 di vrde

Il 5 ottobre l’Associazione per il Software Libero ha pubblicato il comunicato stampa dal titolo Software libero per la scuola.

Brunetta e la Gelmini il 25 settembre parlano di nuove iniziative per la scuola digitale.
Nuove iniziative per la scuola digitale vuol dire tutte le cose belle che potete pensare: efficacia, accessibilità, semplificazione, ottimizzazione, diffusione di strumenti informatici e contrasto all’analfabetismo digitale.

Ma come si implementa™ l’innovazione digitale nella scuola? Basta firmare un protocollo di intesa con Microsoft (il pdf è una simpatica scansione… e parlano di innovazione… WTF!).

E come non infilarci dentro i terremotati per rendere l’iniziativa più nobile? Dall’art. 2 del protocollo:

Le Parti concorderanno iniziative da porre in essere per le istituzioni scolastiche coinvolte nel terremoto dell’Abruzzo, in particolare per quelle poste nella zona cratere.
Tali iniziative, disciplinate da specifico accordo, saranno volte a sostenere l’offerta formativa delle istituzioni coinvolte per permettere alle stesse di riprendere in tempi brevi l’erogazione dei servizi.

Se li mettete in mezzo abbiate almeno l’accortezza di definire quali saranno queste iniziative.

Gli impegni di Microsoft

A costo zero si impegna a (qui solo alcune, per tutte dai un occhio all’Art. 3 del protocollo):

  • fornire gratuitamente il sistema operativo e/o applicativo;
  • collaborare con le proprie consociate affinché vengano riconosciute a studenti e docenti condizioni agevolate d’acquisto di soluzioni e prodotti;
  • trovare sinergie™ tra le iniziative del Piano del MIUR [...], il Piano eGov2012 ed i programmi Microsoft al fine di arricchire l’offerta formativa rivolta agli studenti nell’area delle ICT;
  • mettere a disposizione i propri contenuti multimediali, denominati digital literacy, per trasmettere adeguate conoscenze e abilità nell’uso delle nuove tecnologie a docenti e studenti di istituti scolastici di ogni ordine e grado;
  • rendere disponibile per InnovaScuola contenuti digitali dei propri archivi [...] per consentire ai docenti la produzione di contenuti didattici regolati secondo i principi dei Creative Commons; [lodevole, ma generico, che licenza?]
  • [questa è bella, giusta per concludere questa serie di cazzate] promuovere concorsi tra gli studenti al fine di incoraggiarli a utilizzare la loro immaginazione, passione e creatività per cercare soluzioni a problemi concreti attraverlo le nuove tecnologie e per la produzione di contenuti didattici digitali che saranno messi a disposizione sulla piattaforma Innovascuola;

Gli impegni della Gelmini e di Brunetta

Anche qui alcuni, non tutti:

  • offrire supporto per il coinvolgimento degli Uffici Scolastici Regionali e Provinciali per una
    migliore comunicazione delle iniziative, per il coinvolgimento di esperti a livello locale e per
    la realizzazione su base territoriale degli obiettivi e delle iniziative; [bello, ma gli esperti sono per caso i partner certificati Microsoft?]
  • sostenere, in tutti i casi in cui lo si riterrà opportuno, l’utilizzo da parte di docenti e studenti dei contenuti formativi messi a disposizione da Microsoft come “Digital Literacy”
    attraverso la loro diffusione sui canali di comunicazione del MIUR. [ah quindi spingono perché la gente usi prodotti Microsoft]

insomma…

Onestamente Microsoft non è che mi stia proprio simpatica, Brunetta lo conosciamo anche per JumPC e della Gelmini non parliamo.

Al di là di quello che ho scritto in questo post (faccio parte della cerchia di consulenti dell’Associazione per il Software Libero ma ovviamente nel mio blog sto parlando a nome mio), la conclusione del comunicato stampa di Assoli è la seguente:

Per questo l’Associazione per il Software Libero ha deciso di intervenire nel procedimento amministrativo in corso con un’istanza trasmessa oggi al Ministro dell’Istruzione dell’Università e della Ricerca ed al Ministro per la Pubblica Amministrazione e l’Innovazione, e, per il miglior perseguimento del bene comune, domanda la modifica del Protocollo di Intesa sottoscritto con Microsoft S.r.l..

Boris — Pink

5 Ottobre 2009 di vrde

how to use WSGI + Authkit + Beaker for OpenID authentication

20 Settembre 2009 di vrde

openid auth form

This is a simple how to for enabling OpenID authentication using Authkit (and Beaker, we need cooookies!!!) over WSGI.

The following snippet is inspired by the (broken?) example I found in the Pylons documentation wiki.

from authkit.authenticate import middleware, sample_app
from beaker.middleware import SessionMiddleware

app = middleware(
    sample_app,
    setup_method='openid,cookie',
    openid_path_signedin='/private',
    openid_store_type='file',
    openid_store_config='',
    cookie_secret='secret encryption string',
    cookie_signoutpath = '/signout',
)

app = SessionMiddleware(app, key='mysession', secret='randomsecret')

if __name__ == '__main__':
    from paste.httpserver import serve
    serve(app, host='0.0.0.0', port=8080)

TODO: fix the broken example in the wiki (:

how to use simple HTTP auth with hg serve

2 Settembre 2009 di vrde
Logo Mercurial

Last night Kiwi and I were exploring Mercurial for our über-secret-project.
Mercurial is, like GIT, a distributed revision control system (if you want to deeply understand the differences between those two systems take a look to http://gitvsmercurial.com/)

After some tinkering with the great hg command, we discovered how to collaborate with other people using the informal sharing (thanks to hg serve).

With the informal sharing we both expose our repos in a read-only mode so we can hg clone or hg pull changes. No hg push is permitted (it is read-only!).

Note that:

Because it provides unauthenticated read access to all clients, you should only use hg serve in an environment where you either don’t care, or have complete control over, who can access your network and pull data from your repository.

hg serve hasn’t anything for access control… but we need it ’cause our project is an über-secret-project. Of course we can use Mercurial with ssh, but hg serve is so cool :D

And here is the second part aka the beauty of WSGI specification.

Mercurial is written in python, the hg serve is also a python program and the hgweb (the mercurial web-app module) exposes a very toasty class: mercurial.hgweb.hgweb_mod.hgweb [kudos to tomfmason]

An hgweb object is a WSGI application so you can use it with any middleware you like. For a basic HTTP auth I used authkit (you can find a simple example in the pylonshq wiki, if you run the example please note that the protected area is under the http://localhost:8080/private path).

After a lot of swearing^H^H^H^Hting (I never used WSGI before) this is the result:

from paste import httpserver
from mercurial.hgweb.hgweb_mod import hgweb

from authkit.authenticate import middleware
from authkit.permissions import RemoteUser
from authkit.authorize import authorize_request

PATH_TO_REPO = '/home/vrde/work/secret-project'
TITLE = 'secret project repo'

hgapp = hgweb(PATH_TO_REPO, TITLE)
def simple_app(environ, start_response):
    authorize_request(environ, RemoteUser())
    response = hgapp(environ,start_response)
    return response

def valid(environ, username, password):
    return username == 'kiwi' and password == 'antani'

app = middleware(
    simple_app,
    setup_method='basic',
    basic_realm='Secret Project Realm',
    basic_authenticate_function=valid
)

httpserver.serve(app, host='0.0.0.0', port='8000')

If you want to try the snippet you need paste and authkit frameworks.

The code wraps the Mercurial server and asks for user and password, if the auth is successful the client can clone, pull or visit the web interface of the repo.

TODO: patch the hg serve source and add a parameter for the simple HTTP auth.

Cheers from Boarduino!

22 Agosto 2009 di vrde

Boarduino v1.0

Wow, the days at HAR were fuckin’ awesome.

Thanks to Mitch Altman and his willing friend I bought and build an Arduino clone: the Boarduino.

What is an Arduino?

Arduino is a tool for making computers that can sense and control more of the physical world than your desktop computer. It’s an open-source physical computing platform based on a simple microcontroller board, and a development environment for writing software for the board. [from Arduino - Introduction]

Boarduino Kit

Boarduino Kit

The Boarduino is 100% compatible with the Arduino software, the main differences are:

  • the USB port is replaced with a serial header (so you need a USB to TTL converter);
  • it can easily be inserted on a solderless breadboard;
  • you make it (: (soldering is a fun!). [this is true for the Arduino too]
Boarduino Kit - making

Boarduino Kit - da making

After a very relaxing soldering (really! it clears your mind! or it was the soldering vapours… never mind…) Mitch connected the Boarduino to the laptop and, wow, it worked :D

(If you, like me, don’t know how to connect the TTL cable remember: GRN means green, not ground! :P )

Boarduino Kit - yeah (:

Boarduino Kit - yeah (:

Today I flashed the ATmega328P with a sketch (the evergreen “Hello World!”) I found in the Arduino Software.

This is the code for the Boarduino:

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Hello World!");
}

and this is the result in the python interpreter:

>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600)
>>> while 1:
...     ser.readline()
...
'rld!\r\n'
'Hello World!\r\n'
'Hello World!\r\n'
'Hello World!\r\n'

Cool, it worked :D

I have got some problems with /dev/ttyUSB0 because of brltty, I just removed it and everything is OK now.

domani si parte per l’HAR!

11 Agosto 2009 di vrde

Logo HAR

Si parte in macchina con protoboard, inverter, alimentatore (ATX!) 12 V per il frigo, frigo, ciabatte, sottotenda, sopratenda, infratenda, tenda, computer (eh senza backup… mi piace il rischio), lockpick, della prugna in testa, il saldatore di kiwi e voglia di fare cose random.

Per chi ci sarà, ci vediamo là. Per chi non c’è mi dispiace :P vediamo se riesco a tenere un minimo aggiornato il blag.

ciao!

Check broken link in a bunch of static html files (python version)

7 Agosto 2009 di vrde

OK, this time we are more pythonic (:
The small script looks for html files in the current directory (but you can change the base dir passing it as the first argument to the script) and tells you which local links are broken.

#!/usr/bin/env python
import os, sys
import lxml.html

stats = dict(
    checked = 0,
    broken = 0
)

def valid_link(dirpath, link):
    # checks only local links
    if '://' not in link:
        return os.path.exists(os.path.join(dirpath, link))
    return True

def check(dirpath, filename):
    fullfile = os.path.join(dirpath, filename)
    try:
        html = lxml.html.fromstring(open(fullfile).read())
    except:
        print '[ERROR]'
        print '    file: %s' % fullfile
        return

    for element, attribute, link, pos in html.iterlinks():
        stats['checked'] += 1
        if not valid_link(dirpath, link):
            print '[BROKEN]'
            print '    file: %s' % fullfile
            print '    link: %s' % link
            print
            stats['broken'] += 1

if __name__ == '__main__':
    basedir = '.'
    if len(sys.argv) == 2:
        basedir = sys.argv[1]
    for dirpath, dirnames, filenames in os.walk(basedir):
        htmls = filter(
            lambda f: f.endswith('.html'),
            filenames)
        for f in htmls:
            check(dirpath, f)

    print '[STATS]'
    print '    checked: %s' % stats['checked']
    print '     broken: %s' % stats['broken']

P.S.: lxml rocks.