Why you should reinvent the wheel, but shouldn’t use it

Why you should reinvent the wheel, but shouldn’t use it

I am a passionate developer. I didn’t choose this path because I wanted to make big money, or create the next Unicorn. I became a developer because I love code.

I started coding early, at about twelve. This was a time were the Internet was barely emerging. the access to information was scarce, but yet there. You had to know the right words to find what you needed. Thus, at the beginning, I was “reinveting the wheel”. A lot of times. And as a developer we are often told “Don’t reinvent the wheel”.

I strongly disagree with that. I really believe that every wheel I reinvented made me a better developer. What I believe is that you should reinvent the wheel, but you shouldn’t use it in the real world.

Let me illustrate this with a skill I got when I was in college : regular expressions.
I had this project that required to parse a human-readable file to a 3D scene. This was a pet project, I wanted to build everything by myself. So I decided to write my first parser (I didn’t know that was a parser at that time). And I got stuck on a problem : how do you parse the string lexeme ? This is not a keyword, this has arbitrary length, and sometimes you use the backslash to add special chars. So I invented my own syntax and an algorithm to parse lexemes. It took me about a week to make it work properly. It was very basic, but fitted my needs.

Then a friend told me “Do you know about regular expressions ?”. Of course I didn’t. So I started my 56k modem and typed “regular expressions” on Google. What I read got deeply written in my brain. That was exactly what I was trying to do. So I obviously started using them and dropped my home brewed syntax.

The fact that I got stuck on this for a week made me understand the challenges that regular expressions were solving, and the power of its syntax and simplicity. Now, I am pretty good at writing them. I often have a colleague coming to me when he is stuck on a tricky one.

But the most important thing this experience made me understand is : to become an expert in something, you have to dig into it, to try to solve it by yourself. The outcome won’t be very valuable or even usable, but you will learn at lot of things along the way.
And when you did that, you should drop it. Because others have already solved this problem, probably better than you did. But now you can see why this is better.

You really should reinvent the wheel as many times as you can. But don’t use it on a real world project.

Show card ID in Trello using GreaseMonkey

Show card ID in Trello using GreaseMonkey

This short snippet is a simple way to show the card numbers in Trello. Useful if you use it as a bug tracker, for example.

This is a GreaseMonkey user script, but it should be compatible with Chrome as well.

// ==UserScript==
// @name        Trello Cart ID
// @namespace   *
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// @match       https://trello.com/*
// @version     1
// @grant       none
// ==/UserScript==

var update = function() {
	$('.list-card').each(function (e,item) {
		var $this = $(item);
		var $a = $this.find('a.list-card-title');
		$a.find('.card-short-id').removeClass('hide').css('font-weight',700);
	});
};

$(document).ready(function() {
  setInterval(update, 5000);
});
How to accurately detect responsive breakpoints

How to accurately detect responsive breakpoints

I recently had to detect in Javascript which responsive “state” a page was rendered. For instance, I had to detect that it was rendering the mobile phone state, which was the @media(max-width: 767px) breakpoint in CSS.

I wanted to do it with $(document).width(), but sadly, the jQuery width() method didn’t return the correct width of the screen, because it wasn’t counting the scrollbar, but CSS is.

The problem with scrollbars

The scrollbar is an OS and often theme-specific GUI element. It has not a fixed, concensual width. And unfortunately, $(document).width() does not take the scrollbar width into account.

We could use some hacks like $(document).width() + any_amount, but it would not work correctly because scrollbars don’t have the same width everywere. Some screen widths would end up in an incoherent state. See this JSFiddle for an example.

The solution : use CSS to detect the breakpoints

I found out this little hack and though it would be interesting to share. Instead of using $(document).width(), we should use the @media query somehow to get the responsive “state” of the CSS. This way, we cannot be wrong.

A simple CSS rule and a hidden div can do the trick :

<div class="responsive-state">
</div>
.responsive-state {
    display:none;
    width: 10000px;
}
@media (max-width: 767px) {
    .responsive-state {
        width: 767px;
    }
}
@media (min-width: 768px) and (max-width: 1024px) {
    .responsive-state {
        width: 1024px;
    }
}
function responsive_state()
{
    return $('.responsive-state').css('width');
}

