Latest posts.

Dynamic Error Pages in Rails 3 with Goalie

As part of my work on Shapado in the Google Summer of Code, I just released a Rails3-compatible little gem (called Goalie) that makes it easy to have custom error pages with dynamic content. It is still very early-stages and I would like your feedback. Here’s the release README. Enjoy!


Goalie

Goalie is a flexible dynamic error response renderer for
Rails built on Rack and Rails Engines. It provides the same
default error pages as Rails, but allows you to easily customize
them with dynamic content. This means you can use your
application layout, have different error pages for different
subdomains, and do all sorts nice things.

Installation

WARNING: at this point, Goalie is highly experimental and
should not be used in production!! Everything can and probably
will change before it is ready for production. Install it only if
you want to play with and/or contribute to it.


gem install goalie

After you install it and add it to your Gemfile
, you have to require it together with Rails’ frameworks
at the top of your config/application.rb file:


require 'goalie/rails'

This will remove Rails’ default exception renderer middleware
( ShowExceptions ) and use Goalie’s
instead. Unless you have custom static pages in your
public
directory (which we plan to support later), this
will be a drop-in replacement.

Customization

Controllers

The public (production) rescuing of errors is done by the
PublicErrorsController found in Goalie’s
app/controllers
directory. If you create a controller
with the same name, it will automatically be used instead of
Goalie’s. All it needs to do is support the following actions:

  • internal_server_error
  • not_found
  • unprocessable_entity
  • conflict
  • method_not_allowed
  • not_implemented

If you don’t actually need a separate action for each of
these errors, you can redirect them to others, for example, with:


def unprocessable_entity
  render :action => 'internal_server_error'
end

Views

You can also customize only the views and use Goalie’s
default controller. All you need is to have inside
app/views/public_errors
views with the same names as the
actions listed above. Besides the standard stuff that Rails makes
available to views, you will also have access to the following
instance variables:

Be VERY careful when using this in production, as you could
expose sensitive information inside the request and
exception. Generally, you probably shouldn’t use these variables
at all. The only place it makes sense is to have a more detailed
error screen for admins or other high-level users.

Credit

Goalie copies a lot of code and ideas from:

* Rails’ ShowExceptions middleware
* Rails’ default error views
* Rails’ exception_notification plugin

Which are mostly the work of
Joshua Peek
, with help from various contributors. We’re
highly indebted to them and thank them a lot for their work.

Contributions

Any form of feedback, patches, issues, and documentation are
highly appreciated.

License

MIT license. Copyright 2010 Helder Ribeiro.

  • Share/Bookmark

Seeing production error pages in Rails 3 on local machine

So you’re programming on Rails 3 and you want to see how your 404 or 500 error page looks like to the end user. You think “that’s easy, all I have to do is run in production mode”, right? Yo do that, run to your browser, type in a bogus address and voilà… A stack trace! Wha..? I thought I was in production mode, shouldn’t I see the red default error page that comes with Rails (or your custom one)? Well, you are, and yes, you should. But that’s not how things work right now.

What happens is that, even in production mode, Rails shows you the stack trace if it sees that the request is coming from localhost. Previously, on Rails 2.x, this was decide by the method local_request? which lived in ActionController::Base, so all you had to do (according to the docs) to fix that was to override it on your application controller with something like:


def local_request?(*args)
  RAILS_ENV == 'production' ? false : true
end

But on Rails 3 (since this commit), exception handling isn’t done inside the controller anymore, it’s Rack-based, and so is the local_request? method. That means you can’t override it from inside your application controller anymore. And there isn’t properly-exposed API or documentation for how to work around this, so you’re screwed!

Oh wait, it’s Ruby, right? What’s another monkey-patch anyway?

So here it goes:


# Put this at the end of config/environments/production.rb

class ActionDispatch::ShowExceptions
  def local_request?(*args)
    false
  end
end

Hopefully this will be more properly configurable in the future.

Update: this isn’t checked on ShowExceptions anymore, it’s now a method on the Request object, so instead of the above, you need this:


# Put this at the end of config/environments/production.rb

class ActionDispatch::Request
 def local?
   false
 end
end

Thanks to Daniel Cadenas for the heads up in the comments :)

  • Share/Bookmark

Installing MongoDB on Gentoo

So I had some trouble running the good old “sudo emerge mongodb -va” due to some issues. After installing it by hand I found this little portage overlay that handles things better, but it has an outdated version of MongoDB, so I’ll show you how to get the latest and greatest. It’s all very basic, but since I’m no sysadmin, I still had to wrestle with things a bit to get it working, so I hope to relieve others of the same effort.

Since the problem was with one of the dependencies (spidermonkey), you’ll need the static version, that is, the one that comes with all the dependencies compiled in. Below is the one I used, but make sure to find the latest tgz for your platform here (choose the “legacy-static”).


wget http://downloads.mongodb.org/linux/mongodb-linux-i686-static-1.4.2.tgz

After that, basically all you have to do is follow the instructions on this guide. It’s in German, but you can get what you have to do from the commands it tells you to run (the automatic translation is also not so bad).

The only thing you’re not supposed to do is copy the script in the section “Start-Stop Script”. It is meant for Debian distributions and won’t work on Gentoo because of some missing commands. So instead, copy the script below into /etc/init.d/mongodb, give it +x permission and follow the rest of the guide as usual. Let me know if you run into any troubles!


#! /bin/sh
# start / stop script for mongodb

