I've always be annoyed when I want to use a character such as » in HTML as I struggle to find the corresponding HTML Entity. This is why I made this small utility. Just paste the sexy UTF-8 character you found and it will give you the associated HTML-ready code 🙂

Enter any weird character:

I've come across an SQL issue. I need to make a fake spell for the WoW database. However creating one from scratch is too annoying, there are like 30 non-NULL values to fill. Instead what I want is to copy an existing spell with the new id. It appeared to be less trivial than expected.

Working Solution

Let's say you want to copy the spell #1000 into the spell #12345. Here is the SQL command to do it:

INSERT INTO spell
  SELECT 12345 AS id, name, icon, /* ... fill all the column names */
  FROM spell
  WHERE id = 10000;

Trying to improve ...

It is really annoying to get the list of column names (You can get it using \d spell). What we would like to do is use the wildcard * like this:

-- This is not working!
INSERT INTO spell
  SELECT *, 12345 AS id
  FROM spell
  WHERE id = 10000;

The problem is that * also adds a column named id. Therefore there are two id columns ... Problem, now it no longer fits the spell structure.

What I need to make it work is to be able to remove a column from *. Here is something I'd like to write:

-- This is not working!
INSERT INTO spell
  SELECT * \ id, 12345 AS id
  FROM spell
  WHERE id = 10000;

I tried to simulate \ with JOIN, UNION but I couldn't get anything that works. If you have any idea, I'm really interested in!

The talk is over. Check out the Slides & Video.

For several months now I've been surveying my friends and teachers at EPITA and I came to the conclusion that they have absolutly no idea what Javascript really is. In order to help them discover a language that is getting a lot of traction nowadays, I'm organizing a 2-hour presentation on the subject.

