Never ever use a singleton

I was testing old code while suddenly a Singleton class attacked me!

What is this pattern again?

class MyEvilSingleton{
    private static $instance;
    private $whatever;
    private __constructor(){
    }
    public static function getInstance(){
        if(self::$instance === NULL){
            self::$instance = new MyEvilSingleton();
        }
        return self::$instance;
    }
    public function doSomeNastyStuff($AddMe){
        $this->whatever.="something else ".$AddMe;
    }
    public function getNastyStuff(){
        return $this->whatever;
    }
}

So now we can do this


// File 1
$myInstanceOfAnEvilClass = MyEvilSingleton::getInstance();
$myInstanceOfAnEvilClass -> doSomeNastyStuff("test");
$myvar = $myInstanceOfAnEvilClass -> getNastyStuff();
// $myvar="something else test";
...
// File 2
$myInstanceOfAnEvilClass = MyEvilSingleton::getInstance();
$myInstanceOfAnEvilClass -> doSomeNastyStuff("test");
$myInstanceOfAnEvilClass -> getNastyStuff();
// $myvar = "something else testsomething else test";

Most of the time a website is called by several modules and if one developper is working on file 1, another on file 2 some bugs will appear somewhere in the page and that will be a pain in the A** to debug.

Let’s talk a bit about unit testing.

If your objective is to have a lot of ticket in the support ticketing system go ahead… if your objective is to reduce cost and enhance efficiency you will probably try to unit test your code.

let’s test the previous class

class MyEvilSingletonTest {
    public function test_doSomeNastyStuff(){
        $myInstanceOfAnEvilClass = MyEvilSingleton::getInstance();
        $expected = "something else";
        $myInstanceOfAnEvilClass -> doSomeNastyStuff("test");
        $actual = $myInstanceOfAnEvilClass -> getNastyStuff();
        $this->assertEquald($expected,$actual);
    }
    
    public function test_doSomeNastyStuffDefaultEmpty(){
        $myInstanceOfAnEvilClass = MyEvilSingleton::getInstance();
        $expected = "";
        $actual = $myInstanceOfAnEvilClass -> getNastyStuff();
        $this->assertEquald($expected,$actual);
    }
}

First test will pass

Second test will fail

How do you solve that… here are some hint but that needs some adaptation in your Singleton pattern by adding some nastier stuff in there (reset, parameter to functions, pulbic test property…)

Worst: testing order becomes important !!!

There is no nice solution with Singleton

Next time you want to do a Singleton, think it again, write the test and don’t write a Singleton.

And if you really want a Singleton… share one from Dufftown with me instead and I will convince you that you don’t need it.

singleton 12 years

Qualcomm Snapdragon 800 (Sony Xperia Z1) WebGL Speed test

vlcsnap-2013-11-12-00h14m01s45

It was really hard to find a competitive device so I finally choose my 4 years old mac book pro to have a good point of comparison.

Comparing cell phone and laptop was just unbelievable 3 years ago. But now we can! Again Moore’s law is still true.

I wanted to try out some WebGL demo, I tried few chrome experiment and I was surprised to see them working smoothly.

So I decided to compare with my Laptop and sometime the FPS was faster on the SnapDragon 800 device.

If anyone is interested I stored all the figures here and the video on Youtube.

Comparison Method

  • No other application running in the background
  • Same navigator
  • Wait 10 seconds after the animation start
  • Read the most seen mean FPS (with the birds, the FPS vary a lot when there are no birds it’s around 50 FPS when there are a lot of birds it’s more near 18 FPS but as the FPS displayed is a mean FPS for a specific amount of time, I use the one I see the most often)

For the threejs car there is no FPS displayed but you can see how smooth it is in the video

Test sites

  • http://threejs.org/examples/#webgl_materials_cars
  • http://threejs.org/examples/#webgl3_performance
  • http://threejs.org/examples/#canvas_geometry_birds
  • http://webglsamples.googlecode.com/hg/aquarium/aquarium.html

Figures

Mac Book Pro (5.1) Sony Xperia Z1
CPU Intel Core 2 Duo Krait 400
CPU Speed 2.4 Ghz 2.15 Ghz
Cores 2 4
Memory 4 GB 2 GB
Graphic NVIDIA GeForce 9400M Adreno 330
Vram 256 MB
Screen Resolution 1280×800 1776×1080
Test: measuring FPS
threejs Material Car N/A N/A
threejs Birds 31 14
threejs Performance 13 12
Aquarium with 50 fish 30 46
Aquarium with 100 fishes 25 44
Aquarium with 250 fishes 21 36
Aquarium with 1000 fishes 20 18

Chart

SnapDragon800FPSComparison

Pâtes au chicon, jambon et fromage de chèvre (ou le chicon au gratin revisité)

J’avais envie de chicon au gratin… et sans purée je me suis dit pourquoi pas avec des pâtes (sacrilège oui je sais).
Notez bien que je n’avais plus de fromage rapé non plus… mais bien du chèvre! (deuxième sacrilège).