### BEGIN INIT INFO
# Provides: mongod
# Required-Start: \$remote_fs \$syslog
# Required-Stop: \$remote_fs \$syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start mongod at boot time
# Description: Enable service provided by mongod.
### END INIT INFO

# Source function library.
#. /lib/lsb/init-functions

retval=0
pidfile=/var/run/mongodb.pid

exec="/opt/mongodb-linux-i686-static-1.4.1/bin/mongod"
prog="mongod"
config="/etc/mongodb/mongodb.conf"
lockfile="/var/lock/mongod"

[ -e $config ] && . $config

start() {
if [ ! -x $exec ]
then
echo $exec not found
exit 5
fi

echo "Starting mongoDB daemon"
echo $prog

start-stop-daemon --start --pidfile $pidfile -m -c $MONGO_USER \
--exec $exec -- $MONGO_OPTS run > /dev/null 2>&1 &
retval=$?

if [ $retval -eq 0 ]
then
echo 0
else
echo 1
fi
return $retval
}

stop() {
echo "Stopping mongoDB daemon"
echo $prog
start-stop-daemon --stop --pidfile $pidfile --retry 10 \
--exec $exec

retval=$?

if [ $retval -eq 0 ] && rm -f $lockfile
then
echo 0
else
echo 1
fi
rm -f $pidfile
return $retval
}

restart() {
stop
start
}

reload() {
restart
}

# See how we were called.
case "$1" in
start)
$1
;;
stop)
$1
;;
restart)
$1
;;
reload)
$1
;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 2
esac

exit $?

  • Share/Bookmark

Accepted GSoC Proposal: Plugin system and machine-tags for Shapado

This is the proposal I sent to the Google Summer of Code to work on Shapado for the Encyclopedia of Life. It has just been accepted! :D


== Abstract ==

The Encyclopedia of Life wants to use Shapado, a FOSS project, as a Q&A system for its database of species. Many of the customizations needed are not of general interest so, to avoid feature creep, this GSoC project intends to create a plugin system for Shapado to allow creation and sharing of features while keeping a clean and solid core. It also intends to implement machine tags as a first plugin, making the EOL-Shapado integration more immediately possible.

== Background ==

My name is Helder dos Santos Ribeiro (obvio171 on IRC), born and living in Brazil.

