SQLite Blessing

I just found this in the SQLite source code, just fantastic:

[source:c::firstline(30)] /************** Begin file sqliteInt.h ***************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. **


** Internal interface definitions for SQLite. ** ** @(#) $Id: sqliteInt.h,v 1.658 2008/01/30 16:14:23 drh Exp $ */

ifndef SQLITEINT_H

define SQLITEINT_H

[/source]

Null References

There’s an interesting discussion going on these days on Ruby blogs about, basically, how to avoid one of the most common, annoying, easy-to-create bugs in any programming language: calling a method on a null reference (or pointer, depending on your language).

This single issue happens all the time, in garbage-collected and non-managed languages, static and dynamic, weakly and strongly typed; you have a handler variable “pointing” to an object, and before calling any methods on it, you’d better be sure that the object is there; you end up using assertions, “if” statements (and all of its variants), boilerplate code all over the place, when everything you want to do is to call that damn method. It’s frustrating, time-consuming and oh so common that we just try to not to think about it anymore. Continue reading

declaracion antimilitaristas de america latina

(recibido por e-mail)

No necesitamos otra guerra más. Nosotras/os, objetoras y objetores de conciencia y antimilitaristas del Ecuador, Colombia, Venezuela, y toda América Latina y el Caribe, unidos, nos negamos rotundamente a una escalada bélica que desemboque en una guerra que, nuevamente, nos intente dividir. Ya bastante tenemos con el hambre, la corrupción, el militarismo exacerbado, el impúdico gasto militar, la inseguridad ciudadana, el continuo bofeteo a los derechos humanos por parte de nuestros gobernantes, para que nos quieran regalar un conflicto armado más.

Una guerra sólo fortalecerá los respectivos nacionalismos de los países en conflicto, aumentando la xenofobia instalada en nuestros países. Fortalecerá a las Fuerzas Armadas, que encontrarán otra razón para incrementar sus presupuestos y servirá para esconder aún más los problemas que nos aquejan como pueblos latinoamericanos y del Caribe: la explotación sin control de nuestros recursos, los altísimos niveles de desempleo, la discriminación y violencia de género, la corrupción y las mafias del poder, las comunidades desplazadas por conflictos bélicos o por monocultivos agrícolas y forestales, el racismo y la discriminación por clase, etc. Nada eso se solucionará por la guerra. Al contrario, significará que esos problemas aumentarán como han aumentado en cada dictadura y guerra civil.

Una guerra entre estados latinoamericanos es, al mismo tiempo, una conflagración civil entre pueblos hermanos, conducidos al matadero por gobiernos militaristas, tanto de derecha como de izquierda. Los únicos vencedores de un enfrentamiento fratricida entre hermanas y hermanos son los comerciantes globales de armas, que desde Estados Unidos hasta la Federación Rusa, construyen laboratorios de guerra y opresión en nuestros países bajo eufemismos como el “Plan Colombia”.

Decimos no a la guerra y a sus preparativos. No al fortalecimiento de cualquier militarismo, sea de derecha e izquierda. Sí a la autonomía de los pueblos y de sus luchas. Sí al hermanamiento latinoamericano.

Convocamos a una acción conjunta contra el militarismo y la guerra, partiendo desde nuestra convicción de seguir trabajando juntas y juntos por la promoción de la justicia y la solidaridad, fuera de los cuarteles, en cada uno de nuestros países.

Antimilitaristas de Latinoamérica y el Caribe

Organizaciones:

Internacional de Resistentes a la Guerra – IRG/WRI Grupo de Afinidad Antimilitarista de Asunción GAAA (Asunción-Paraguay) Pelao Carvallo, consejero IRG Yeidy Luz Rosa Ortiz, Casa Feminista de Rosa – Quito, Ecuador Periódico El Libertario – Venezuela Xavier León, Grupo de Objeción de Conciencia del Ecuador – GOCE Movimiento Antimilitarista y de Objeción de Conciencia MAOC Chile Adriana Castaño Román, Red Juvenil de Medellín, consejera IRG Accciòn Colectiva de Objetoras y Objetores de Conciencia (ACOOC) Bogotá Elda Munch Comini, Rosario, Santa Fe, Argentina.

