Archive for the ‘Computer’ Category

Programmation objet

Mardi, novembre 18th, 2008

 Extrait d’une entrevue avec le créateur du langage Erlang.  Il parle de sa vision de la programmation orientée objet.
Ref: http://www.infoq.com/interviews/Erlang-Joe-Armstrong

You’ve been reading my OOP sucks blogs. I saw a blog yesterday, they said Erlang is actually more object oriented, truer to the spirit of pure object orientation than all object oriented languages. You could take two views: you could say either Erlang isn’t object oriented - which I used to say a few years ago - or you could say it’s more object oriented than all the object oriented languages. Alan Kay said that he made a mistake in not really emphasizing the messaging aspect of object oriented programming. He said in SmallTalk you talk about sending a message to an object, but you don’t, you do a function call. I think function calls and remote procedure calls are too high-level in the sense that a function call or a remote procedure call returns to the person who made it.

If I do remote procedure call against you, I can say “Hey, do this!” and the answer automatically comes back to me, but that’s not how we work. I could say “You do that” and reply to this guy. Why am I involved? That’s how we behave. If you are a manager at office you say “Can you check this out? When you’ve done it, tell this guy”. This is just an asynchronous message passing model. I think when you talk about object orientated programming, when you model a world, you are encouraged to think in terms of objects and I don’t see objects. I also have what you would call the categorization problem: which object do I put my code in? Sorry I just don’t get this. Let’s suppose you have a method, in SmallTalk terms, that manipulates time of a directory structure or something like that, is this a subclass of a time object or is it a subclass of a directory object? I don’t know.

Years ago I’ve started several projects staff - file my data/my letters, physical papers and research reports and things like that. Every time I’ve done that it failed, because I get files and I put something on this line - it says “Correspondence”, “Lectures”, “Papers”. Then I get this thing: it’s a paper, I put it in the file called papers; this is a letter which contains a paper “Do I put it in ‘Correspondence’ or do I put it in ‘Lecture notes’?”. It breaks down because I don’t know where to put it. I think if you’ve got objects in your function, which object do you put it in? I made another filing scheme, in which I just numbered everything, and I have files and I go over my office and the first file says 1-167 and the next file says 168- something. I have a single file that goes 1,2,3,4 and some text. I use emacs to create, I use grep to search, and it’s a brilliant system!

This is how we organize things in English. We have a dictionary and when we want to know what the word means, we look it up in the dictionary. Everything is in alphabetical order - that’s a good way to organize data. I think object oriented programming is not a good way to organize data. There is a principle in programming “Never write something twice” - yes, it’s a fine principle, a great principle, but let’s think about this: “How do I find the old stuff, that I am going to reuse?” That becomes extremely difficult, in fact, I think people have been deluded into thinking that this choice is easy. When I started programming, there were no choices, I programmed everything in Fortran - Fortran was the only language I had on my machine. Nowadays, some poor sod’s got to choose the programming language: “Should I have Java or C# or C++ or Lua or F# or Pascal or Prologue or Erlang or Haskell? On what should I do it?” “You don’t want something in the-NET framework or a Java framework that runs on the JVM or on Mac OSX?”

You have all these decisions, incredibly difficult to make, and then you got bosses. You don’t write this stuff in scratch! You got to reuse somebody else’s code. After all that is. Somebody else’s code doesn’t do exactly what you want - it does something that’s subtly different. Then, the time taken to modify and understand this old code takes an incredible amount of time. Have you ever sat there with code that somebody else has written and have to modify it? You spend hours and hours doing it. You can’t reuse object oriented code, because all the stuff it inherited has to be there as well. You can’t just take this stuff out and put it in your program cut and paste, like you did in C, or Erlang or Prologue or Perl, you got to take all the stuff it inherits from.

One of the problems I had with object oriented programming, one guy said: “You wanted a banana but what you got was a gorilla that was holding the banana and the entire jungle. You got a lot of stuff in it and all you wanted was just a little bit of code”. The Lisp idea - lots of little functions - ubiquitous data structures like Lists, everywhere, and lots of very small functions that work on this, that these are highly reusable. Code that’s referentially transparent, that means if you call it twice with the same arguments, you get the same value - it’s very reusable. To them the question is “How do we reorganize all this stuff? I think something like a dictionary, like the English dictionary, put in alphabetical order. Don’t put lots of modules, just put one module! If code is referentially transparent, it’s small functions, then it doesn’t belong to object. Where does it belong? What is the containing object? There isn’t one! So, just put them all in alphabetical order and use Google to search it and you’ll find the code easily.

