Vim for the win :)

May 16, 2010 4 comments

I have been using Vim a lot in the last few weeks, to edit CSS and HTML files. It might seem a bit awkward at first but once you get used to it, it becomes great!
What helps a lot too is to configure Vim properly to make it perfect for use.
Vim and Vi configurations are done by setting variables using :set or by editing the file .vimrc in your home folder.
I will share here my Vim configurations and some of the commands I use more often. It also works as a Vim cheat sheet for my own future reference.

So, my ~/.vimirc looks like this:

set tabstop=2 expandtab autoindent smartindent shiftwidth=2 number

Here’s what each of them does

Configuration Effect
tabstop=N Sets the tab size to N spaces. The default is 4.
expandtab Tabs are expanded, when you press tab, N characters will be inserted instead of a tab character (where N is the amount of spaces set for tabstop).
autoindent Will keep the same indentation when you press enter in the end of a line.
smartindent Vim will try to automatically detect indentations. For instance, if you go to a new line and enter a ‘}’, Vim will go back one indentation level.
shiftwidth=N The number of spaces used for one indentation level.
number Shows lines numbers.

And here are some of the commands I use more often:

Command What it does..
:N goes to line N
/foo searches for ‘foo’
:%s/foo/bar/g replaces all occurrences of ‘foo’ with ‘bar’ in the current file
:s/foo/bar/g Same as above, but replaces only on the current line
:s/foo/bar/gc Same as above, but prompts for confirmation before replacing each occurrence of ‘foo’. Can also be used with ‘%’ to replace all occurrences in the file
Shif + G goes to the end of the file
v enter select mode
<< moves the current line one indentation level backwards;
>> moves the current line one indentation level forward;
yy copies current line to the buffer
dd removes the current line out and place it on the buffer
p pastes the text from the buffer on the next line

Also remember that many of these commands may be used with a different number of lines.
For instance, pressing 1, 0, d, d will delete he next 10 lines.

Any other cool commands for Vim? Let me know on the comments!

Categories: English, Linux, Programming

Grails: Separating the database access from the domain classes

May 8, 2010 5 comments

Some days ago I started working on my second project involving Groovy & Grails.
Grails is my first contact with server side development with dynamic languages, and, despite some small problems (mostly due to the fact that the framework is still not so mature compared to others out there), I really, really enjoy it.

One of the things that I like is how using Groovy’s dynamic features the framework injects database access technicalities into our domain classes.
The domain is therefore smart enough to retrieve/update its relationships and even to find/update itself, all without the need to pass around repositories dependencies whatsoever, or to force the domain classes to extend any other classes.

But sometimes we need to write HQL (or criterias) ourselves, and then in our first project we ended up having some domain classes quite bloated with custom queries and a lot of other database related operations mixed with pure domain-specific logic operations.

