links for 2008-06-24

June 25, 2008 – 1:37 am

links for 2008-06-22

June 23, 2008 – 1:35 am

Eating habits of developers

June 12, 2008 – 12:37 pm

This one started out as an internal joke, but it has become quite generic :)

  • Java developers always go to eat together, in pairs, hand in hand, well organized (synchronized)
  • PHP devs go at random times, some of them run, some walk, some take the elevator. (loose coding style)
  • DB devs choose someone, who will then go to kitchen and fetch the food for everyone (also known as proxy)
  • Delphi devs get the plate, put it in the center of kitchen, then get a fork and then walk between the food containers and plate, until plate is filled (drag ‘n drop)
  • C devs kill their own animals and eat them raw (low-level)
  • C++ devs prepare their food from prefabricated components in microwave oven (not that low-level)
  • Frontend (HTML) devs decorate their food with cucumbers, tomatoes and generally everything else in the fridge and then play around with it until the food is cold
  • Python devs always take the stairs (mandatory stepping) (from Jaagup Irve)
  • Perl devs bring their own food to the work and eat it alone in the corner, while everybody else is giving them weird glances (You call THAT food? eewwwww) (syntax)

Scanning files for a specific string

June 11, 2008 – 7:21 pm

Over at DevNetwork forums somebody asked for a piece of code, that scans a directory containing thousands of files for a file containg specific string.

Here is the solution I came up with it:

  1. < ?php
  2. // list file extensions that you care about here
  3. $extensions = array('php','inc');
  4.  
  5. foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $Item)
  6. {
  7.     if ($Item->isFile() and in_array(pathinfo($Item->getFilename(),PATHINFO_EXTENSION),$extensions))
  8.     {
  9.         foreach($Item->openFile() as $linenum => $line)
  10.         {
  11.             // add the code to check your pattern here
  12.             if (stripos($line,'class') !== false) {
  13.                 echo $Item->getPathname(), ':', $linenum, ' ', $line;
  14.             }
  15.         }
  16.     }
  17. }

Upside: it scans the directory structure recursively and the code is quite clean, besides maybe the pathinfo call to filter out filenames with specific extension.

Downside: it’s slow. In real life grep or some other tool is used for task like this.

Still, the code shows the power of SPL File- & DirectoryIterators nicely.

Grouping array contents

June 10, 2008 – 4:02 pm

Source data:

  1. $triples = array();
  2. $triples[] = array('VISA','EUR',13);
  3. $triples[] = array('VISA','EUR',26);
  4. $triples[] = array('VISA','EUR',39);
  5. $triples[] = array('VISA','JPY',13);
  6. $triples[] = array('PAYPAL','JPY',13);

Desired result

  1. array(
  2.     array('VISA','EUR',78),
  3.     array('VISA','JPY',13),
  4.     array('PAYPAL','JPY',13)
  5. )

e.g. group data by both payment method and currency.
My solution

  1. $triples = array();
  2. $triples[] = array('VISA','EUR',13);
  3. $triples[] = array('VISA','EUR',26);
  4. $triples[] = array('VISA','EUR',39);
  5. $triples[] = array('VISA','JPY',13);
  6. $triples[] = array('PAYPAL','JPY',13);
  7.  
  8.  
  9. $result = array();
  10. foreach($triples as $key => $value)
  11. {
  12.     $lookup_key = $value[0] . '-' . $value[1];
  13.     if (array_key_exists($lookup_key, $result)) {
  14.         $result[$lookup_key][2] += $value[2];
  15.     } else {
  16.         $result[$lookup_key] = $value;
  17.     }
  18. }
  19.  
  20. print_r($result);

Downside - data is accessed by numberic key, which is generally not a good thing to do. This however is just a proof of concept, in real life you probably have names for your columns.

Can you write a shorter and more elegant solution?

Searching file contents with Iterators

June 4, 2008 – 11:12 am
  1. // the following code returns all lines of source.txt that contain the string Aerosmith.
  2. // Feel free to extend it for your own uses
  3. class FileGrep extends FilterIterator
  4. {
  5.     private $needle;
  6.  
  7.     public function __construct($file, $needle) {
  8.         parent::__construct(new SplFileObject($file));
  9.         $this->needle = $needle;
  10.     }
  11.  
  12.     public function accept()
  13.     {
  14.         if (strpos($this->current(),$this->needle) !== false) {
  15.             return true;
  16.         }
  17.     }
  18.  
  19. }
  20.  
  21. foreach(new FileGrep('source.txt','Aerosmith') as $line) {
  22.     print $line;
  23. }

SimpleXMLIterator & FilterIterator combined