I am a frequent user of StackOverflow/ServerFault/SuperUser and I host two StackExchange sites myself, one for Brazilian college students to do Q&A on the courses they’re taking (http://umamao.com.br) and another one for translators (http://betweenmywell.com). This means I’m very familiar with the domain and with how the Q&A engine should work, both from the user and the admin sides. I also plan to port my StackExchange websites over to Shapado at some point, so I’ll be a direct user of the project myself and will likely have a long-term involvement with it.

I’m also very familiar with the main technology used in Shapado, Ruby on Rails (RoR). I’ve worked professionally with RoR before, mostly as internship + freelance work for Europe’s leading local reviews website, Qype. Their web application is closed-source so I can’t show code samples of my work there, but I have code from personal projects and small contributions to other open source projects at http://github.com/obvio171.

I have also successfully completed two GSoC projects before, one in 2007 with Ruby Central as mentoring organization and the other in 2009 with Review Board.

I’m currently studying Computer Engineering at Unicamp (State University of Campinas – http://en.wikipedia.org/Unicamp). Unicamp is considered to have one of the best Computer Engineering courses in Latin America.

== Motivation ==

The Encyclopedia of Life Project (http://eol.org) aims to be a database of all species known to science. One direction in which this database is filled with good information is that where knowledgeable individuals supply what they know, editing and improving the website so that, when that information is demanded, it is already available. This form of input is already possible today. Another way to aggregate information is to have it be driven by demand, that is, to let one user explicitly point out, in the form of a question, something she was looking for and couldn’t find, and let other users answer with what they know. This form of input is currently not supported, and this is what this project aims to help fix.

== Deliverables ==

EOL’s development process uses an agile approach, with iteration meetings every 2 weeks where work for the next two weeks is decided based on feedback from what was accomplished in the previous iteration. So this list of deliverables is more a draft of what I think might fit the duration of the GSoC, and will evolve as the work progresses. It might be possible to deliver less or more than expected, depending on how easily the pieces fall together.

* Plugin infrastructure for Shapado
** autodetect newly-installed plugin (package extracted into plugins folder)
** admin interface to list/configure plugins
** entry points in views for content (like WordPress widgets)
** plugin can replace existing views/partials
** access to models/db
** plugin can have its own migrations
** plugin can create/change routes
* Plugins
** Machine-tag plugin
*** REST API for CRUD operations on tags and tagged items
*** user-facing interface
** A couple other simple plugins that illustrate well the use of different parts of the API
* Documentation explaining how to write plugins

An effort will be made to keep things as general and decoupled as possible to make it easier for other Rails applications to have their own plugin system (or maybe even build something that can be used as a drop-in plugin system).

== Availability ==

I live in the Southern Hemisphere, so I don’t have my big summer break now, it’s only a 1-month winter break in July. As far as my ability to work goes, this has only one drawback: until the end of June, I won’t be able to work much (10-15h/week). After that I can work full-time, both July (no classes) and August (next semester is my last so I’ll have only one or two courses to take), and even after that. I have managed to complete two GSoCs before with the same type of constraint, so that won’t be a problem for me.

== Timeline ==

My general idea of how to go about implementing the plugin infrastructure is to start writing a real plugin (machine-tags) and, in the process, identify what APIs and scripts are needed and write it. Then pick another simple plugin, start writing it, see what is missing, rinse and repeat. Of course that, in the process, we might see features that plugins would reasonably expect to have, so not everything has to be driven directly by the demands of a real plugin.

First iteration (weeks 1 and 2)

* Research
** See how WordPress and Mephisto implements plugins
*** What are the hooks and entry points made available
*** What capabilities plugins can have
*** How (if) they limit what a plugin can do
*** Read up on Rails Engines, Rails 3 mountable apps, Rails Cells plugin

** Flickr machine-tags
*** What APIs exist
*** How 3rd-party applications use them
*** How they are handled on the user interface

* Brainstorm stories
** What capabilities we want our plugins to have (what they’re allowed to do)
*** Use cases for the capabilities (not implement something just “because we can”: there has to be a reasonable expectation of use)
** What they’re _not_ allowed to do
** What the machine-tags plugin should do
** What other simple and illustrative plugins could be written

Second iteration (weeks 3 and 4)

* Start building machine-tags as a normal Rails plugin
* Identify and start implementing missing hooks and scripts needed to turn machine-tags into a real (user-level) plugin

Third iteration (weeks 5 and 6)

* Finish rudimentary plugin infrastructure (enough for a site admin to install the machine-tags plugin without being a programmer)
* Publish blog post/documentation explaining what’s been done so far, what is available to plugin developers as of now and asking the community for feedback on the types of plugins people would like to write and what hooks/APIs they would like to see

– Mid-term evaluations –

Fourth iteration (weeks 7 and 8)
* Refine plugin infrastructure based on community feedback

Fifth iteration (weeks 9 and 10)
* Legroom for unpredictability
* Polish off documentation for plugin developers
* If time allows, work on integrating Shapado with EOL, allowing posting/listing species-specific questions directly on the EOL website through the machine-tags API

  • Share/Bookmark

O Processo Legislativo Animado: Chamada Para Designers

Um problema que vamos enfrentar com certeza no Meu Parlamento é o quão complicado é o Processo Legislativo. Existe um número enorme de trajetos diferentes que uma proposição pode percorrer, e não é nada trivial saber o que cada etapa significa. A Câmara dá uma explicada e tem bastante coisa para ler no Interlegis, mas nada que se possa chamar exatamente de intuitivo. Também não é nada fácil olhar a tramitação de uma proposição em particular e entender onde ela está, por onde ainda falta passar, etc.

Eu pensei em um jeito de resolver estes dois problemas.

A idéia

A idéia é fazer um diagrama de estados completo e interativo, mostrando os estados e transições pelos quais uma proposição pode passar.

Aprendendo o Processo

Nas transições, as arestas tem a espessura proporcional ao número de proposições que já fizeram essa transição (a la Charles Joseph Minard). Os dados viriam do Legisdados.

Passar o mouse por cima da aresta a destaca e mostra um balão com sua descrição.

Passar o mouse por cima de um estado o destaca e mostra sua descrição.

Clicando o botão Play (tem um botão Play), começamos com uma nova proposição no estado inicial. Um texto explicativo é exibido embaixo, como se fosse uma visita guiada, falando o que aquele estado significa e explicando o que pode acontecer com a proposição a partir dali (isto é, descrevendo as arestas). Neste ponto, o usuário escolhe e clica em uma das arestas, passando para o próximo estado.

Repetindo estes passos, o usuário tem uma simulação completa da tramitação de uma proposição, explicada do começo ao fim. A espessura das arestas indica o caminho mais frequente e pode ser usado como dica para o usuário explorar primeiro os casos mais comuns.

Podemos pegar algumas proposições reais que sejam particularmante representativas ou históricas e ilustrar da mesma forma, com texto específico para ela, o caminho que seguiu. [Em vez de deixar o usuário clicar nas arestas, fazemos apenas um playback, exibindo um botão de "avançar".] Dessa forma sedimentamos o aprendizado com um exemplo real.

Acompanhando proposições

Para acompanhar a tramitação de uma proposição específica, mostramos o diagrama de estados um pouco apagado, destacando a trajetória já percorrida pela proposição. Nos balões de informação das arestas e estados, podemos colocar informações específicas daquela proposição. Por exemplo, na aresta poderíamos ter: “enviado para a Comissão de Constituição de Justiça em 05/03/2009″; e no estado: “na Comissão de Constituição e Justiça – relator Deputado João da Silva”.

O balão de informação do estado “votação” poderia mostrar um gráfico bonitão do resultado, como os do Congresso Aberto.

E podemos disponibilizar a mesma função de playback que descrevi acima: começamos na apresentação do texto, e cada click no botão de “avançar” vai para o estado seguinte, mostrando informação sobre a aresta tomada e o estado atingido.

Podemos também dar um leve destaque para os caminhos que a proposição ainda pode vir a percorrer.

A chamada

Eu sou um zero à esquerda para coisas gráficas. Eu posso programar a lógica do negócio, integrar aos dados, etc., mas não consigo nem fazer um mockup para ilustrar a minha idéia.

Então se você é um designer gráfico (especialmente se entende de animações em browser, com flash ou javascript) e quer dar uma mãozinha à democracia, entre no grupo de discussão do Meu Parlamento e diga alô :)

Talvez já haja coisas mais ou menos prontas que a gente possa reaproveitar. Eu encontrei este software que aparentemente transforma fluxogramas em animações flash, mas é proprietário, e não deve ser muito extensível. O ideal seria uma biblioteca, framework, alguma coisa assim que desse pra gente programar e adaptar.

Sugestões e críticas sobre a conceituação do negócio também são bem-vindas, tanto nos comentários quanto no grupo.

E se você resolver implementar a idéia por conta própria, pelo amor de deus libere o programa sob uma licença livre e mande o link :)

  • Share/Bookmark

Wish: RSS Tab Creator

I wish there were a Firefox extension that did this:

  1. you enter a list of RSS feeds;
  2. it keeps track of which items you haven’t read yet;
  3. you click a button or menu item and BAM!, it opens one tab for each unread item, showing the original page, not the RSS text content.
  • Share/Bookmark

The Holy Grail of Kickass API Documentation

Disclaimer: this is a bunch of vaporware.

Read/Write Asymmetry

It’s been a while since people solved the problem of making API documentation easily readable, while keeping it closely tied to the code: keep it in comments in the source code and export it to HTML.

One problem that still remains is that developers suck at writing documentation. They have no need for it (it’s just a waste of time: they already know how that stuff works), and they often don’t use the API they develop themselves, or at least not in all possible use cases, so they end up not knowing very well which information is most valuable to the users.

Users, on the other hand, know it all too well. They know a hack around that quirky behavior; they inadvertently found that undocumented feature (or was it a bug?); they have collectively field-tested it in a hundred times as many use cases as the author had originally foreseen; and they know what needs to be known.

They write about it too! You can see countless blog posts, forum answers, even comments appended to the documentation itself taking up where it left off. It just happens that this stuff never makes its way back into the official docs because it’s too much of a hassle!

If you’re just a user of some library, you usually have it installed in some far-away system directory, outside of source control, and read-only. Making a change to the documentation means finding where the repository is hosted, checking it out locally, finding where in the code that bloody method is implemented, making a change and sending a patch (where to, again?). That’s not your job right?

So why don’t we just make it all a wiki huh? Easy as pie. No funky markup in comment blocks, no generation step, it’s all HTML. You’re reading it, you spot something wrong or incomplete, edit it right there and you’re back to reading before you can say “back to reading.” And where is the code now? Well, somewhere completely dissociated from the documentation. You’re not even sure which version you’re reading about.

So what we really want is API documentation that:

  • comes directly from the source code;
  • is easily editable as a wiki;
  • and goes back to the source code.

There and Back Again

Rdoc.info takes any arbitrary repository and generates API documentation for you. So far it only works for Ruby repositories on Github, but it’s the only one I know so it’s the one I’ll talk about. The idea is applicable to anything that does the same type of auto-generation though.

That’s really cool then! Our first requirement is covered.

The second requirement is making a wiki, so I think we can borrow from about five million solutions.

Now HOW?! How do you turn that stuff back into source code again?!

chmod +w RDoc

Documentation on rdoc.info is generated per repository, per user, so you can decide, for each repository, if its documentation should be wiki-editable or not (if you made it this far I assume you really want it really bad). In that case, all you have to do is create a public branch called “docs”, and rdoc.info starts tracking that instead of the master branch, generating a wiki from it. Now you just tell everyone to come and edit!

Gathering edits

Rdoc.info forks your repository and commits every wiki edit to that fork. It’s quite simple: it just replaces the comment block next to a method/class/whatever with the edited version. On every commit, you receive a pull request.

Displaying

On the website, rdoc.info shows the latest wiki-edited docs by default, with a read-only “canonical” tab showing the last official version that was pushed before the recent edits.

Merging back

When you receive the pull request from rdoc.info, you merge rdoc.info’s branch back into yours, resolving possible conflicts and integrating the changes.

Edit History

What if you push to your “docs” branch when there are wiki commits that you haven’t integrated? Rdocs.info can’t try a normal merge, as there might be conflicts, and the whole thing has to be automatic. If it just does a “reset hard”, it’ll lose previous edits. So it does a merge, but with a no-hostages approach: automatically resolve every conflict by choosing your changes. It will count as a normal edit in the wiki, with the previous version still in the history.

Reverting to a particular version from the wiki interface is the same thing: the contents (only the doc comments, not the code) of the chosen version are commited on top of the current commit, and can be diffed with it.

Attribution, Statistics, Reputation

If the user making the edit is logged in, the commit can have her as the author, and statistics can be kept on who helped out the most and that kind of stuff. Methods with the least content can be marked as “stubs”, and editing those can be worth more points.

More into metadata territory, the developer could also possibly benefit from indirect usage statistics (through clicks and searches), and people up/downvoting individual methods, maybe even commenting on their design (whether they should be split in two; if the parameters or return values make sense, etc.).

You want it too?

From the few services I know which host API docs, I think the most likely to implement something like this are either rdoc.info or ApiDock. So write them and ask for it! (hey, I told you it was vaporware.)

Update: Apparently, something like this has been tried already by DocBox as a Google Summer of Code project. The code on Github is from last year and the website pointed at by RubyFlow seems to be down. Anyone with more info on this?

  • Share/Bookmark

Democracia Líquida no Brasil: Uma Realidade Possível (a curto prazo!)

English version here

O que é?

Democracia Líquida é um método de tomada de decisão em grupo que funciona mais ou menos como uma “democracia direta para pessoas que sabem que não são especialistas em um assunto, mas conhecem pessoas em que elas confiam e que sabem mais sobre esse assunto do que elas”.

É muito mais democrático do que a Democracia Representativa (a que temos hoje no Brasil, com deputados, senadores, vereadores), e muito mais factível do que a Democracia Direta, onde todo mundo vota em tudo. Como na democracia direta, a pergunta pode ser respondida por todo mundo mas, no caso da Democracia Líquida, a resposta pode ser “eu voto o que o fulano votar”. Cada pessoa pode escolher “assessores” para determinados assuntos, como os deputados fazem hoje.

Por exemplo, você não sabe nada sobre a matriz energética do Brasil e suas necessidades, mas tem um amigo engenheiro elétrico que sabe muito disso e que tem opiniões parecidas com as suas, então ele vira seu “assessor” em matérias de Energia: a não ser que você vote diretamente, o voto dele passa a valer um a mais. Ele, em determinadas questões, pode não estar completamente seguro sobre o assunto específico: ele é engenheiro elétrico, estão votando exploração do petróleo. Mas ele conhece um geólogo que entende e tem os mesmos valores que ele, então delega seu voto. O voto do geólogo passa a valer dois a mais (o seu e o do engenheiro elétrico).

Nos assuntos que te interessam mais e sobre os quais você entende melhor, você vota diretamente.

Se você simplesmente não se interessa por nada e não quer gastar seu tempo com isso, é só delegar tudo. Fica igual a nós todos hoje, com alguém votando tudo por nós sem nossa intervenção, com a exceção que, neste caso, quem vai votar por você serão pessoas que você conhece e com quem pode conversar pessoalmente se precisar, e você não precisa esperar 4 anos se quiser trocá-las.

Importante:

Não existe mandato. Se estiver insatisfeito, você pode trocar de assessor a qualquer momento.

Importantíssimo:

Você sempre pode votar diretamente. Não importa se você delegou seu voto para um determinado assunto. Se você for e votar diretamente, a delegação não conta naquela votação: seu voto vale 1 (mais o número de pessoas que delegaram pra você) e o do seu assessor passa a valer esta quantidade a menos. Como você pode ver o que o seu assessor vai votar antes que ele vote de fato, se você discordar é só ir lá e votar você mesmo.

Como faz?

Dissolvemos câmara dos deputados, senado, assembléias legislativas estaduais e câmaras de vereadores, criamos um site de elaboração e votação de leis e instituimos que este será o único meio pelo qual estas duas coisas serão feitas, certo?

Calma. Ninguém vai pegar em armas, ninguém vai dissolver nada. Como eu disse, esta é uma revolução factível, não um sonho distante e utópico.

Uma maneira que alguns suecos inventaram de fazer isso foi criar um partido (o Demoex) e eleger um “vereador-laranja” que vota na câmara o que for tirado pelos membros do partido através de um sistema online de democracia líquida. Tudo bem, eles começaram só com uma cadeira, mas já conseguiram resultados bem legais. A idéia é muito boa e parece que já foi tentada no Brasil (não consegui achar muita informação). Mas eu tenho uma idéia diferente que não envolve eleger ninguém.

Meu Parlamento

Criamos o tal site com o sistema de democracia líquida, pegamos as pautas da Câmara Federal antes de cada plenário e jogamos lá. Discutimos, delegamos, votamos. Somos nosso próprio parlamento paralelo, cada um de nós um deputado. Simples assim.

Que diferença faz?, você pergunta. Só eu e você? Não muita. Agora imagine 10% da população brasileira (ou mesmo só de São Paulo) usando isso. Os deputados começariam a dar atenção. Começaríamos a ter influência. Eu consigo imaginar um deputado, na véspera de uma sessão do plenário, consultando o site pra ver o que eu e você votamos. Agora imagine 30%. Depois 50%. Só um louco nos ignoraria. Sem que tenhamos eleito nenhum “laranja” nós mesmos, todos os deputados, aos poucos, entrariam na discussão e passariam a ser voluntariamente nossos laranjas. Afinal de contas quem, depois de ver uma parcela gigante do eleitorado votar de um jeito no site, votaria de maneira contrária no plenário?

Ah, claro: depois que eles votarem, comparamos as escolhas deles com as nossas. “73% dos cinco milhões de usuários do Meu Parlamento votaram contra a lei do Azeredo; 340 dos 513 deputados da Câmara votaram a favor. Estes são os deputados que votaram a favor: Fulano, Ciclano, Beltrano”.

E, depois que você tiver um certo número de votações registradas no site, podemos fazer comparações personalizadas. Você vai ao perfil do Fulano (deputado federal, talvez o que você elegeu na última eleição) e lá está: em 70% das votações, Fulano votou diferente de você. Hm… será que você vai votar nele na próxima eleição? Talvez você queira consultar a lista de todos os deputados, ordenada por quão parecido com você eles votaram. Escolher um representante por quanto ele te representou e não pela campanha, quem diria hein?

Mas está faltando alguma coisa pra isso ser um parlamento de verdade. Até agora, nós estamos apenas votando nos projetos de lei elaborados pelos deputados. Por que não criarmos nossos próprios?

Se a proposta do Túlio Vianna virar lei, poderemos elaborar colaborativamente projetos de lei no próprio site (wiki?), debatê-los e encaminhá-los à Câmara para votação. Precisaríamos de mais ou menos 1 milhão de apoiadores. Veja que não é tanta gente quanto parece. O Orkut tem mais de 30 milhões de usuários no Brasil (você poderia inclusive pedir pros seus amigos no Orkut assinarem). Como qualquer outro projeto em votação na Câmara, ele passaria antes por nós, e já iria para o plenário com o peso dos nossos votos.

E mesmo se a proposta do Túlio Vianna não passar, tudo o que precisamos é de mais ou menos um milhão de assinaturas reais, em papel. A elaboração e a discussão ainda podem ser feitas no site. Depois disso, cada pessoa interessada imprime o texto do abaixo-assinado, assina embaixo e manda pelo correio para a ONG que vai gerenciar o Meu Parlamento. A ONG recolhe as assinaturas e encaminha o projeto de lei à Câmara. Pronto.

Cortando o atravessador

Podemos elaborar leis nós mesmos e mandá-las para a Câmara. Podemos influenciar a Câmara para que vote o que nós votarmos. Somos um Parlamento completo.

Quando tivermos este tipo de controle, iremos nos perguntar: pra que temos mesmo uma Câmara? Pra que gastamos esta quantidade monstruosa de dinheiro pagando deputados, assessores, secretários, faxineiros, motoristas, etc.? É, realmente não faz muito sentido. Vamos manter o Meu Parlamento e cortar o resto.

Por que vai funcionar?

Como eu disse, isto não é uma utopia. Ok, a parte de cortar o atravessador talvez seja. Mas votar leis como qualquer deputado — e ter o nosso voto ouvido — e criar nossas próprias leis são coisas que dependem de muito pouco: software (livre, claro) e usuários.

Haverá, claro, a necessidade de um empenho grande de algumas pessoas para que o site seja criado: programadores, designers, gente disposta a testar e dar feedback.

Também será grande o esforço para que o site tenha uma adoção significativa. Precisaremos de comunicadores para divulgar a idéia e atrair novos usuários. Precisaremos de jornalistas, comentadores políticos e cidadãos engajados para alimentar a discussão no site e dar-lhe vida.

Talvez dê muito trabalho participar e fique difícil convencer novas pessoas a se cadastrarem, certo?

Errado. Como em todo site de conteúdo gerado por usuários, quem desenvolve e divulga o site e quem gera a maior parte do conteúdo é uma fração minúscula do número total de usuários (pense no YouTube). A maioria interage muito pouco, contribui quase nada e ainda consegue tirar proveito. E, mesmo assim, constroem-se comunidades vibrantes e ricas.

O cidadão mais desinteressado e preguiçoso precisará fazer muito pouco, então não será tão difícil convencê-lo a se envolver. “É só criar um login e escolher uns amigos pra votarem por você”. Ele receberá um email de vez em quando falando “olha, tem essas coisas sendo votadas, você se interessa?” e o deletará. E depois outro dizendo “tal amigo seu votou a favor disso por você, outro amigo votou contra aquilo” e também o deletará. Mas ele estará, pelo menos de uma maneira passiva e vaga, informado sobre o que anda acontecendo, o que já é mais do que temos hoje. Nestes emails, alguma coisa talvez lhe salte os olhos. O amigo que vota por ele pode ligar e conversar sobre o que está sendo discutido (coisa que deputado algum jamais faria). Mesmo com o mínimo de esforço ainda há mais democracia.

Como chegar lá?

Não precisamos fazer tudo de uma vez. O site pode começar muito simples e ir agregando funcionalidades aos poucos.

O primeiro passo é criar um simples sistema de acompanhamento de deputados, algo parecido com o Twitter. Você vai até o “perfil” de um deputado e escolhe “seguir” seus votos (e *apenas* os votos), seja por email, RSS ou qualquer outro jeito. Toda vez que ele vota alguma coisa você recebe uma notificação: “Fulano votou X na votação sobre Y”. Colocamos no site o texto do que foi votado para debate, algo parecido com isso.O desenvolvimento desta parte já está em andamento.

Em seguida, adicionamos um sistema simples de votação direta pós-fato (inicialmente, é mais fácil lidar com votações que já ocorreram do que com a pauta antes das sessões). Você recebe “Fulano votou X na votação Y, o que você teria votado?“. Clica no link, vai até o site e vota. Com isso já dá pra fazer as comparações citadas acima do seu histórico de votações com o dos políticos.

O bom de fazer as coisas nessa ordem é que o site vai ficando incrementalmente mais útil. Ele não precisa de uma massa gigante de usuários logo no começo pra fazer algum sentido. Mesmo se você for o único usuário, já se beneficia de informação sobre os políticos, suas atividades e o quanto eles te representam.

Depois disso, aos poucos, vamos introduzindo outras funcionalidades: votação sobre a pauta antes da sessão no plenário, sistema de escolha de assessores e delegação de votos, sistema de elaboração colaborativa de projetos de lei, etc.

Começamos primeiro com a Câmara Federal porque é o órgão legislativo que mais disponibiliza eletronicamente informações sobre sessões, votos e deputados. Na maioria das assembléias estaduais e câmaras de vereadores, esta informação está em atas de papel, e só consegue ver quem tem a paciência de ir até lá. À medida que estas começarem a ser disponibilizadas online também, passarão a ser incluídas no site.

Como eu ajudo?

Como dá pra ver, tem muita coisa a ser feita. Precisamos de desenvolvedores, designers, comunicadores, lobistas (pra convencer as assembléias e câmaras municipais a disponibilizarem seus dados na internet), testadores, críticos, captadores de recursos, advogados, enfim, não importa o que você faça, tem como você ajudar.

Eu criei um grupo de discussão para começar a agregar os interessados. Cadastre-se em: http://groups.google.com/group/meuparlamento.

Referências

Conteúdo:

http://campaigns.wikia.com/wiki/Liquid_Democracy (en)
http://en.wikipedia.org/wiki/Proxy_voting#Delegated_voting (en)
http://en.wikipedia.org/wiki/Delegative_Democracy (en)
http://www.brynosaurus.com/deleg/deleg.pdf (en)
http://p2pfoundation.net/Decision-Making_Tools (en)
http://pt.wikipedia.org/wiki/Demoex_-_democracia_experimental (pt)
http://www.opencongress.org/ (en)
http://legistalker.org/ (en)
http://www.democracia.com.br/ (pt)

Discussão (veja também os comentários):

http://tuliovianna.wordpress.com/2009/07/19/democracia-digital-direta-ja/ (pt)
http://www.trezentos.blog.br/?p=2193 (pt)

Perguntas?

Não deu pra cobrir tudo acima, senão o texto ficaria longo demais. Mas, por favor, usem os comentários. Existem várias questões que ainda precisam ser debatidas (segurança, anonimidade, exclusão digital, etc.) e eu ficarei feliz em responder às perguntas.

Update: parece que já tem algo do gênero sendo desenvolvido em http://www.democracia.com.br/. Tem acompanhamento e votação direta, mas não consegui me cadastrar nem acessar o blog. Ainda está ativo?

Update 2009-11-25: troquei “Parlamento Aberto” por “Meu Parlamento”, o novo nome.

  • Share/Bookmark

Brincando com políticos e inteligência artificial

A idéia desta análise veio do André Lima (@andlima) e será executada por mim como um projeto de pesquisa orientado pelo Prof. Siome K. Goldenstein.

Resumo

A quantidade de informação disponível eletronicamente sobre a atuação dos nossos representantes eleitos tem aumentado drasticamente em tempos recentes e, apesar de ainda longe do ideal, já permite análises interessantes.

“Informação”, aqui, refere-se não a notícias ou opiniões, mas a dados crus e objetivos como: contribuições de campanha, fluxos orçamentários, movimentações partidárias, processos na justiça, históricos de votação em plenário, etc. Para os fins deste artigo, vamos nos focar no último.

A idéia básica é, olhando apenas os históricos de votação dos deputados:

  • fazer um agrupamento automático por similaridade;
  • comparar este agrupamento automático com o real (por partidos);
  • estabelecer as votações ou projetos de lei mais relevantes.

Modelagem

No site da Câmara dos Deputados há muita informação sobre o processo legislativo. Em particular, o site lista:

  • Deputados;
  • Votações (projetos de lei, entre outros);
  • Votos (sim/não/abstenção/ausência).

Com estas informações, podemos modelar um deputado como sendo um vetor de votos, onde cada dimensão corresponde a uma votação, e o valor da dimensão, ao voto. Ex.:

Deputado1: <sim,não,não,sim,aus,abs>
Deputado2: <não,não,não,sim,sim,aus>

Sabemos a que votação cada voto corresponde pela posição no vetor.

Tendo isso em mãos, podemos criar uma medida de distância entre dois deputados, dada pelo número de votações em que os dois votaram diferente. Intuitivamente, quanto mais eles discordarem, mais “distantes” estarão ideologicamente. No exemplo acima, Deputado 1 e Deputado2 discordam na primeira, na penúltima e na última votação. Portanto, tem distância 3.

Agrupamento

Vetores e uma medida de distância são a entrada de vários algoritmos de agrupamento (clustering, em inglês), subárea da Inteligência Artificial conhecida como Aprendizado de Máquina (Machine Learning, em inglês). As saídas em que estamos interessados são o número de grupos encontrado e a distribuição dos deputados em grupos.

Uma maneira intuitiva de imaginar, grosso modo, como o número de grupos é obtido é a seguinte: se todos os políticos tiverem votado exatamente a mesma coisa em todas as votações, precisamos apenas de 1 grupo (eles concordam em tudo). Se eles tiverem votado exatamente a mesma coisa em todas as votações exceto em uma, onde metade votou “sim” e a outra “não”, precisamos de 2 grupos, e assim por diante.

O número de grupos é um resultado interessante em si porque, de certa forma, pode ser interpretado como a quantidade de “variação ideológica” entre os deputados. Uma crítica frequente ao sistema político brasileiro é o fato de haver dezenas de partidos sem muita definição da diferença entre eles (ao contrário do sistema estadunidense, polarizado em dois partidos principais). O número de grupos encontrado pelo algoritmo refletiria o número de pólos ideológicos reais, definidos puramente pelas opiniões dos deputados expressas em seus votos.

A composição dos grupos é também interessante, pois podemos ver não só que políticos foram parar em que grupos mas, melhor ainda, que partidos foram parar em que grupos. Talvez haja pouca surpresa aqui, mas seria curioso se pessoas de partidos supostamente opostos ideologicamente acabassem no mesmo grupo, ou se um pedaço de um partido estivesse em um grupo e outro pedaço em outro, revelando uma divisão partidária.

Relevância dos projetos de lei

Fazendo algo semelhante a uma Análise de Componentes Principais (PCA – Principal Component Analysis, em inglês), podemos obter um conjunto pequeno das votações que foram mais relevantes em distinguir um político do outro. Retomando o exemplo acima, se todos tivessem votado exatamente a mesma coisa exceto em uma votação, onde metade votou “sim” e metade “não”, concluiríamos que esta uma votação é muito mais relevante do que as outras porque, para qualquer político, bastaria saber o que ele votou nesta uma votação para determinarmos a que grupo ele pertence. O resultado real claramente não será tão óbvio, mas através deste procedimento poderíamos obter, por exemplo, as 10 votações ou projetos de lei mais relevantes.

Aplicações

A aplicação mais imediata seria, a partir da análise de relevância, criar um questionário online com as leis mais importantes, determinando a que grupo o usuário pertence e que deputados de seu estado se encontram nele (e quais não se encontram). Outras aplicações, diretas ou indiretas, das idéias básicas apresentadas aqui são muitas e muito importantes, e as apresentarei melhor em outro post.

  • Share/Bookmark

Code Review + Google Wave = Code Wave !

Doing some exploratory thinking about the possibilities opened by Google Wave, I came up with this very early idea of something that could turn out to be pretty interesting. In explaining it, I’ll assume you’ve watched that huge 1h20min video they have about it (it’s worth every minute, but there’s an abridged — 10min — version).

Motivation

People have been doing code review through email for ages. It’s the easiest, dead-simple way of doing it. Just add a post-receive-hook to your repository and make it email a diff of every new commit to a mailing list. People answer to that email, inlining comments where needed. Great, you say. But… It’s not 2.0. Bummer.

You know what is 2.0? Review Board. Very pretty web interface, AJAX, all that goodness (seriously, it’s awesome, I’m even working on it myself). But… It’s not Email.

You know what is Email and 2.0? You’re absolutely right! Google Wave*! :)