A demo can be found here on JSFiddle.

For each responsive breakpoint, its maximum width is set as the width of .responsive-state. This way, calling responsive_state() will always return a different width for each responsive “state”. Using this value, you can detect the responsive state accurately. You don’t have incoherent state anymore.

Stronger passwords with GreaseMonkey

Stronger passwords with GreaseMonkey

Using the same password on every website is dangerous. We all know it. But we couldn’t afford to think up a different one every time : it would be impossible to remember them all. The solution I present here is a good way to reuse your “main password” (we all have one :-)) with a better security level. I also propose a GreaseMonkey Javascript code that automatize the process.


I have read some month ago a very interesting post about it, but sadly I did’t find it back. However, the idea in the article is the following : keep your main password in every site, but add “salt” based on the domain name.

Let me show you an example : let’s say that your password is ‘ilovecats’, and you want to register at www.youtube.com.

  1. Take the five first letters of the website : “youtu”,
  2. make some permutations on them – for example, make them uppercase : ‘YOUTU’,
  3. prefix it to your main password.
    The password for youtube.com becomes : ‘YOUTUilovecats’.

This idea is great ! With training, you won’t have to bother about remembering many different password. Also, you get a stronger password, since it is longer than your main password. The only thing you have to be sure is not to forget what permutations you did. Write it down somewhere maybe (this is anyway safer than writing all your passwords somewhere. If someone reads your permutations method, you don’t care : he still doesn’t know your main password ;-))

 

Going more geeky

I’m using this method since the day I learned it. But as my friends know, I’m a bit lazy : I don’t want to write my permutation every time I have to log in (beside, my permutation is quite complex to mentally process). So, I wrote a small piece of Javascript to use with GreaseMonkey. This script searches for every password field on a website, and adds the five first letters of its url, with a permutation. You can change it by yourself if you want.

The permutation used in the file is the following :

  1. Take the five first letters of the url (after the ‘www.’),
  2. add one to each letter, so that a become b, b becomes c, …, z becomes a,
  3. make the result uppercase,
  4. prefix it to your main password.

Again : don’t forget the permutation that you are using !! Remember that if you want to log in on a computer that is not your own, you will have to do the permutation by yourself !

 

Installation

  1. Firefox users : Download GreaseMonkey if you don’t have it yet : https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/
  2. Download the Javascript file here; GreaseMonkey should ask you to install the file.
  3. Once installed, every time you will click on a password field, the five first letters of your password will show up; just add your main password. Congratulations, you have a stronger password with almost no effort.

Source code

// ==UserScript==
// @name           Stronger Passwords
// @namespace      *
// @description    Get the first five chars of the domain name and prepend it to every password field of the page, with a permutation
// ==/UserScript==

window.setTimeout(function()
{
  //Extracting the first five letters
    var host = window.location.hostname;
    var domains = host.split('.');
    if (domains.length <= 2)
      host = domains[0];
    else
      host = domains[1];

    host = host.substring(0,5).toLowerCase();
  //Extraction done

  //Building the 5 first chars
  // You can change the code here to use another permutation.
  // The five letters are stored in the variable host and the
  // code below must build a variable names prefix which
  // contains the permutated string
    var prefix = "";
    var acode = 'a'.charCodeAt();
    var zcode = 'z'.charCodeAt();
    for (var i=0; i!=5;++i)
    {
      var c = host.charCodeAt(i);
      if (c >= acode && c <= zcode)
      {
        c -= acode;
        c  = (c+1)%26;
        c += acode;
      }
      prefix += String.fromCharCode(c);
    }
    prefix = prefix.toUpperCase();
  //Chars built

  //Appends the five letters to every password field when you click them
    var inputs = document.getElementsByTagName('INPUT');

    for (var i=0; i!=inputs.length; ++i)
    {
      if (inputs[i].type=="password")
      {
        var input = inputs[i];

        input.addEventListener('focus', function(event)
        {
          event.target.value=prefix;
          document.selection.empty();
        }, false);
      }
   }
 //Append done
}, 1000);
Fabric Engine, the new Flash Killer ?