June 3, 2008 – 10:55 pm
  1. < ?php
  2. /*
  3.     Goal:
  4.       * Take a GPX (which is XML) file
  5.       * Extract interesting records from it
  6.       * Calculate the arithmetic average of latitudes and longitutes
  7.      
  8.     I won't tell you why exactly I needed this, just that it is part of a game
  9.     called geocaching
  10.  
  11.     —
  12.    
  13.     Class is called collector, because I am _collecting_ only the records
  14.     I'm interested in
  15.  
  16.     Example record:
  17.         <wpt lat="59.4658317566" lon="24.8649997711">
  18.             <name>< ![CDATA[Gtehnokratt]]></name>
  19.             <url>< ![CDATA[http://www.geopeitus.ee/?p=350&c=2]]></url>
  20.        
  21.    
  22.     Actually there is more data, but I'm only interested in lat and lon attributes
  23.     and name and url elements.
  24.  
  25.     Records do not have any id-s, only the url has the unique identifier at the end.
  26. */
  27.  
  28. class Collector extends FilterIterator
  29. {
  30.     /**
  31.      * I only care about records with id's that are listed here
  32.      */
  33.     private $ids = array(187, 513, 537, 542, 544, 563, 605, 715, 717, 748);
  34.  
  35.     /**
  36.      * Set up the FilterIterator by passing our SimpleXMLIterator to it
  37.      */
  38.     public function __construct(Iterator $it) {
  39.         parent::__construct($it);
  40.     }
  41.  
  42.     /**
  43.      * Part of FilterIterator implementation, called for each record,
  44.      * responsible for the decision whether the current element is needed
  45.      * or not
  46.      */
  47.     public function accept() {
  48.         $id = $this->get_id_from_url($this->current()->url);
  49.         if (in_array($id,$this->ids)) {
  50.             return true;
  51.         }
  52.         return false;
  53.     }
  54.      /**
  55.      * Extracts record ID from string
  56.      */
  57.     private function get_id_from_url($url)
  58.     {
  59.         // http://www.geopeitus.ee/?p=350&c=514
  60.         preg_match('/&c=(\d+)$/',$url,$matches);
  61.         return $matches[1];
  62.     }
  63. }
  64.  
  65. /*
  66.     SimpleXMLIterator is one of the standard SPL iterators, which makes it possible
  67.     to use other standard iterators when parsing XML
  68.  
  69.     Second argument of simplexml_load_file is a class name and as result the XML
  70.     in-memory representation becomes instance of that class. Seems awkward, but
  71.     really useful
  72. */
  73. $it = simplexml_load_file('geopeitusee.gpx','SimpleXMLIterator');
  74.  
  75. $lat_sum = $lon_sum = $count = 0.0;
  76.  
  77. // so, all the data goes in, but only the elements I'm interested in, come out
  78. foreach(new Collector($it) as $element) {
  79.     // access subnodes with $element->name
  80.     // access attributes with array notation
  81.     printf("taking %s, lat=%f, lon = %f\n", $element->name,$element['lat'],$element['lon']);
  82.  
  83.     // typecasting is needed to get correct results from SimpleXML, otherwise you would
  84.     // get integers
  85.     $lat_sum += (float)$element['lat'];
  86.     $lon_sum += (float)$element['lon'];
  87.     $count++;
  88. }
  89.  
  90. // finally do the math
  91. printf("Average: cnt=%d lat=%s, lon=%s\n", $count, ($lat_sum / $count), $lon_sum / $count);

How to make sure you’re an Estonian

May 29, 2008 – 4:55 pm

1. You use the word “normal” if something is ok.

2. When visiting friends abroad you bring along a box of Kalev chocolate.

3. You attended a song festival at least once either as a performer or as a spectator.

4. You know that going to the sauna is 80% about networking and 20% about washing.

5. You are nationalistic about Skype (it is actually an Estonian company).

6. ‘Kohuke’ belongs to your menu.

7. You declare your taxes on the internet like all modern people.

8. You actually believed for a while that Latvians had 6 toes per foot when you heard that as a child.

9. You are convinced that Estonia is very strategically located.

10. You spent at least one midsummer in Saaremaa, Hiiumaa or one of the smaller islands.

11. You can quote films like “Viimne reliikvia” and “Siin me oleme”.

12. You spit three times around your left shoulder for good luck.

13. Words like “veoauto”, “täieõiguslik” or “jää-äär” sound perfectly pronouncable to you.

14. You like bold statements, such as this one?

15. There can never be too much sarcasm.

16. You can at times drink hot tea to hot food.

17. You are disappointed that Jaan Kross never got the Nobel prize in literature.

18. It would not be suprising for English-speakers to find your name naughty (Peep, Tiit, Andres [sounds like undress]) or hippy (Rein, Rain).

19. You have been to Finland.

20. You say ‘Noh’ (sounds like NO) even when you speak English, just to confuse people.

21. You know the lyrics to “Mutionu” and “Rongisõit”.

22. You would never mistaken Kreisiraadio for a radio station.

23. You would agree that wife-carrying is a real sport (at least as long as Estonians are winning).

24. Your best friend’s girlfriend is your English teacher’s daughter and they live next door to your grandparents, who were colleagues with your advisor, who is friends with your?

25. You think that any beverage below 20% is non-alcoholic.

26. You check the thermometer before going out.

27. You look in both directions before crossing the road, even if it’s a one-way street.

28. You grin very mysteriously when people ask about your national food.

29. You teach a non-Estonian speaker the word “Tänan” before “Aitäh”.

30. You put ketchup inside your pasta (french-cooked gourmet faire la finemanger pasta) in order to not to get the ketchup-bowl dirty.

31. You cheated on your husband/wife at least ten times but you still think you’re in a good marriage.

32. When someone asks you “Where is Estonia?” you quickly reply that it’s located in Northern Europe close to Finland?

33. Your grandmother’s “purse” is an old plastic bag that has been reused several times.

34. Sour cream tastes good with everything.

35. A foreigner speaks to you in broken horrible Estonian and you go on and on about how wonderful their Estonian is compared to “the Russians”.

36. You have ever worn or seen anyone wear “karupüksid”.

links for 2008-05-11

May 12, 2008 – 1:30 am

links for 2008-05-09

May 10, 2008 – 1:33 am