adhesiones a : antimililat@gmail.com

REST + HTTP (Basic + Digest) Authentication support for Django’s test Client class

Django has a nice support for unit and functional testing; however, its django.test.client.Client class does not support PUT and DELETE requests, which might be useful if, like me, you’re doing some kind of REST implementation using that framework. There’s an open ticket about it, but for the time being, here’s my wrapper that supports those methods as well as GET and POST:

[source:python] from cStringIO import StringIO from django.test.client import Client as DjangoClient, encode_multipart from django.utils.http import urlencode import base64 import md5

class Client(DjangoClient): “”" Wrapper and drop-in replacement around Django’s own test “Client” class, providing PUT, DELETE and OPTIONS support, as well as HTTP Basic + Digest Authentication support. NOTE: the django.test.client.Client does not directly support PUT, DELETE or OPTIONS requests so we’re using the “request()” method directly… there’s an open ticket about it: http://code.djangoproject.com/ticket/5888 “”"

auth = { }
def http_basic_login(self, username, password):
    base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
    self.auth = { "HTTP_AUTHORIZATION": "Basic %s" % base64string }
def http_digest_login(self, method, url, params, response, username, password):
    (authmeth, auth) = response['WWW-Authenticate'].split(" ", 1)
    if authmeth.lower() != 'digest':
        return
    amap = {}
    for itm in auth.split(", "):
        (k, v) = [s.strip() for s in itm.split("=", 1)]
        amap[k] = v.replace('"', '')
    try:
        realm    = amap['realm']
        qop      = amap.get('qop', '')
        nonce    = amap['nonce']
        opaque   = amap['opaque']
    except:
        return
    cnonce = "01b6730aae57c007"
    nc = "00000001"
    query_string = "&".join(["=".join(item) for item in zip(params.keys(), params.values())])
    uri = url + "?" + query_string
    ha1 = md5.md5('%s:%s:%s' % (username, realm, password)).hexdigest()
    ha2 = md5.md5('%s:%s' % (method, uri)).hexdigest()
    if qop:
        chk = "%s:%s:%s:%s:%s:%s" % (ha1, nonce, nc, cnonce, qop, ha2)
    else:
        chk = "%s:%s:%s" % (ha1, nonce, ha2)
    response = md5.md5(chk).hexdigest()
    self.auth = {
        "HTTP_AUTHORIZATION": 'Digest username="%s", realm="%s", nonce="%s", uri="%s", response="%s", opaque="%s", qop=auth, nc=%s, cnonce="%s"' % (username, realm, nonce, uri, response, opaque, nc, cnonce),
    }
def http_logout(self):
    self.auth = {}
def pre_request(self, url, data):
    r = {
        'CONTENT_LENGTH':  None,
        'CONTENT_TYPE':    'text/html; charset=utf-8',
        "HTTP_USER_AGENT": "Django Unit Test HTTP Client",
        'PATH_INFO':       url,
        'QUERY_STRING':    urlencode(data, doseq=True),
    }
    r.update(self.auth)
    return r
def get(self, url, data, **extra):
    r = {}
    r.update(extra)
    r.update(self.auth)
    return DjangoClient.get(self, url, data, **r)
def post(self, url, data, **extra):
    r = {}
    r.update(extra)
    r.update(self.auth)
    return DjangoClient.post(self, url, data, **r)
def delete(self, url, data):
    r = self.pre_request(url, data)
    r["REQUEST_METHOD"] = "DELETE"
    return self.request(**r)
def options(self, url, data):
    r = self.pre_request(url, data)
    r["REQUEST_METHOD"] = "OPTIONS"
    return self.request(**r)
def put(self, url, data, form):
    BOUNDARY = 'BoUnDaRyStRiNg'
    MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
    encoded = encode_multipart(BOUNDARY, form)
    r = self.pre_request(url, data)
    r.update({
        'CONTENT_LENGTH': len(encoded),
        'CONTENT_TYPE':   MULTIPART_CONTENT,
        'REQUEST_METHOD': 'PUT',
        'wsgi.input':     StringIO(encoded),
    })
    return self.request(**r)