Néanmoins ce n’était pas mauvais.

Voici la recette en image!

Ingrédients pour 2 personnes (mais j’ai tout mangé tout seul)

  • 2 chicons
  • 2 tranches de jambon coupée en dés
  • 1 tranche de bûche de chèvre (les grosses sur ~1.5 cm d’épaisseur)
  • 30 gr de beurre
  • 1 citron (vert je n’avais plus que ça)
  • 30 gr de farine
  • 300 ml de lait (tiède)
  • 300 gr de pâtes
  • 1,5 L d’eau bouillante

Préparation des chicons

Couper les chicons en 2 (sens de la longueur) enlever la partie amère (en bas) et les déposer dans une casserole anti-adhérente avec un petit peu de beurre (5 gr).
Verser le jus du citron, couvrir et laisser cuir à petit feu pendant 30-35 minutes. Rajouter de l’eau (quelques cl) dès qu’il n’y a plus assez de jus de cuisson.

Cuisson des chicons avec le jus de citron (vert)

Cuisson des chicons avec le jus de citron (vert)

pendant ce temps

Cuire les pâtes et les refroidir à l’eau froide en fin de cuisson

Dès que les pâtes sont cuites: préchauffer le four à 180 °C

Préparation de la béchamel

Dans une casserole moyenne (>1 L) faire fondre le beurre à feu doux, dès que le beurre est fondu, rajouter la farine et à l’aide d’un fouet mélanger.
Verser ensuite un fond de lait, attendre les premières bulles et mélanger.
Re-verser un fond de lait, attendre les premières bulles et mélanger…

mélanger la béchamel dès que ça reprend

mélanger la béchamel dès que ça reprend

Couper le chèvre en petit morceaux et l’ajouter à la préparation.
Optionnel: Moi je rajoute le fond de jus de cuisson des chicons dans la béchamel mais ça peut déranger (citron + amertume)

Rajouter le jus de cuisson dans la béchamel

Rajouter le jus de cuisson dans la béchamel

Le plat

Déposer les pâtes dans un grand ramequin pour le four.

Déposer les pâtes dans le ramequin

Déposer les pâtes dans le ramequin

Déposer le jambon dessus.

Déposer les morceaux de jambon

Déposer les morceaux de jambon

Déposer les chicons légèrement essoré.

déposer les chicons

déposer les chicons

Verser la béchamel par dessus le tout et enfourner pour 15 minutes (ou plus pour avoir une jolie croûte)

Verser la béchamel sur la préparation

Verser la béchamel sur la préparation

Les photos ont été réalisée avec le Sony Xperia Z1 en mode ‘Manual>gourmet’ ou en mode ‘Time shift burst’ (pour la sauce par exemple)

I want to highlight words in file (one liner)

sed_cat_bash

Let’s say you want to highlight the following specific text: w00tw00t.at in red bold in your apache log