If you know how to program and are interested in learning sexy advanced Javascript, you are more than welcome to attend this presentation. It will be Tuesday 25th October from 6:30pm to 8:30pm at EPITA Amphi Master (Metro Porte d'Italie). If you are in Paris at this time and speak French, do not hesitate to send me a mail at [email protected], I will explain how to get there 🙂

I've written a more lengthy explanation about my motives and presentation's content in the LRDE bulletin L'air de rien #23:

Edito par Olivier Ricou (Enseignant-Chercheur)

[...] Ce numéro est aussi l’occasion de mettre en valeur un étudiant du LRDE un peu fou, il aime Javascript, mais fort sympathique et qui sait partager sa passion. Il le fait à travers un article ici, mais aussi le mardi 25 octobre à 18h40 dans l’amphi masters (entrée libre). [...]

Présentation Javascript

Les sites tels que Gmail, Facebook et Google Maps sont des exemples classiques d'utilisation de Javascript. Mais saviez-vous que l'interface de Windows 8 ou les extensions de Chrome et Firefox sont écrites en Javascript? Ou qu'il est possible d'écrire des serveurs web en Javascript grâce à Node.js ?

Javascript est partout et pourtant, je me suis rendu compte en parlant autour de moi que personne ne connaissait réellement ce langage. C’est pourquoi je vous invite à une présentation de deux heures sur le sujet le Mardi 25 Octobre en Amphi Master de 18h40 à 20h40.

Javascript, le language

Pour commencer, un petit peu d'histoire. Brendan Eich raconte qu'il a pensé et implémenté le premier prototype de Javascript en 10 jours en 1995. En effet, Javascript est un langage qui contient un nombre extrêmement restreint de concepts. Cette idée provient du monde des langages fonctionnels tels que Lisp, Haskell ou Caml. Le génie de Javascript c'est d'avoir su s'écarter d'un modèle mathématique parfait au profit d'un confort d'utilisation pour le développeur.

Javascript a pour objectif d'être utilisé par le plus grand nombre de personnes. La syntaxe du langage a été fortement inspirée du C et ne contient aucune fantaisie. Cela rend le code source lisible et compréhensible par n'importe quel informaticien. Le language a été conçu pour exécuter un maximum de programmes, même mal formés. Par exemple, une heuristique va rajouter des point-virgules manquant. Au final, la barrière d'entrée au Javascript est très faible.

Lambda Fonctions et Objects

Javascript tire sa puissance de deux concepts fondamentaux: les Lambda fonctions et les Objets. La présentation a pour objectif principal de vous apprendre à manipuler ces deux outils. En guise d'introduction au langage, je montrerais comment reproduire des paradigmes de programmation connus, en particulier la Programmation Orientée Objet.

Le navigateur est un environnement hostile. Dans un site cohabitent une multitude de modules Javascript développés par des personnes différentes. On peut citer le site lui-même, les publicités, les commentaires, les statistiques, le bouton "like", etc. Nous verrons brièvement l'utilité des objets et des fonctions pour se placer dans l'un des trois points de vue suivant : être un citoyen respectueux, fortifier son code contre les attaquants ou au contraire s'amuser avec le code des autres.

Un langage dynamique

A l'école nous avons principalement étudié des langages de programmation statiques comme le C, C++ et Caml. Javascript quant à lui fait parti de la catégorie des langages dynamiques comme le PHP, Ruby ou Python. Les fonctionnalités de ces derniers ont pour objectif de simplifier la vie du développeur en s'éloignant des contraintes de la machine ou des théories mathématiques de typage. De ce fait, les langages dynamiques sont de plus en plus utilisés.

Nous étudierons les changements apportés par cette nouvelle façon de penser. Par exemple, les chaînes de caractères sont utilisées de façon quasi systématique afin de faciliter le débuggage, les objets sont construits à la volée dans définir leur structure dans un fichier séparé pour gagner du temps, etc.

Qui suis-je ?

Cette présentation n'est pas le fruit du hasard. Je me suis longuement intéressé à Javascript et aux langages dynamiques durant ces dernières années.

Le traitement d'image est largement developpé en utilisant des langages statiques en raison de l'important besoin en performance. Mon sujet de recherche au LRDE est d'adapter des concepts dynamiques tels que les lambda fonctions ou chaînage de méthode aux problématiques de traitement d'image

Je travaille en parallèle des cours pour la société Curse qui réalise des sites internet pour les joueurs de jeux en ligne dont World of Warcraft. J'utilise au quotidien Javascript, Python et PHP. Mes découvertes sont mises en ligne sur un blog : http://vjeux.com/.

À Épita, j'ai pu utiliser un langage de programmation dynamique dès ma première année. Lua est intégré dans Fooo, un remake de Warcraft III, afin de permettre des interfaces de jeu facilement personnalisables.

This article is about a difference algorithm. It extracts changes from one version of an object to another. It helps storing a smaller amount of information.

Template

In a project, I have a template object with all the default settings for a widget.

var template = {
    achievement: {
        page: 0,
        column: "name",
        ascending: true,
        search: "",
        filter: [1, 2, 3]
    }
};

Alter it

Default settings are changed during the use of the application. It can happen when you load a configuration from an object:

var override = {
    achievement: {
        page: 1,
        ascending: false
    }
};
var settings = _.extend({}, template, override);

Or when the user clicks on the buttons, you have script that edits a copy of the template:

var settings = _.extend({}, template);
settings.achievement.page = 1;
settings.achievement.ascending = false;

Find the differences

Now, we'd like to store the current user configuration. We could simply dump the current settings variable but we can do better. Instead we want to dump only what has changed from the defaults. This has the benefit of being smaller to store and more resilient to changes.

In order to extract changes between the template and settings, I made a small function called difference (If you have a better name, feel free to suggest :)).

var override = difference(template, settings);
console.log(override);
 
// Result:
{
    achievement: {
        page: 1,
        ascending: false
    }
}

Instead of saving the full object, we only have to save 2 fields. This is therefore smaller 🙂 In order to get the full configuration back, we simply extend the template object with the difference:

var settings = _.extend({}, template, override);

In a way, difference is the opposite of extend.

  • settings = extend(template, override)
  • override = difference(template, settings)