So how do we tie it to the code?

Code Wave

The idea so far includes developing four separate pieces of software — one wave robot, two gadgets and one stand-alone web application which will use the embed API — , but the basic idea is to map every commit and every file to its own wave. Think of it as a code browser on steroids.

The Robot

The robot handles creating, linking and updating the repository content, access control and custom markup.

It creates one “absolute” wave for each version of each file and directory, plus one “relative” (HEAD) wave for each, which gets updated with every new commit. This way, one can look at a particular version of a file using the absolute wave, but also use the Playback functionality on the relative wave to watch it evolve as new changes are committed. Since waves can be linked to one another, besides being able to make directory listings, we can also have a header on each wave, linking to the usual previous/next/head commits. This is the “code browser” part.

When new commits arrive, they each also get their own wave, with the commit message, diff content and a link to each file changed. As with any wave, people can comment inline on any part they want, even chat about it, effectively doing (possibly live!) code review. The conversation history will be kept (and “playbackable”) in the wave, and people who are participants will be notified of the changes and can also come and chip in.

The robot also handles access control. Apparently waves, at least so far, don’t allow one to say “nobody can edit the content, only add comments.” If I’m right about that, the robot will need to watch and overwrite any changes to the content itself (the content must always reflect the repository), leaving only comments. On the web interface (which we’ll talk about in a sec), people can decide to “watch” certain (or all) files or directories, being notified about changes in them (much like in Review Board). The robot accomplishes this by adding these people to the commit waves where these files/directories are changed, so the wave pops up in their inboxes. The original committer always gets added, so she gets notified about any comments on her changes.

