Reverse a string using regexps

I know you have always wondered how would one reverse a string without using loops or any kind of iteration, using, say, regular expressions and recursion. So stop wondering you:

class String
  def r_revert
    sub(/(.+)(.)/){$2 + $1.r_revert}
  end
end
'jablan'.r_revert
#=> 'nalbaj'

or, if you prefer recursive lambdas instead of monkey-patching:

l = ->(s){s.sub(/(.+)(.)/){$2 + l.($1)}}
l.('jablan')
#=> 'nalbaj'

Get first and last line from a file

I needed to get only first and last line from a file (actually, not a file, but rather output from another command). head -1 and tail -1 can be used to get either first or last, but how to combine the two at the same time? Here’s how. Enter tee:

cat somefile | grep something | tee >(head -1) >(tail -1) > /dev/null

Neat, huh?

Random Mac/OSX PITA list

Ok, here’s my entirely private, subjective, random list of Pains In The Ass that I experienced while I was trying to get used to using OSX on a Macbook. While I spent years working in Windows as well, I mostly tend to compare experiences with Linux, allegedly notorious for its desktop (un)friendlyness.

The list is unordered, some things bothering more, some less.

  • No way of changing the UI, only two, marginally different “skins”, that’s it. Let me say I’m not some design-obsessed lunatic that changes his desktop appereance every day or two, but I like to be able to set it once the way I like it (colours, fonts, window decorations, iconsets etc) and use it that way.
  • No localization to my native Serbian language. Again, I’m far from a nationalist in any possible sense, but I like my language and I like the possibility to use it on my computer, as much as I use it when talking to people around me.
  • Again, non-US keyboard layout is not easy to use. Application don’t remember their individual layout, serbian layout is nonstandard so it has to be tweaked using third party tools etc.
  • There is a set of application that you are kind of encouraged to use. Music player - use iTunes. Image viewer - use built one. Text editor - buy TextMate. There are alternatives, but they are far from anywhere close to the mainstream ones. In Linux, there are really plenty of alternative software. Not always 100% bug-free and not always 100% features there, but there’s always hope that either application A, B or C will get the feature you need, or application D will emerge with it. No such thing on Mac.
  • I like to see the name of the song currently being played. In Linux, there’s Panflute applet that hooks to a number of music players. I had no luck finding similar tool for Mac.
  • XWindows apps look and feel crappy (gimp and inkscape for example).
  • Package management is inferior to apt.
  • Every possible 3rd party application, no matter how trivial, is commercial.

Now, some hardware issues

  • Keyboard is designed to look nice, but the keys lack tactile feedback (flat surface) and they are way too fragile (broke two before I adapted, and I hate having to adapt).
  • Sharp front edge where the wrists are resting. Not sharp enough to really cut you, but uncomfortable for sure.
  • No way to make use of integrated graphic card in OS other than OSX.
  • Only two USB ports.
  • Non-standard port for external monitor.

Clojure’s interpose and interleave in Ruby

These days I’m reading a great book titled “Seven Languages in Seven Weeks” by Bruce Tate, currently I’m on Clojure, and I am really surprised how easy it is to follow, knowing Ruby beforehand.

In chapter on lazy evaluation, I noticed couple of methods that didn’t have their exact counterparts in Ruby, and I was curious how hard would it be to implement them. So, there they are.

interpose works similarly to Ruby’s join, just more generic: its result is not String, but lazy sequence of elements from the starting sequence, with object given as argument inserted in between each two.

Here it is, implemented in Ruby:

module Enumerable
  def interpose obj
    Enumerator.new do |yielder|
      self.each_with_index do |elem, i|
        yielder.yield obj unless i == 0
        yielder.yield elem
      end
    end
  end
end

p [:lather, :rinse, :repeat].cycle.interpose(:and).take(5)
#=> [:lather, :and, :rinse, :and, :repeat]

interleave works similarly to Ruby’s zip, but this one also works on lazy sequences, not Arrays, as in Ruby, meaning that you can apply it to indefinite sequences as well. Here it is in Ruby:

module Enumerable
  def interleave another
    this = self.to_enum
    another = another.to_enum
    Enumerator.new do |yielder|
      loop do
        yielder.yield this.next
        yielder.yield another.next
      end
    end
  end
end

p (0...2).cycle.interleave((0...3).cycle).take(20)
#=> [0, 0, 1, 1, 0, 2, 1, 0, 0, 1, 1, 2, 0, 0, 1, 1, 0, 2, 1, 0]

Both examples are taken directly from Bruce Tate’s book.

Zašto je PHP bolji od Rubija

[Prevod članka Alija Nadžafa, britanskog programera. Original je ovde: Why PHP is better than Ruby]

21.2.2011.