REST, RESTFull, RESTLess the saga

Lundi, octobre 20th, 2008

Un bon vieux principe élémentaire du web.. un URL c’est supposé être un document.

Du Full REST (et même du rest less) implique donc qu’un URL correspond à 1 document et soit “cachable”.

La nomenclature d’une URL du type

http://”HOST_NAME”/usedcar/fullloadbygeocoordinates?lat=43.345&long=-79.801&dist=250

serait donc fautive.. il faudrait utiliser un format

GET http://…./fullloadbygeocoordinates/43.345,-79.801

pour être plus conforme.

Cependant l’utilisation avec des paramètres pourrait être faite en utilisant préalablement un POST pour créer un document

POST http://”HOST_NAME”/usedcar/fullloadbygeocoordinates?lat=43.345&long=-79.801&dist=250

qui retournerai l’URL d’un nouveau document créé en utilisant les coordonnées en paramètre et par la suite appellé en GET

GET http://….url retourné… ?page=1&encoding=json
Ce nouveau document peut être référé par plusieurs requêtes POST avec plus ou moins de précisions sur les coordonnées, permet de faire varier l’ordre des paramètres, etc.  Ce nouveau document est également référençable et “cachable”.

L’utilisation de l’URL fautive (avec les lon/lat en paramêtre dans la requête GET) devrait au moins retourner une redirection (302) sur un URL correctement forgé avec les coordonnées dans l’URL comme référence au nom du document et non pas en paramètre.

Mac Os X - Barre d’application

Dimanche, septembre 21st, 2008

Saviez-vous qu’on peut retirer facilement des icones de la barre d’application au haut (par défaut) dans Os X?  Il suffit de cliquer dessus en maintenant la touche commande (la pomme) enfoncée et de “dragger” les icones hors de la basse.  C’est de cette manière dont je me suis débarassé de l’icone de “mobile me” que je n’ai jamais demandé de voir apparaître!.L’on peut également de cette manière, réorganiser les icones présentes dans la barre en les déplaçant sur la barre. 

Building PNG Images

Jeudi, septembre 18th, 2008

Did you ever try to build a png image (with a programming language, not an image editor)?  A lot of code sample are available on the internet.  But most if not all are using libpng or some high level libraries like gd.

But what happend if you can’t install libraries on the system where you’re working?  Ever thing about building an image from scratch?  Here is what I do in PHP.

This isn’t the most performant code, but at least it generate a valid PNG image without any non standard libraries.   (Some one could say that zlib or crc are php external libs.. but I haven’t see any php distribution whitout them in a while!)

<?php
/*
* Title: PNG Image Generation
* Author: Jean-Luc Cyr
* Date: 2008-09-17
* License: GNU GPL2
* Description: Generate a simple PNG image
* directly in PHP without using external libs
* like GD.
*/
 
header("content-type: image/png");
 
function long2string($long)
{
$string = chr(($long&0xFF000000)>>24).
chr(($long&0xFF0000)>>16).
chr(($long&0xFF00)>>8).
chr(($long&0xFF)>>0);
return $string;
} // long2string()
function build_png($matrix, $w, $h)
{
////////////////////////////////////////////////////////////////
//PNG Header
$image = chr(0x89).chr(0x50).chr(0x4E).chr(0x47);
$image .= chr(0x0D).chr(0x0A).chr(0x1A).chr(0x0A);
 
////////////////////////////////////////////////////////////////
//Header Chunk
 
//Chunk type
$chunk = "IHDR";
//Chunk data
//Width
$data = long2string($w);
//Height
$data .= long2string($h);
//Depth
$data .= chr(8); //Bits per sample
//Color Type
$data .= chr(2); //RGB
//Compression method
$data .= chr(0);
//Filter method
$data .= chr(0);
//Interlaced method
$data .= chr(0);
 
$crc = crc32($chunk.$data);
//Add length at start
$chunk = long2string(strlen($data)).$chunk.$data;
//Add CRC at the end
//Dump chunk
$chunk = $chunk.long2string($crc);
$image .= $chunk;
 
////////////////////////////////////////////////////////////////
//Data Chunk
 
//Chunk type
$chunk = "IDAT";
//Data (2x2 rgb 8bits)
$s = 3; //samples per pixels
#$matrix  ="\0\0\0\0\0\0\0\0\0";
#$matrix .="\0\0\0\0\0\0\0\0\0";
#$matrix .="\0\0\0\0\0\0\0\0\0";
// No filter so add 0 to beginning of each scan line
$datas = '';
for($c=0; $c<$h; $c++)
$datas .= "\0". substr($matrix,$c*($w*$s),($w*$s));
// Compress Data
#$zdata = gzencode($data,9,FORCE_DEFLATE);
#$zdata = gzdeflate($data,0);
$zdata = gzcompress($datas,0);
// Calculate CRC
$crc = crc32($chunk.$zdata);
// Add length at start
$l = strlen($zdata);
$chunk = long2string($l).$chunk.$zdata;
// Add CRC at the end
$chunk = $chunk.long2string($crc);
$image .= $chunk;
 
////////////////////////////////////////////////////////////////
//End Chunk
 
// Chunk type
$chunk = "IEND";
// Data
$data = "";
// Calculate CRC
$crc = crc32($chunk);
// Add length at start
$chunk = long2string(strlen($data)).$chunk.$data;
// Add CRC at the end
$chunk = $chunk.long2string($crc);
$image .= $chunk;
 
// Send out the image
echo $image;die();
} // build_png()
////////////////////////////////////////////////////////////////
// Demo code
 