def hello(self, url, data, **extra):
    """Sends a fake 'HELLO' request which returns a 405 answer :)"""
    r = self.pre_request(url, data)
    r["REQUEST_METHOD"] = "HELLO"
    r.update(extra)
    return self.request(**r)

[/source]

Hope it helps! Of course you could extend this to support OPTIONS, HEAD or other HTTP methods you could find in the specification.

Update, 2008-03-05: Following Yoan’s comment below, I’ve DRYed the code a bit. Neat.

Update, 2008-03-11: I’ve added HTTP Basic Authentication support to the class (and changed the post title accordingly).

Update, 2008-03-13: Another modification: now the client supports HTTP Digest Authentication (Yay! To use it, make a first call to your server and then pass the response as a parameter to the http_digest_login method), plus support for the OPTIONS verb, plus another method which sends a method with a “HELLO” verb, which of course does not exist… and which will (normally) return a 405 response!

Now this is ridiculous

Generics in JavaScript.

Who came up with this? Let’s put things in context: JavaScript is a dynamic language. It turns out that this characteristics deeply upsets many people, particularly those who prefer to rely on a compiler to check their code for them before running it. It turns out that these guys also have a hard time imagining their objects in memory, what do they look like, what they do, and so on, and for them ECMAScript 4 will bring types, that is, variables declared both with the var keyword and a special type declaration after the variable name. There is an illusion built around statically typed languages. I know it: I’ve already advocated them as the silver bullet that never existed. But I was wrong, and I admit it. Personally I think that dynamic languages are the future.

The problem with statically typed languages is that “collections” or “containers” of things should also be typed, because otherwise you spend a good deal of CPU time boxing and casting instances, because otherwise you might as well “put a cat in a dog collection” as one commenter put in the Ajaxian page above.

I am sorry but, in the case of JavaScript, the evolution of the current draft is becoming ridiculous, even after you throw in all your arguments about performance, IDE support and who knows what else:

[source:javascript] function reprimand(list:List.< +Employee>) { … } var writingTeam:List. = new List.(); reprimand(writingTeam); // no error if ECMAScript adopts this style of variance annotation [/source]

ActionScript 3 developers can already enjoy this “syntax sugar”. Ugh! Continue reading

How to count words in LaTeX files?

I am a big LaTeX fan, mostly thanks to my friend Cedric who introduced me to it ;) And I don’t regret it at all; there is simply no better way to create long, beautiful PDF documents, particularly during these times of dissertation writing! I’m in my last step towards the Master’s degree I’ve been working on for the last two years, and creating documents is an important part of that.

LaTeX works for me, because:

  1. It’s cross-platform (and I need that for my project!);
  2. It’s text based (I can edit the files with any decent editor; personally I use and TexShop and sometimes TextMate);
  3. I can generate PDF, plain text, RTF, and much more from the same source;
  4. I can split my documents in several others and work separately in each;
  5. I can generate meaningful diffs using Subversion (to see what I’ve changed in every revision);
  6. I can manage the bibliography for my papers easily (using the awesome BibDesk tool);
  7. I don’t have to cope with a buggy text editor that crashes every so often!
  8. I can generate gorgeous, absolutely beautiful documents. Easily.

For my last document, the dissertation, I have a numeric limit in the number of words (~ 10K to 15K words) and I need to count the number of words in the documents I generate. Since I’m not using Word, nor KOffice nor OpenOffice, this simple requirement becomes more complex to fulfill. But working in a Unix environment has its benefits; first I found this solution:

$ detex file.tex | wc -w

This command provides a first approach to the problem; however, it just strips off the LaTeX commands, even those that generate content in the final document. For example, if you have a macro that puts in bold the name of your project, those words will not appear in the final calculation even if they do appear in the final document. Clearly not acceptable. Googling a bit more, I found what I was looking for:

$ ps2ascii file.pdf | wc -w

In this case we’re working on the final PDF document, and of course the final result is much, much more interesting.

Happy typesetting!