PHP je bolji od Rubija. Eto, rekao sam. U ovom članku ću vam objasniti zbog čega, i usput verovatno iznervirati neke hipi fanove od dvadeset i kusur sa japankama i Mekovima.

U Rubiju sve je objekat… čak i literali!

Ovo je prosto bolesno. Ne znam kako Rubi developeri mogu da sebe nazivaju programerima. U PHP-u nismo pobornici standardnog interfejsa. Mi slavimo svoju šarolikost. Da li je plast, igla ili igla, plast? Da li treba da zovemo metodu nad objektom ili da ga prosledimo funkciji? Ili treba da radimo i jedno i drugo i kodiramo različitim stilovima da bismo učinili život veselijim?

U poređenju sa svakodnevnom avanturom provaljivanja kako PHP radi, Rubi je dosadan. Uzmite kao primer funkcije za rad sa stringovima. Da biste uradili najobičniju zamenu stringa u Rubiju, morate da pozovete metodu na svom stringu, a ne da ga prosledite funkciji za rad sa stringovima. Kakav objektno orijentisani krek je pušio Matz? To ubija svako uživanje u programiranju!

<?php
//zameni foo sa bar na razuman, PHP način
str_replace('foo', 'bar', 'I eat food and play football')
# I eat bard and play bartball

# Kakav pacijent je smislio ovo objektno-orijentisano iživljavanje?
"I eat food and play football".gsub('foo', 'bar')

Pored toga, imam osećaj da su developeri Rubija bili posebno duhoviti kad su smišljali jezik. Hajde da odemo dotle da se složimo da je sve objekat. Ali i klase? “Klase su objekti klase Class”? Neko sigurno umire od smeha na račun ovih ubogih Rubi developera.

Sintaksu Rubija je nemoguće razumeti!

Rubi poseduje takve sumanute i uvrnute začkoljice koje normalno ljudsko biće nije sposobno razumeti. Pogledajte ovo, recimo:

class Address
  attr_accessor :name, :line1, :line2, :county, :postcode, :country

  def Address.valid_postcode?(string)
    #true for valid postcode, false otherwise
  end

  def initialize(data)
    if data[:postcode]
      raise "Invalid postcode" unless Address.valid_postcode?(data[:postcode])
    end
  end
end

Ovaj kod je potpuno nerazumljiv… Kao prvo, nigde nema vitičastih zagrada. Vitičaste zagrade me čine sigurnim i voljenim, a ja ovde ne vidim nijednu. Takođe, gubim osećaj ravnoteže kad nemam zagrade. Iako je suviše zagrada loša stvar (ne podsećajte me na to koliko mrzim LISP), naravno da su nam neophodne za grananja? Argumente funkcija? Zar niko ne uočava ludilo ovde?!

PHP mi omogućava da vežbam svoju veštinu slepog kucanja a Rubi ne

Kao zaluđenik za slepo kucanje, volim da se vežbam. Problem sa Rubijem je što mi dozvoljava da radim iste stvari koje mogu u PHP-u, samo sa mnogo manje kucanja. Pogledajte ovaj primer jednostavne klase sa geterima i seterima u PHP-u, a zatim u Rubiju:

class Address
{
    private $name;
    private $line1;
    private $line2;
    private $county;
    private $postcode;
    private $country;

    public function getName() {
        return $this->name;
    }

    public function getLine1() {
        return $this->line1;
    }

    public function getLine2() {
        return $this->line1;
    }

    public function getCounty() {
        return $this->county;
    }

    public function getPostcode() {
        return $this->postcode;
    }

    public function getCountry() {
        return $this->country;
    }

    public function setName($newName) {
        $this->name = $newName;
    }

    public function setLine1($newLine1) {
        $this->line1 = $newLine1;
    }

    public function setLine2($newLine2) {
        $this->line2 = $newLine2;
    }

    public function setCounty($newCounty) {
        $this->county = $newCounty;
    }

    public function setPostcode($newPostcode) {
        $this->postcode = $newPostcode;
    }

    public function setCountry($newCountry) {
        $this->country = $newCountry;
    }
}

A sada pogledajte istu stvar sa istim pristupom u Rubiju…

class Address
  attr_accessor :name, :line1, :line2, :county, :postcode, :country
end

Ovo je previše kratko da bi bilo kome bilo od koristi. Ako tako lako mogu da pravim klase sa public geterima i seterima na svom poslu, prsti će mi odumreti i neću imati ništa za vežbanje. Hoću da mi se tastatura dimi pošto otkucam definiciju klase, a tri patetične linije Rubi koda nisu ni od kakve koristi.