Fabric Engine, the new Flash Killer ?

Everyone that has followed HTML5 a bit knows that, in term of performances, Flash is still better… But it could change.

HTML5 vs Flash
HTML5 vs Flash; source : http://themaninblue.com/writing/perspective/2010/03/22/

I deeply think that HTML5 is going to kill Flash. It’s open, it’s widely adopted by developers, and it’s totally free. Even Adobe knows that : they already stopped developing flash for mobile. The only things remaining for Flash is the speed : it is still faster than HTML5.

But the Fabric Engine may be going to change that. Technically, it is a plugin for Firefox and Chrome – maybe it will be released for Opera, but I doubt that it will for IE – that literally compiles JavaScript code to make it run faster. This is open source – Flash is not – easy to install, and multi-thread.

Fabric Engine
Fabric Engine
For now, it is only in beta testing, I suscribed to the beta testing group. I didn’t try it yet, but I looked at the demos and I think this has great potential.
I highly encourage every Web developer to take a look at this plugin.

Sources :

Large Scale Javascript Architecture

Large Scale Javascript Architecture

[slideshare id=10198269&doc=jquerysummitshare-111117040722-phpapp02]

Developers creating JavaScript applications these days usually use a combination of MVC, modules, widgets and plugins for their architecture. They also use a DOM manipulation library like jQuery.

Whilst this works great for apps that are built at a smaller-scale, what happens when your project really starts to grow?

In his talk, Addy Osmani present an effective set of design patterns for large-scale JavaScript (and jQuery) application architecture that have previously been used at both AOL and Yahoo amongst others.

You’ll learn how to keep your application logic truly decoupled, build modules that can exist on their own or be dropped into other projects and future-proof your code in case you need to switch to a different DOM library in the future.

Source : Addy Osmani’s Blog

CSS3 easier properties writing

CSS3 easier properties writing

CSS3’s new features are really nice. But unfortunately, all the browsers don’t support everything (in fact, no browser support it entirely), but they provide vendor-dependent properties that allow to use it. So to use them, you need to duplicate your code, with all the problems that it can bring. I present you here a solution to write less CSS for the same result, without having to take care of vendor-specific options.

Vendor-specific properties are a pain in the ass !

Let’s say that you want to use a new property in CSS3. For this example, we will use border-image. According to W3Schools, you simply cannot use it in IE (duh !). In Firefox, Chrome and Opera, you have to use vendor specific rules to make this property work. So you need to write :

div
{
border-image:url(border.png) 30 30 round;
-moz-border-image:url(border.png) 30 30 round; /* Firefox */
-webkit-border-image:url(border.png) 30 30 round; /* Safari and Chrome */
-o-border-image:url(border.png) 30 30 round; /* Opera */
}

(example taken from http://www.w3schools.com/css3/css3_borders.asp)

Okay, this works. But you wrote four lines to get only one effect. And if you want to change this property, you will have change it four times instead of only once. Your code become harder to read and longer, for so few. And I don’t even talk about misspelling or different behavior because the -webkit property is different from the -moz property, but you didn’t notice it !

Well, you got my point, this is pain in the ass.

Couldn’t we get rid of it ?

In fact, yes, you can. The good news about those vendor-specific properties is that they have the same syntax as CSS3, with just a prefix that is different for each browser (-moz-, -o-, -webkit-, -ms-…). All you need to do is to duplicate the rule for each vendor-specific prefix, just like in the code above. And a simple parser should be able to do that for you.

I already wrote it, so you don’t even have to create your own (aren’t I kind ? :-)). It is working nicely (in fact, this blog uses it right now), so you shouldn’t have problem with it. That said, if  you find an error, some properties that are missing or shouldn’t be converted, let me know !

Also, I’m working on a system that takes a CSS file, convert it and saves it in a cache, so that you can use it directly in your website without going through this page. If you change your CSS, the system detects it and recompile the converted version for you. I will probably publish the system before Christmas, so stay tuned !

A PHP Command-line interface parser

A PHP Command-line interface parser