// Build a simple image matrix
// 256 x 256 x 8rgb
 
$w=256; // width
$h=256; // height
$s=3;   // 3 x 8 bits samples per pixel (8bits rgb)
for($x=0; $x<$h; $x++)
for($y=0; $y<$w; $y++)
//    for($z=0; $z<$s; $z++) //Ordered R G B
$matrix .=
chr( ( (($y/64)<1) && (($y/64)>0) )?$x:0 ). // R
chr( ( (($y/64)<2) && (($y/64)>1) )?$x:0 ). // G
chr( ( (($y/64)<3) && (($y/64)>2) )?$x:0 ); // B
 
build_png($matrix,$w,$h);
die();
 
////////////////////////////////////////////////////////////////
// Hex dump image for debugging
 
for ($x=0; $x<strlen($image); $x++) {
printf("%02X ",ord($image[$x]));
if ((($x+1)%16)==0)
printf("<br/>");
}

Agile - Scrum

Jeudi, juillet 10th, 2008
Mais qu’est-ce que c’est que ça Agile et Scrum?
Selon WikiPedia:
 

Scrum est une méthode agile pour la gestion de projets.
 

et

La notion de méthode agile se limite actuellement aux méthodes ciblant le développement d’une application informatique. Ces méthodes Agiles permettent de concevoir des logiciels en impliquant au maximum le demandeur (client), ce qui permet une grande réactivité à ses demandes. Les méthodes agiles se veulent plus pragmatiques que les méthodes traditionnelles. Elles visent la satisfaction réelle du besoin du client, et non d’un contrat établi préalablement. La notion de méthode agile est née à travers un Manifeste Agile signé par 17 personnalités.”

J’ai essayer de trouver quelques liens intéressants sur le sujet.

En premier, voici deux podcasts (en anglais) dont l’un avec un des ”inventeurs” du scrum.



Et voici les autres

Il y a également plusieurs volumes intéressants et d’autres liens pertinents.

PHP Post

Lundi, avril 28th, 2008

Here a quick example of how-to post some data over the web in a simple php script.

<?php
$datastream = array(
'short_msg'=&gt;'this is a simple message',
'address'=&gt;'98887996662',
);
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, <a href="http://psms.canoe-inc.com/send_sms" class="moz-txt-link-rfc2396E">"http://psms.canoe-inc.com/send_sms"</a>);
$o="";
foreach ($datastream as $k=&gt;$v)
{
$o.= "$k=".utf8_encode($v)."&amp;";
}
$post_data=substr($o,0,-1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);

Graphical widgets

Mercredi, avril 23rd, 2008

Are you like me, programming a lot but not been a graphical designer?  I’ve found a project offering all the icons we could need to make some pretty apps without loosing our time drawing (which will be obviously ugly) icons.

Juste go and take a look at Tango Desktop Project.

How did i find it?  I was just reading my daily stuff (newsforge, slashdot, etc) and I discover luminote, a web based note collector which use tango for their design.

Utilisation de sphinx sous os x

Mardi, février 26th, 2008