How it works

Once we know what we want it to do, it is fairly straightforward to write. We traverse the template and build a new object that contains only attributes that mismatch between template and override. The following implementation makes great use of underscore (isObject, isArray and isEqual).

function difference(template, override) {
    var ret = {};
    for (var name in template) {
        if (name in override) {
            if (_.isObject(override[name]) && !_.isArray(override[name])) {
                var diff = difference(template[name], override[name]);
                if (!_.isEmpty(diff)) {
                    ret[name] = diff;
                }
            } else if (!_.isEqual(template[name], override[name])) {
                ret[name] = override[name];
            }
        }
    }
    return ret;
}

Note: Any attribute that is present only in the override object will be ignored.

Conclusion

I'm still looking forward storing as much information as possible in the hash part of the URL. Two years ago, I did SmallHash to encode integer ranges. This week, with URLON and this difference algorithm, I explored another way to look at the problem, dealing with structured objects.

It is possible to combine both approaches in order to encode structured objects that also contain integer ranges. Maybe in a next blog post!

URLON.stringify() suffer from a problem, when passed an object that contains a cycle, it will never stop. This article shows 3 techniques in order to detect if an object is cyclical.

Edit the object: Mark

In order to detect a cycle in an object, the method we learn at school is to mark each visited node. When doing a traversal, if we encounter an already marked node, then it is cyclic.

This method alters an object we don't own. It is a dangerous practice and has many side effects.

  • How do we find a unique mark key? I chose to use Math.random but it has a slight chance of giving the wrong result and removing this key from the object!
  • Adding a new key then deleting it makes the object memory size change. Therefore there are great chances of introducing memory copy and at the end of the process, memory holes because of the attribute deletion.
  • It does not work with Sealed objects and Proxies.
function isCyclic (obj) {
  var seenObjects = [];
  var mark = String(Math.random());
 
  function detect (obj) {
    if (typeof obj === 'object') {
      if (mark in obj) {
        return false;
      }
      obj[mark] = true;
      seenObjects.push(obj);
      for (var key in obj) {
        if (obj.hasOwnProperty(key) && !detect(obj[key])) {
          return false;
        }
      }
    }
    return true;
  }
 
  var result = detect(obj);
 
  for (var i = 0; i < seenObjects.length; ++i) {
    delete seenObjects[i][mark];
  }
 
  return result;
}

Keep the mark in a separate data structure

Obviously, we want to avoid editing the object, but what solutions do we have? The only one I found is keeping the visited nodes in an array. Then using indexOf, we can detect if we already visited the node.

However, this is a O(n²) process where the previous one was O(n).

function isCyclic (obj) {
  var seenObjects = [];
 
  function detect (obj) {
    if (typeof obj === 'object') {
      if (seenObjects.indexOf(obj) !== -1) {
        return true;
      }
      seenObjects.push(obj);
      for (var key in obj) {
        if (obj.hasOwnProperty(key) && detect(obj[key])) {
          return true;
        }
      }
    }
    return false;
  }
 
  return detect(obj);
}

Use native JSON.stringify

The last technique is a bit hacky. When implemented by the browser, JSON.stringify will throw an error if the object happens to be cyclic. It requires a recent browser and feels wrong.

function isCyclic (obj) {
  var isNativeJSON = typeof JSON !== 'undefined' && JSON.stringify.toString().match(/\{ \[native code\] \}$/);
  if (!isNativeJSON) {
    throw 'Native JSON.stringify is not available, can\'t use this technique.';
  }
  try {
    JSON.stringify(obj);
    return true;
  } catch (e) {
    return false;
  }
}

Conclusion

The conclusion is a bit sad, none of the techniques above are satisfying. In order to make a pure-Javascript and efficient version of cycle detection, it would require an Object hash-map, which we don't currently have.

If you are interested, the code source is on github and there's a jsperf that compares the 3 techniques.

Related Work

If you need to store and load circular structures, use Douglas Crockford decycle & retrocycle functions.