Something like this:

  class Book {
    // properties, mappings, constraints
    // domain methods

    def findAllBooksFromTheSameAuthor() {
      return findAll("some HQL")

    def findSimilarPurchasedBooks() {
      return findAll("some HQL")

This code is just a silly example to illustrate the problem.
Of course we could have used Grails’ dynamic finders for those queries too, but we would be externalizing the internals of our domain class so we like this approach of adding custom query methods better.
One thing we didn’t like though, is that we had many methods like the ones above, mixed with the domain logic and properties.
So we decided to move these methods somewhere else and inject them into our domain classes, like Grails does with its dynamic generic finders.

A very nice way to do it seemed to be using Groovy’s Delegate annotation, having something similar to:

  class Book {
    @Delegate BookQueries bookQueries = new BookQueries(this)

    // properties
    // mappings, constraints, domain methods

  class BookQueries {
    Book book

    BookQueries(Book book) { = book

    def findAllBooksFromTheSameAuthor() {
      return Book.findAll("some HQL")

    def findSimilarPurchasedBooks() {
      return Book.findAll("some HQL")

We have to pass the book object to BookQueries because we are gonna need its properties to build our queries.
For instance, we need its author to find all books from the same author.
And using the delegate we can call methods from BookQueries with a Book object:


The only problem with this is that we also had some static methods to first retrieve our objects.
These are queries that are not related to any relationship or similarities between objects, so they are static methods in the Book class:

  static def findBestSellersInMonth() {
    findAll("some HQL")

The problem is that static methods are not delegated.

In our project we decided to scrap the @Delegate for good, move all custom query methods to BookQueries, including the static ones, transform them into closures and inject them manually, one by one, into the Book class during the application BootStrap, using Groovy’s Expando metaclass.

But I didn’t really like this approach.
I think I’d rather keep the @Delegate, and then move the static methods to a BookRepository class:

  class BookRepository {
    def findBestSellersInMonth() {
      return Book.findAll("some HQL")

It might seem as a step backwards.. “why do you need repositories if you have your rich domain that can retrieve itself?”
But the static modifier already tells that these methods don’t belong to our domain *objects*.
They are there to initialize the objects, retrieve them from somewhere (the database).
And, well, isn’t this part of the definition of repositories? =P

Update — May 10th ———————————

Peter Ledbrook suggested using Grails’ named queries (see comments). It looks indeed very nice, but we really wanted to move our queries out of our domain class, to make it more readable and, well, prettier ūüėÄ

With the named queries we could move a static block containing the static queries to the BooksQueries class and assign this static block to a static nameQueries block in the Book class, and this would import the static queries.

Today I was messing with this a bit more and I realized that I could just inject the static methods into my domain class from inside my delegate itself.
It’s so simple I don’t understand how come I didn’t think about that before ūüėÄ
So, if you don’t like the repository approach, you can always have something like:

  class Book {
    @Delegate BookQueries bookQueries = new BookQueries(this)
    // all Book properties, constraints, domain methods, etc

  class BookQueries {

    static {
      BookQueries.metaClass.methods.each {
        if (it.static) {
          Book.metaClass.static."$" = owner.&amp;"$"

    Book book

    BookQueries(Book book) { = book

    def findAllBooksFromTheSameAuthor() {
      return Book.findAll("some HQL")

    static def findBestSellersInMonth() {
      return Book.findAll("some HQL")

Cool CSS tab menu

April 17, 2010 4 comments

As you can see, lately I have been playing quite a bit with CSS.
So I recently made a CSS tab menu that I thought was worth sharing. It looks like this:

CSS Tab Menu

And it is quite simple.
All that is needed is an image with the looks of the tabs, when unselected and when selected/hovered.
I used this:

tabs background image

You can edit the image to get whatever looks you want.
So, now we only need our html and css:

* Please notice that I used a ‘header’ container for the menu and I set some style attributes for position/etc, but you would probably change it to whatever your container needs.

HTML fragment:

<div class="header">
  <ul class="menu">
     <a href=""><span>Option 1</span></a>
   <li class="selected">
     <a href=""><span>Option 2</span></a>
     <a href=""><span>Option 3</span></a>
     <a href=""><span>Option 4</span></a>


.header {
  width: 100%;
  height: 80px;
  background: #003366;
  position: relative;

.menu {
  margin: 0px;
  list-style: none;
  position: absolute;
  bottom: 0px;
  right: 20px;

.menu li {
  float: left;
  margin-left: -12px;

.menu li a {
  float: left;
  height: 24px;
  background: url('img/menu.png') no-repeat;
  position: relative;
  text-decoration: none;
  color: #003366;
  cursor: pointer;

.menu li a span {
  float: left;
  padding: 6px 31px 0 35px;

.selected a,
.menu li a:hover {
  background: url('img/menu.png') 0px -25px no-repeat !important;
  z-index: 10;

.menu li a:hover {
  z-index: 11;
  color: #99cc00;

Notice that the image has to be placed in a folder called img with the name menu.png.

And that’s it! ūüėČ

Categories: English, Programming Tags: , , , , , , ,

How to center a floating HTML div with variable width

April 15, 2010 4 comments

Hi! I know I have been away from the blog for a long time, but I decided to wipe off a little of dust and write some small things that I have been doing here.
Recently I have been working and learning lots of new and cool things, some of them are simple, some are not so trivial, but many of them could be quite useful for a bunch of people out of there, including myself! I mean, I decided to restart writing small tutorials on some simple things that I usually do, like the one I wrote about how to install the new JDK release candidate on Linux.
Ever since I wrote it, many times I had to come back here to recheck one or another detail of some command, when I wanted to install a version of JDK that was not available on the Ubuntu repositories.

So, today I will write down how to center a floating div with variable width…. A what? Portuguese English please!

Nowadays it is very common to see on websites a small notification on the top of the screen, like those:


I first saw these things on Google applications like GMail, but they are very nice anyways, because they avoid the use of (grr!) pop-ups (grr!) when there’s the need to notify the user about something. That’s probably why they are becoming each time more popular.

Anyway, this is basically a div or a span, centered on the screen or whatever other container contains it.
Usually to center something it is enough to use

margin: 0 auto;

But in this case we don’t know how wide the div should be, as it depends on the text it will show, which is dynamically provided by some programming language.
So my notification div class does not have a ‘width’ attribute and is displayed as an inline element:

.notification {
  display: inline;

In this case setting the margin to auto won’t work, so what to do?
I wanted to center my notification div in relation to the screen, so I created two divs:

<div class="container">
  <div class="notification">
   Here goes my notification message

And my CSS:

.container {
  position: absolute;
  top: 0px;
  width: 100%;
  text-align: center;

.notification {
  display: inline;

Basically we insert the notification div inside a container that occupies the whole area in which the div is to be centered, and set text-align: center.

I know it is very simple but it is not always obvious ūüôā

Cowboy Bebop Original Soundtrack

July 11, 2008 5 comments

Era uma vez um desenho japonês em que a história se passava no futuro e contava a história de caçadores de recompensa a bordo de uma nave chamada Bebop.

Cowboy Bebop

Cowboy Bebop

Pra quem não sabe, Bebop é uma subdivisão do Jazz, e essa é só a primeira das referências musicais presente no anime.

Misturando batalhas espaciais com artes marciais e faroeste, o desenho tr√°s uma trilha sonora de dar inveja a qualquer trilogia famosa de Hollywood, com forte influ√™ncia de blues, jazz e rock’n roll.

A composic√£o da trilha sonora foi liderada por Yoko Kanno, uma japonesinha batuta conhecida por suas criac√Ķes musicais para games, animes e filmes. Ela reuniu alguns m√ļsicos e formaram uma banda para a cria√ß√£o da trilha-sonora. Batizaram a banda de The Seatbelt (Os cintos-de-seguran√ßa), pois brincavam que deveriam usar cintos-de-seguran√ßa para permanecerem seguros durante as sess√Ķes de jam.

A banda n√£o tinha um cantor principal, mas contaram com a participa√ß√£o de vocalistas como Steve Conte, Mai Yamane, Gabriela Robin (h√° rumores de que esta seja na verdade um pseud√īnimo da pr√≥prio Yoko Kanno) e outros para as m√ļsicas n√£o-instrumentais.

A banda se reuniu mais uma vez em 2004 para criar a trilha-sonora do segundo game baseado em Cowboy Bebop.

Clique em ‘Leia o resto deste post’ para poder ouvir algumas m√ļsicas da trilha.

Read more…

Mais algumas fotos

June 10, 2008 7 comments

Parque Kadrioru:



O tigre no zoológico e uma placa muito importante:


Pra quem achava que aqui n√£o tinha criancas (aff!):


Andando pelo centro às quatro da manhã:

Super-Macarronada by eu mesmo:

Indo dormir ontem, foto tirada a meia-noite:

Semana que vem vou ter muitas fotos e coisas pra contar. Neste fim-de-semana vamos pra Tartu, a segunda maior cidade do país! Beijos!

Head aega!

Seek and hide

May 27, 2008 12 comments

√Č comum ver em blogs alguma sec√£o em que as pessoas escrevem termos de busca que levaram outras pessoas a seus blogs. Nunca me interessei muito em fazer algo do tipo, provavelmente porque as buscas que traziam pessoas at√© aqui eram sempre baseadas em alguma d√ļvida com Linux ou Java ou algo do tipo.

Daí de uns tempos pra cá eu comecei a escrever sobre coisas diferentes e comecaram a aparecer termos de busca mais inusitados.. então.. vejam algumas coisas que pessoas buscaram em sites como Google e Yahoo! e acabaram vindo parar aqui:

nokia e51 bom negocio
Estou com ele a mais de uma semana e posso garantir que √© um bom neg√≥cio ūüôā

e51 n√£o conecta
Não conecta o que? Onde? Se está na garantia e você for leigo leve na assistência técnica. Caso contrário use o Google mesmo (ou seja, comecou bem :))

‘o que levar na mala’ europa ver√£o
Depende muito dos países pra onde você vai e onde você vai ficar hospedado.
Por exemplo, se for ficar num hotel não precisa se preocupar com toalha, mas se for ficar na casa de alguém ou surfar em algum colchão, é recomendado se preocupar com cada detalhe.
Quanto a roupas, eu recomendo trazer pelo menos uma troca de roupas de frio, alguma jaqueta por exemplo. Mesmo que seja ver√£o, o ver√£o daqui n√£o √© como o ver√£o do Brasil (a n√£o ser que voc√™ esteja indo somente a pa√≠ses do sul da Europa como Espanha, Gr√©cia, It√°lia….).
Claro, traga seus documentos, remédios corriqueiros e algum que você tenha que usar regularmente (recomendo um tubo de Gelol também :)). Quando eu vim pra Europa eu trouxe dentro da minha mala um quilo de limão e quatro garrafas de cachaca. Daí vai de cada um hehe.
O mais importante aqui é saber o que levar na bagagem de mão: nada de líquidos nem objetos pontiagudos e por favor, o passaporte num lugar bem acessível (para você, não para os outros :P).

turismo r√°pido amsterdam
As principais atrac√Ķes tur√≠sticas ficam no centro da cidade ent√£o d√° pra conhecer muita coisa a p√© se voc√™ gostar de andar. Mas o que recomendo mesmo √© alugar uma bicicleta e passear pelo centro da cidade visitando os museus e ver os canais, Red Light District, etc. Se voc√™ falar ingl√™s n√£o se preocupe pois todo mundo fala ingl√™s l√° e h√° postos de informac√Ķes para turistas espalhados pela cidade inteira.
Os b√°sicos s√£o: ao chegar no aeroporto compre um ticket de trem para a estac√£o central. Chegando na estac√£o central, saia e voc√™ vai dar de cara com uma casinha com informac√Ķes para turistas, venda de tickets para passeios de barco, mapas, etc. Da√≠ em diante depende do que voc√™ quiser visitar. N√£o perca o Red Light District e o museu Anne Frank ūüôā

cidade sona vermelha em amisterdam
Zona vermelha em Amsterdam, certo? Sim, é uma zona, e tem putas. Com certeza você não fala inglês porque nem português você sabe então se programe direitinho antes de ir e de preferência leve alguém que saiba se comunicar. Se não der, já vá pelo menos com hotel ou albergue reservado e com um passeio tracado. Não esqueca a camisinha.

passagens para brasileiros amsterdam
KLM ou Air France. Boa viagem.

quantas horas de v√īo de guarulhos a ams
10 horas aproximadamente.

passagens p√°ra tallin
Olha só alguém querendo vir para Tallinn. O jeito mais fácil é comprar uma passagem da KLM ou equivalente fazendo escalas em alguma cidade européia como Paris, Frankfurt, Amsterdam, Berlim, etc.
O jeito mais barato é comprar no Brasil uma passagem Guarulhos -> Berlim e pela internet uma passagem Berlim -> Tallinn em alguma companhia aérea européia de baixo custo, como a Easy Jet.

carros antigos com a letra j
Me pergunto como essa pessoa chegou aqui… Jipe, Jaguar, Jiraiya, Jiban.. ops… n√£o sei mais.

ulcera causa dor nas costas?
SIM! √Č preciso cuidado para n√£o sofrer o que eu sofri. No meu caso eu sentia APENAS dores nas costas, nada no aparelho digestivo. Isso torna o diagn√≥stico bem mais complicado e se voc√™ tomar anti-inflamat√≥rios e rem√©dios para dores vai PIORAR E MUITO sua √ļlcera.
Úlceras do duodeno causam dores nas costas que melhoram após comer.
√ölceras do est√īmago causam dores que pioram ap√≥s comer.
Se você está sentindo esse tipo de dor procure rapidamente seu médico e faca uma gastroscopia.

encontrei um bmw perdido
√Č meu!!!

como comprar maconha
Putz! Se voc√™ est√° no centro de Amsterdam, n√£o importa o ponto inicial, √© s√≥ fechar o olho e dar tr√™s passos para a esquerda que voc√™ estar√° dentro de um “Coffee Shop” (que n√£o vende somente caf√©, se √© que voc√™ me entende).
Se n√£o est√°, tem o jeito legal e o ilegal, o jeito legal requer comprar uma passagem pra Amsterdam antes.

piadas de besteiras legal
O Google funciona mesmo! Você saiu no lugar certo!

Instalar driver nVidia, Beryl ou Compiz no Debian, resoluc√£o de tela no Linux, Instalar Java no Linux, ou buscas similares:
Instalando o Compiz e/ou Beryl no Debian Etch
Resolução de Tela no Linux
Instalando driver nVidia no Debian Etch
Instalando o JDK 6 RC no Linux e Waters no Brasil!