cat /var/log/apache2/*.log | sed 's/w00tw00t\.at/\\\\e\[31;1m\0\\\\e\[0m/i' | while read line; do echo -e $line; done;

Don’t forget to escape your dots, dashes, brackets in the search part of the regexp.

It should highlight like a grep –color the part you are looking for.

Strict Javascript

While looking at Win8 apps I ran into the “strict mode” keyword directive prologue.

"use strict"; reminds me of perl :P

As always, using strict is good practice. Scope it locally first:


(function (){
"use strict";
// ...
})();

It will allow your javascript engine to gently remind you wrong usage such as: duplicated properties (same name), duplicated parameters, undeclared variable, RO/RW property, non extensible property, property deletion, usage of future/present reserved keywords, this (object) protection, eval scope, withdraw the usage of with, withdraw usage of octal.

Well that sounds great, using strict mode will just allow you to avoid typo, misuse and to follow best practice.

So why don’t use it?

Probably when you need to mix it with code that don’t use strict mode. But as I said you can scope it so for your own libs don’t hesitate go STRICT!

Source:

Ubuntu 12.04 Nginx MariaDB Php

I just wrote an article about Nginx & PHP 54 fpm on irtbf posterous site

Activate full log MariaDB/Mysql

  1. Set the log filename
    db001 [(none)]> SET GLOBAL general_log_file = '/var/log/mysql/full.log';
  2. activate full log
    db001 [(none)]> SET GLOBAL general_log = 'ON';
  3. deactivate full log
    db001 [(none)]> SET GLOBAL general_log = 'OFF';

credit: Michaël

XPdev hot seat at work experience learned

I proposed new objectives to myself:
Programming in XP (hot seat: 2 dev one computer) 1/2 day per week with another developer each week.
Here is a summary of DOs and DONTs to keep in mind.

Let’s say there are 2 guys:

  • Tori: the executor (the guy who have the keyboard and explain what he does)
  • Uke: the learner (the guy who look at the guy who have the keyboard and learn from what he does)
DO DON’T
Explain the whole concept of XP hot seat, Tori & Uke roles and plan it Start without briefing, scheduled appointment
Predefine the scope 1 day before start without plan
Master the concept of the scope do a spike in XP as it request a lot of documentation reading
Read the documentation the day before Drive blind
Use shortcuts, quick links, snippets, auto completion, syntax highlighting Use notepad or similar way of development
Refine and reduce objective and scope while working Enlarge the scope and work on more and more stuff
Let Tori explain what he is doing Let Uke take the lead
Respect the time window of 15 minutes Let Tori continue over 15 minutes
Stop and re-schedule, redefine scope when it fails (both get stuck by a lack of knowledge for instance) Continue if it doesn’t work

Upgrading from ubuntu 11.10 to 12.04LTS

Same issue. In system settings: clicking on Network raise a popup with: The system network services are not compatible with this version…

No network at all

cat /etc/interfaces
auto lo
iface lo inet loopback

Gasp.

update 1 hour later

Problem solved.
Obviously the upgrade process crashed somewhere, I clicked the “Updates Available…” menu item from the top right computer menu and ran a partial upgrade which finished successfully the 12.04 install and restarted the network.
I guess the X server failed during the night waiting for me to click a dialog box. This morning the screen was dark and the pc was running, but with no answer from the keyboard I thought he hanged at the restart stage… but it was at the config stage somewhere.

Everything back to normal. Resuming normal activities.

end of transmission

Mysql 5.5.20 utf8 collation bug with implicit datetime casting

A very strange behavior detected in Mysql 5.5.20 maybe linked to some implicit cast/convert: The datetime is implicitly converted to the next day…

it’s a morning bug, solved every afternoon and detectable thus only in the morning, probably an AM/PM error while working in 24h…

That’s a really stupid bug that makes me waste half a day so I post it here, just in case someone has the same issue.

It did not exist in 5.1 and does not exist in MariaDB, so it’s probably something added by Oracle somewhere in between…

Here is the query with a between date, with the standard connection settings:

show variables like 'character%';
+--------------------------+---------------------------------------+
| Variable_name            | Value                                 |
+--------------------------+---------------------------------------+
| character_set_client     | latin1                                |
| character_set_connection | latin1                                |
| character_set_database   | utf8                                  |
| character_set_filesystem | binary                                |
| character_set_results    | latin1                                |
| character_set_server     | utf8                                  |
| character_set_system     | utf8                                  |
| character_sets_dir       | /opt/mysql/server-5.5/share/charsets/ |
+--------------------------+---------------------------------------+
SELECT * 
FROM tableA A 
WHERE (A.`end_date` >= '2012-04-27T07:04:25+02:00') 
AND (A.`start_date` <= '2012-04-28T06:30:00+02:00' );
| id    | start_date          | end_date            |
| 42966 | 2012-04-27 19:50:00 | 2012-04-27 22:55:00 |
| 36883 | 2012-04-27 23:00:00 | 2012-04-27 23:50:00 |

Trying with the settings switched to utf8 still works.

SET NAMES utf8;
SELECT * 
FROM tableA A 
WHERE (A.`end_date` >= '2012-04-27T07:04:25+02:00') 
AND (A.`start_date` <= '2012-04-28T06:30:00+02:00' );
| id    | start_date          | end_date            |
| 42966 | 2012-04-27 19:50:00 | 2012-04-27 22:55:00 |
| 36883 | 2012-04-27 23:00:00 | 2012-04-27 23:50:00 |

And then, TADAAA the bug, with implicit casting while using the collate utf8_unicode_ci.

SET NAMES utf8 COLLATE utf8_unicode_ci;
SELECT * 
FROM tableA A 
WHERE (A.`end_date` >= '2012-04-27T07:04:25+02:00') 
AND (A.`start_date` <= '2012-04-28T06:30:00+02:00' );
| id    | start_date          | end_date            |
| 37093 | 2012-04-28 17:50:00 | 2012-04-28 20:00:00 |
| 31003 | 2012-04-28 19:55:00 | 2012-04-28 22:00:00 |
| 43181 | 2012-04-28 20:00:00 | 2012-04-28 22:59:00 |
| 43112 | 2012-04-28 22:45:00 | 2012-04-28 23:59:00 |

So let’s try with an explicit conversion… and it works.

SET NAMES utf8 COLLATE utf8_unicode_ci;
SELECT * 
FROM tableA A 
WHERE (A.`end_date` >= TIMESTAMP('2012-04-27T07:04:25+02:00')) 
AND (A.`start_date` <= TIMESTAMP('2012-04-28T06:30:00+02:00') );
| id    | start_date          | end_date            |
| 42966 | 2012-04-27 19:50:00 | 2012-04-27 22:55:00 |
| 36883 | 2012-04-27 23:00:00 | 2012-04-27 23:50:00 |

If anyone can spot the real bug and explain it to me… I’m listening.