Takođe, bagovi koji su posledica grešaka u kucanju su vrhunac mog dana i preferiram sintaksu koja mi omogućava da napravim što više takvih. Batalite taj svetogrdni Rubi kod sa svojom konciznom i izražajnom sintaksom. Usredsredite se na ove tople i sigurne vitičaste zagrade. Eto, tako je bolje…

Rubi vam ne dozvoljava da pravite proizvoljne public atribute na objektima!

Jedna od pobedničkih stvari kod PHP-a je po defaultu mogućnost da postavite proizvoljni javni (public) atribut na objektu. Pogledajte sledeći PHP kod:

class Address {
      // vidi gore..
}

$address = new Address();
$address->xCoordinate = 54;
$address->yCoordinate = 73;

Ovo znači da možete da ugurate proizvoljne podatke u objekat gdegod želite u svom kodu! Povrh toga, ne morate da to deklarišete, dokumentujete ili ukažete na to na bilo koji način. Slobodno pišite kod u ostalim delovima sistema koji se oslanja na to da su ove public vrednosti postavljene. Ovo je odlično za očuvanje posla, jer niko osim vas neće moći da razume kako vaš kod radi.

Rubi vam dozvoljava da redefinišete klase, gdegod vam padne na pamet, uključujući i one iz standardne biblioteke!

U Rubiju, možete da uradite ovo:

# klasa za cele brojeve u Rubiju
class Fixnum
  def +(adder)
    self - adder
  end
end
## tako je rođaci, upravo sam pretvorio sabiranje u oduzimanje

Mora da nešto nije u redu sa jezikom koji vam dozvoljava da podrijete osnovna pravila aritmetike!

Šalu na stranu, developeri su po definiciji glupi. I zli. Dajte im priliku, komitovaće suvu konjsku balegu u svn i naprosto se ne može računati na njihovo ponašanje. Ako im pružite mogućnost da menjaju osnove jezika kako im se ćefne, sami tražite frku od svih glupih i zlonamernih developera iz vaše firme.

U nekim ekstremnim slučajevima, primećeno je da Rubi developeri u svom prirodnom okruženju umeju da prave čitave poddijalekte jezika, prilagođavajući jezik svom određenom domenu. Štagod radili, ne dozvolite ovakve jeretičke gluposti u svojoj organizaciji.

Zaključak

Sve sam ispričao, Rubi je nemoguće razumeti, a daje developerima naizgled potpunu kontrolu nad jezikom. Najiskrenije vam predlažem da još jednom razmislite pre nego pokušate da naučite Rubi. To je slično zombi infekciji, dok kažete keks koristićete git za čuvanje koda, radićete od kuće u Textmate-u i bizarne funkcionalne paradigme će početi da se uvlače u način na koji pišete PHP.

Upozoreni ste.

Acer Aspire One D255 review

I needed a cheap netbook to replace my old 7-inch Asus eeePc, already semi-broken, part of its display permanently dead, some keys not working anymore, others pulled out. It is our kitchen computer, used by wife and kid, and main criteria was to be as cheap as possible, so I wouldn’t have to despair if it gets its keys extruded, or milk spilled over.

Asus Aspire One D255 (single-core Atom) is the cheapest netbook around, although others aren’t much more expensive, all sharing similar features - single core Atom processor, 10-inch screen and 160GB hard drive. When deciding which one to buy, main concerns were around number of USB ports, and quality of keyboard and touchpad. At one point I was also hoping to be able to buy it with Windows, and then reuse the license on another computer, but I found out I am not allowed to do that, so it didn’t matter which OS it came with, as I would reinstall Ubuntu anyway.

Aspire One is available in around a dozen different variants, slightly different casing, different OS’s and hard-drive sizes. I heard there are two-core variants, but I haven’t see any of them offered in Serbia.

This D255 comes with bare minimum of features, 160GB hard drive, 1.66 N450 Atom, 1GB of RAM and 3-cell battery (most of the time, the computer is attached to mains, so I didn’t care much about the battery life). Nice thing are 3 USB ports (2 on the left, one on the right side), so I wouldn’t worry about attaching mouse, external keyboard and a USB drive at the same time (an issue I hate with insanely priced Macbook Pro, for example).

So, here are my impressions after installing Ubuntu and working on it for a while:

Keyboard is big enough to comfortably work on (as much as physical size of the netbook itself allows), but the keys are strangely shaped: their surface seems wider than the basis, crosscut resembling letter T. This probably means that it’s easier to accidentally pull out the key while typing (say, if your finger or a fingernail gets stuck between keys). I had similar problem with macbook’s keyboard, and this one seems even more prone to the problem. I’d give it 3/5.