Sphinx est un engin de base de donnée et de recherche plein texte.Pour installer sphinx, vous devez installer plusieurs paquetages GNU.  Pour ce faire sous mac os-x le plus simple est d’utiliser macport.  Vous devez en autre installer mysql. (Commande: sudo port install mysql5)Par la suive vous devez compiler sphinx avec la commande suivante: ./configure --with-mysql=/opt/local/ --with-mysql-includes=/opt/local/include/mysql5/mysql/ --with-mysql-libs=/opt/local/lib/mysql5/mysql/ Je vous donnerai plus de détails bientôt sur son utilisation. 

ASN.1/DER/BER PHP

Mercredi, février 13th, 2008

Je vous ai parlé dernièrement de ASN.1. Voici un petit parseur de base en PHP

 
//Title: Simple PHP BER/DER/ASN.1 basic decoder
//Author: Jean-Luc Cyr
//Date: 2008-02-13
//Desc: Simple BER Printable string dumper
//	read BER data from a file
 
// Set input filename
$filename = 'o';
// Set max number of tag to parse (0 = no limit)
$limit = 0;
 
//Open data file
$f = fopen($filename,'rb');
//Set read tag number to 0
$c=0;
//While not end of file
while(!feof($f))
{
    //Read first block data type
    $type = ord(fread($f,1));
    if ($type==0)
      break;
    //Read first len block
    $len = ord(fread($f,1));
    if ($len==0)
      break;
    $le = 0;
    //If first bit of len is set (1)
    //we have a multiple bit len to read
    if (($len&amp;128)==128)
    {
        echo "Big Len ".($len&amp;127)." Bytes\r\n";
        for ($i = 0; $i &lt; ($len&amp;127); $i++)
          $le = $le * 256 + ord(fread($f,1));
        $len = $le;
    }
    //Findout data type (first 2 bits)
    $cl = ($type &amp; (128+64) ) &gt;&gt; 6;
    switch($cl)
    {
     case 0:
        $cla = 'Universal';
        break;
     case 1:
        $cla = 'application';
        break;
     case 2:
        $cla = 'context-specific';
        break;
     case 3:
        $cla = 'private';
        break;
    }
    //Dump some info
    printf("[$cla] Type: %x (%d), len: %d\r\n",$type,$type,$len);
    //Read data chunk
    $data = fread($f,$len);
    //Display data chunk based on type
    switch($type)
    {
     case 2: // integer
        break;
     case 3: // bit string
        break;
     case 4: // octet string
        break;
     case 5: // null
        break;
     case 6: // object identifier
        break;
     case 16: // sequence and sequence of
        break;
     case 17: // set and set of
        break;
     case 19: //string
        printf("Data: $data\r\n");
        break;
     case 20: // t61string
        break;
     case 22: // ia5string
        break;
     case 23: // utctime
        break;
     default:
        #printf("Data: $data\r\n");
        break;
    }
    //increment count
    $c++;
    //check if we reach the number of tag specified
    if (($c&gt;$limit)&amp;&amp;($limit&gt;0)) break;
}
 
//close our input file
fclose($f);

Les mails à l’ancienne

Mercredi, février 13th, 2008

Utilisez-vous toujours logiciel graphique pour lire vos courriels? (outlook, thunderbird, mail)  Où vous êtes comme moi et aimez pouvoir lire vos courriels a distance avec une connexion terminal (telnet ou ssh)?

Depuis plusieurs années j’utilise le logiciel ‘mail’ à l’occasion mais je me suis trouvé un affinité particulière pour ‘pine‘.  Je l’avais un peu délaissé ces derniers temps car l’utilisation du format ‘maildir’ au lieu des ‘inbox’ standard de unix ne me permettait plus de voir mes courriels autres que dans la boite de réception.

J’ai maintenant trouvé la méthode pour utiliser ‘pine’ avec les ‘maildir’.

  • Premièrement lancer PINE
  • Aller dans le menu de configuration ‘S
  • Aller dans le sous-menu ‘L
  • Configurer une liste de boites.  La seule valeur qui importe c’est le chemin (’path’) où il faut mettre #md/Maildir
  • Ensuite retourner au menu principal
  • Aller dans le menu de configuration ‘S’
  • Aller dans le sous-menu ‘C’
  • Dans la section ‘folder preferene’ activer l’option ‘enable-dot-folders’

Et voilà vous devriez voir tous vos ‘maildir’ maintenant.