Today, I decided to build a simple, but highly parametrable script that takes a bunch of images and resizes them with a given method. My first problem was : how to make a good command line arguments parser, so that I don’t have to write each argument in a specific order, or not putting some arguments at all, using a default value…
In bash, this is quite simple, but I wanted to use PHP for the script, so that I could use the GD library that I know well.

Then I found this class, made by Diego Feitosa, that looked nice, but wasn’t exactly what I wanted : I was forced to use an option (i.e. “-something <param>”) for each argument in the command line. It is nice for defining the behaviour of the script, but if you want to script something that process files, you just can’t – or only one file at a time.

In fact, this is exactly what I was doing : processing a lot of files. But with this parser, I couldn’t. So I decided to hack it a bit…

This code is an extended version of the CLI Parser of Diego Feitosa, which allows the user to pass arguments that are not options. I also made other modifications to the script :

  • added a method to check if an argument is valid as a non option (by default, everything that doesn’t start with ‘-‘ can be a non-option)
  • improved usage description : the type awaited by an option is shown, better indentation
  • improved error messages : if the type in the command line doesn’t match with an option, the error is shown. In the version of Diego, only the usage message was shown.
  • auto-inclusion of the option types
  • new option types : Positive Numeric, Negative Numeric, Integers, Enum

You can find the code here.

Here is an example of the usage of this parser. This example is also located in the source code provided above :

require_once('CliParser.inc');
$clistring = new CliTokenString("-c");
$clistring->setDescription("It requires a string");

$clihelp = new CliTokenBoolean("--help");
$clihelp->setDescription("Token that shows a help message");

$clisingleton = new CliTokenBoolean("-e");
$clisingleton->setDescription("It don't require any value. The existence of this argument is enough");

$clibool = new CliTokenBoolean("-b");
$clibool->setDescription("Boolean token");

$clidir = new CliTokenDirectory("-d");
$clidir->setDescription("This token require a directory path as argument. If the argument isn't a directory path, an error message will appear.");

$clifile = new CliTokenDirectory("-f");
$clifile->setDescription("This token require a file path as argument. If the argument isn't a file path, an error message will appear.");

$cliint = new CliTokenInteger("-i");
$cliint->setDescription("This token require an integer path as argument. If the argument isn't an integer, an error message will appear.");

$clienum = new CliTokenEnum("-enum", array('the', 'different', 'values', 'accepted'));
$clienum->setDescription("This token requires its argument to be one of the values specified");

class MyCliParser extends CliParser
{
  public function getHelpMessage()
  {
    global $argv;
    echo sprintf("Usage: %s [options] <file(s)>\nOptions :\n", $argv[0]);
    $this->getDescriptions();
    echo "\n";
    exit;
  }
}

//Building the parser and parsing the arguments
$cli = new MyCliParser($_SERVER["argv"]);
$cli->register($clihelp, false); // false because it not require an argument
$cli->register($clistring);
$cli->register($clisingleton, false); // false because it not require an argument
$cli->register($clibool);
$cli->register($clidir);
$cli->register($clifile);
$cli->register($cliint);
$cli->register($clienum);
$cli->parse();

//Showing the help message if asked
if ($clihelp->getValue())
{
  $cli->getHelpMessage();
  exit;
}

//Showing the options
var_dump($clistring->getValue());
var_dump($clisingleton->getValue());
var_dump($clibool->getValue());
var_dump($clidir->getValue());
var_dump($clifile->getValue());
var_dump($cliint->getValue());

//Showing the non options
var_dump($cli->getNonOptions());

/* Some commands :
php example.php --help
=> will show the help message

php example.php -c foo
=> the $clistring token will be set

php example.php -e -c foo
=> the $clisingleton token will be set

php example.php nonoption1 -i 42
=> one non-option argument : nonoption1

php example.php -i 42 nonoption1
=> same thing, different order

php example.php -i 42.5
=> shows an error : 42.5 is not an integer
*/
Finaly online !

Finaly online !

It’s been a while since I wanted to make my own website, but with my studies and my other projects, I never had enough time… Until today :-)

My own website about me, my projects in finaly online ! It is still simple, but I hope I will make it grow as soon as possible.