The touchpad is big enough, concerning the space constraints below the keyboard. I dislike the fact that it’s not separated more clearly from the surrounding surface (only two thin lines which can barely be sensed under a finger), so it’s easy for your finger to get outside the sensitive area. Left and right click are performed using a single button, also a bit hard to hit precisely. Also 3/5.

The screen is glossy but of poor quailty - you can see vertical stripes between pixels on a light background. The backlight is LED and it’s uniform across the whole screen, that’s ok. 3/5 again.

The rest of the features are pretty standard so there’s no point in discussing them separately. Atom is powerful enough to surf and play some movies and music. Single core means that the machine can get stuck sometimes.

It has integrated video card, but it works ok for basic needs: Compiz works outside of the box, and there are no visible glitches during video playback, both in a window or fullscreen.

During a normal work, the machine doesn’t get hot at all, the bottom is pleasantly warm to the touch.

Speakers are placed a bit awkwardly - below the palm rest, but turned downwards, on the bottom of the casing. This means that if you place the computer on a soft surface (say, your lap), the sound will get damped. I am not sure if other netbooks use the same idea, but it doesn’t look right to me.

Now - the software. It comes with the Linux preinstalled (I think some variant of Moblin, or Linpus). It looked interesting, quite unusual for a Linux, but I didn’t bother to investigate it much, I just was a bit annoyed that I couldn’t find a button for shutdown or a restart. I installed Ubuntu 10.10 right away. I used a USB flash drive as the netbook doesn’t have optical drive. I had some problems with grub (Error 17), but it resolved by updating grub manually.

Maverick Meerkat runs smoothly on Aspire One, the only thing doesn’t work is card reader (I will try to find a solution and post about it later). Oh, I haven’t tried webcam at all, I don’t know if it works.

That’s about it, here are general impressions:

Pros:

  • Price
  • Runs Ubuntu smoothly

Cons:

  • Keys seem fragile
  • Vertical stripes visible on screen
  • Inadequately placed speakers

Imate novi pasoš, a treba vam nova lična

Pre mesec-dva sam postavio pitanje na ES-u u vezi vađenja nove lične: interesovalo me je šta treba od dokumenata, pod uslovom da sam već vadio novi (biometrijski, crveni) pasoš.

Evo da odgovorim sam sebi: državljanstvo nije potrebno. Izvod iz matične knjige nije potreban, pod uslovom da ste prilikom vađenja pasoša prilagali novi, trajni izvod (roze boje). Ako ste pasoš vadili pomoću starog, zelenkastog, “ne starijim od 6 meseci” izvodom, trebaće vam novi.

Naravno, potrebne su i dve plaćene uplatnice, o tome više na sajtu MUP-a.

StackOverflow-style syntax highlight on Tumblr

There are several articles on how to enable (client-based) syntax highlighting on Tumblr. None of these solutions worked for me, as each requires setting class on pre or code tags manually for coloring JS snippet to recognize areas to colorize. This is not simple in my case, as I am using Markdown as markup language, and generating HTML tags (and their attributes, such as class) is out of control there.

So I decided to slightly modify existing solutions to suit my needs. I took prettify module and combined it with small jQuery snippet of my own, which prepares existing HTML (created using Markdown) for prettification, by dynamically assigning prettyprint class to code blocks.

If you want to do the same, just customize your theme’s HTML to include following lines:

<link rel="stylesheet" type="text/css" href="http://static.tumblr.com/n9ku3gx/bmmlda7os/prettify.css" />
<script type="text/javascript" src="http://static.tumblr.com/n9ku3gx/1k0lda7q0/jquery.min.js"/>
<script type="text/javascript" src="http://static.tumblr.com/n9ku3gx/DiKlda7r3/prettify.min.js"/>
<script type="text/javascript">
  $(function() {
    $('pre > code').addClass('prettyprint');
    prettyPrint();
  });
</script>

And that should be all it takes to get your code nicely highlighted!

“Each with previous” in Ruby

I often need a variant of Enumerable#each method, with a “twist”: sometimes I want to have previous element available along with the current one, most often for comparison between the two. Here’s a trivial example:

array = [
  {name: 'foo', value: 15},
  {name: 'foo', value: 6},
  {name: 'bar', value: 2},
  {name: 'bar', value: 7},
  {name: 'bar', value: 14},
  {name: 'baz', value: 4},
  {name: 'baz', value: 1}
]

array.each_with_prev{|prev, curr|
  # Want to display name only before the first record in the group
  puts curr[:name] unless prev && prev[:name] == curr[:name]
  puts "    #{curr[:value]}"
}
foo
    15
    6
bar
    2
    7
    14
baz
    4
    1

And here’s (very simple, inject based) implementation of each_with_prev:

module Enumerable
  def each_with_prev
    self.inject(nil){|prev, curr| yield prev, curr; curr}
    self
  end
end