Another cool thing to have is special markup, so the robot watches for stuff like revision numbers/sha1s and turns them into links to the appropriate wave. It can also be configured through the web interface to turn ticket numbers and the like into links.

The Web Interface

It serves two main purposes: store settings and provide a way to browse the repository and comments.

Settings to be stored are repository path, privacy levels, groups of users, change watchers, robot behavior, etc.

Since waves can be embedded into normal web pages, this is also a nice way to make all that content (files, diffs and reviews) available online without needing a wave client. We could even think about indexing everything and making it searchable.

Gadget Number One

Syntax highlighting, plain and simple. Highlight code, skip (wave) comments, allow raw copying, etc. Could also be used to fold and unfold comment threads, so you could have a look at the diffs without the cruft. Maybe we could borrow some things from Bespin?

Gadget Number Two

Link helper. Like the Google button, that lets you search for something and drag results into the wave, this helper would allow you to refer to other files in the repository, searching them by name/path and dragging them in. Not sure how useful this really is, just thought it was a nifty idea.

The Future

Emacs Client

Imagine this: you’re there, nurturing your code on emacs (you are using emacs right?), and you spot something funky. It shouldn’t be there, or there’s a better way to do it, or you have a question about it. You put your cursor over the funky line, hit Control+Meta+Shift+whatever and what happens? Your trusty emacs takes the “git blame” for that line (or the equivalent in your SCM of choice), asks the web app for the wave URL associated with the commit sha1, splits your window in half and shows you said wave (do you have any doubt there will be an emacs wave client?) with the cursor right on the corresponding line in the diff, ready for you to hit M-x add-wave-reply and send your comments the committer’s way. It also might just be that someone already had the same issue, and you’ll see a threaded conversation there with the answer.

Editing

Right now we’ve only mentioned writing on commit waves (code review), but file waves were read-only. I haven’t thought out the details for this yet, but maybe there can be something like embedding Bespin on Google Wave, or the other way around, so that people can do real-time collaborative code editing (while also chatting through inline comments) and then mutually decide to commit. The file wave could wrap the file’s content in a header with a commit command.

The Present

So, how far are we into this project? Well, nowhere, really. It’s just a recent idea I had, and I don’t even have a Google Wave Sandbox account yet (hint, hint if you’re a googler). So if you liked it, feel free to go ahead and implement it. Many of the parts I described can be done independently (like the emacs wave client), so you don’t have to take on everything at once. And if you ever get around to building this (under a free license, of course) and making tons of money, please send me a couple beers :)

Also, this is a very rough draft, so suggestions or any kind of feedback is appreciated.

* For a non-ludicrous version of this comparison, take a look at: http://smartbear.com/white-paper.php?content=docs/articles%2FFour-Kinds-Of-Review.html

  • Share/Bookmark