Monday, 31 December 2012

The Course of History

I guess it's not easy to be fully aware of how fast things have been changing in the last 150 years. Since the times of the Industrial Revolution changes of all sorts have been occurring faster and faster every year. The growth of the megacities, the development of technologies that heal and technologies that kill, ideologies that free and ideologies that oppress, ways to communicate and ways to isolate... I'm not going to talk about transistor's size, storage Terabytes or bandwidth Gigabits... most people with a certain interest in technology are relatively aware of those changes... on the contrary, people with an interest in history and politics are not that fully aware (at least that was my case) of some of the U-turns that the political map has experienced in the last century.

Two weeks ago I was lucky enough to spend a few days in Lisbon, and I did not feel surprised to come across with tons of political posters and political slogans painted all over the city. The country's economy has partially collapsed since the start of the economical crisis, forcing the government to ask for a bailout in 2011. Social spending has undergone deep cuts, and unemployment has risen sharply (well, 15% sounds almost like a joke to someone living in Asturies, where we are at an astonishing 25%...). So, the people are utterly suffering this fucking crisis, and this is expressed on the walls, mainly near the University Campus. I could see tons of slogans against the cuts, the Troika (IMF, EC, ECB), the Banks... but among them there was one that deeply caught my attention:

It reads: "Death to French-German Imperialism"

If you know a little bit of European history and read that slogan twice you should be shocked to the bone. I'm not going elaborate here as to whether the 2 European powerhouses are planning to dominate the rest of Europe (though indeed, as someone living in a Southern European shit country whose corrupt politicians have been wasting enormous amounts of money given to us by Northern European countries... I would probably appreciate some kind of external control over our kleptomaniac politicians).
What I want to say here is that this idea of a French-German "imperialism", alliance, or whatever you want to call it... has some really beautiful components, let me explain:

For centuries the whole soil of this continent has been soaked in the blood of its citizens. Stupid wars orchestrated by the same usual suspects: kings, politicians and priests.
It would not be easy to choose 2 European countries that in one way or another have never been in conflict, but it's easy to select France and Germany as 2 of the countries that more wars have waged against each other:
the Napoleonic wars, the Franco Prussian Wars, WWI, WWII...
Look at Alsace and Lorraine and think how many times it has shifted from one flag to another.
And also, think how after the WWII the French intended to blow Berlin's Victory Column as it commemorates (among others) the Prussian victory over France. Hopefully, the English stopped them from committing such an act of vandalism (I wonder if they would also consider blowing the monument in VictoriaPark)

So, after so much blood spill, the idea of a French-German bloc, sounds more like an achievement than like a tragedy. It helps you to realize what a long way we have gone since the end of the WWII to get to this Europe that we have now. For someone like me, with such a deep feeling (and why not to say it, pride) of being European, the current pseudo Europen state is not enough, and sure I'd like to see a real European State, a union of old different nations which common culture leads them to a common welfare state, common laws, common rights and common duties. We're far from that, and with the dismantling of the welfare state that we're undergoing right now and the rise of euroscepticism, it sadly seems to be moving away instead of getting closer... but if we look at the almost 70 years of peace inside our borders or the weakening of those internal borders granting us free transit... we should still cherish some hope.

This reminds me of the nice feeling that I had in summer 2010 when freely crossing the modern pedestrian bridge that joins Strasburg (France since the end of the WWII) and Keil (Germany). An Asturian freely walking from France to Germany and from Germany to France, no borders, no passports, no mistrust... that's the way to go if Europe, and all the values that I think it stands for, want to survive.

Wednesday, 26 December 2012

One more JavaScript quirk

The other day, while happily adding one gist to my github gists, I stumpled upon something that had me stuck for a while. Indeed, it's not a JavaScript quirk, but either a Base Library quirk, or a lack of documentation reading on my side, or a combination of both... so the thing is that I thought I would share it here.

Long in short, be careful when using Array.concat with the arguments object, cause you could be expecting a different behaviour. By the way, I already talked about arguments here

Let's say you want to create a new array consisting of the elements in another array a1, and the arguments to that function... well, if you are used to .Net's Concat (and don't take into account that arguments is an "array like object", not a real array) you could end up with this wrong code:

function wrongTest(x, y){
var a1 = ["Xixon", "Berlin"];
 return a1.concat(arguments);
console.log(wrongTest("Prague", "Budapest").join(", "));

The code above won't print:
Xixón, Berlín, Prague, Budapest
Xixón, Berlín, [object Arguments]

So, what's happening here?
As you can see by reading the documentation

concat creates a new array consisting of the elements in the this object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).

concat is a rather flexible beast, as it accepts as parameters much more than an obvious array. In our case, as I already said, arguments is not a real array... it just has a length property and allows indexed access, which is usually enough to allow us using on it the Array.prototype functions, but in this case, I guess concat is doing internally an instanceOf Array check, which obviously is not passed, and then is treated just as a plain object, concatenating the object itself instead of its elements.

This means you should rewrite the above code like this:

function correctTest(x, y){
 var a1 = ["Xixon", "Berlin"];
 return a1.concat(, 0));
console.log(correctTest("Prague", "Budapest").join(", "));

Notice how we can leverage the array functions on arguments by means of the delegation mechanism provided by call. We're using slice here to obtain a real array with all the items in arguments.

You can verify that I'm not lying by running this code

Saturday, 22 December 2012

safeGet, safeSet and nameSpace in JavaScript

Some weeks ago I wrote a post praising Groovy's safe dereferencing operator (?.) and showed some code to achieve similar functionality in C#. Sometime ago I also mentioned a very cool application of C#'s dynamic, the Elastic Object. Elastic Object shows how powerful it is to be able to hook our code in the method or property look up process. All this power is brought to us in C#'s dynamic via TryGetMember, TryInvokeMember, or in Groovy by invokeMethod and getProperty. Related to this (it's a subset indeed) having a hook for when a method or property are missing is also pretty useful stuff, and is something that we can achieve in Groovy with MethodMissing and PropertyMissing.

With JavaScript being my other all times favourite language, the obvious question that springs up is:
can I do something similar in JavaScript?

Long in short, the answer is No. Unfortunately JavaScript (at least EcmaScript 5) does not boast something that powerful as the aforementioned invokeMethod, TryInvokeMember... I think the proxies to be introduced in ES6 are a step on that direction, though I'm not sure how far (honestly, I haven't had time to dig deep into them).
Right now you can get part of the functionality, but not all of it:

  • As explained in this previous article we can leverage JavaScript accessor properties, functions as objects, closures and so on to intercept the access to any existing property or invokation of any existing method.
  • Firefox provides the non standard __noSuchMethod__ hook to trap invokations of non existing methods

So, this leaves us with some missing pieces:
intercepting access to missing properties, intercepting invokations of missing methods (except in Firefox)...
One additional miss is that though we could use something like my intercept.js library to add interceptors to all the existing methods and properties in an object in a given moment, if later on the object is expanded with new methods/properties, those ones will be lacking the interceptor, and there's no way to be notified when an object is expanded (we just can seal it to prevent it from being expanded...

Well, after all this digression, back to what prompted this post:

As for Groovy's Safe Dereferencing operator, I've written a safeGet function that receives an Object and a string with a list of properties (yes, it's a way of chaining several property safe accesses). If we can reach the last property in the chain, it's returned, otherwise we get undefined.

function safeGet(obj, propertiesStr){
 if (!obj || !propertiesStr)
  return undefined;
 var properties = propertiesStr.split(".");
 var curObj = obj;
 while(curObj && properties.length){
  var curProp = properties.shift();
  curObj = curObj[curProp];
 return curObj;

var person = {
  name: "xuan",
  country: {
   name: "Asturies",
   capital: {
    name: "Uviéu",
    population: 1100000

 //this code is ugly...
 if ( && &&
 console.log("the capital of my country is: " + safeGet(person, ""));
 console.log("the population of my country is: " + safeGet(person, "country.population"));

Regarding the "Elastic Object", I've created a safeSet function, which likewise, receives an object, a string with a list of properties, and a value, and sets the last property to that value. For any missing property in the chain, the function creates an empty Object, where the following property will get added...

function safeSet(obj, propertiesStr, value){
 if (!obj || !propertiesStr)
 var properties = propertiesStr.split(".");
 var curObj = obj;
 for (var i=0; i≶properties.length-1; i++){
  if (!curObj[properties[i]]){
   curObj[properties[i]] = {};
  curObj = curObj[properties[i]];
 curObj[properties[i]] = value;

var p = {};
 //this code is ugly... = || {}; = || {}; = "Uviéu";
 safeSet(p, "", "Uviéu");
 console.log("the capital of my country is: " +;

 safeSet(p, "", "Berlín");
 console.log("the capital of my country is: " +;

I've used both functions to write my own nameSpace function (bear in mind that this is mainly useful for the browser, in environments implementing the CommonJS module system (like node), namespaces don't seem much necessary).

var nameSpace = (function _nameSpaceFactory(){
 var root;
 if (typeof window == "object"){
  root = window;
//well GLOBAL works only at the module level, and in node with the CommonJS module system, all this namespacing thing is not really necessary 
else if (isNode()){
  root = GLOBAL;
  console.log("we don't know the global object for this environment, namespace function won't work");
 return function _nameSpace(nameSpaceStr){
  if (!safeGet(root, nameSpaceStr))
   safeSet(root, nameSpaceStr, {});

 //creates the namespace
 org.deployToNenyures.base.version = "0.0.1";
 //namespace already exists, so does nothing
Update, 2013/01/27
You can find the source here and test it either with a modern browser here or with node here

Groovy's safe reference (or safe navigation) also works with method invocation, returning null if the method does not exist, it makes sense to me, so I've added a safeInvoke function that in line with my other functions will return undefined if such method does not exist.
I've also decided to upload it to my GitHub account.

Tuesday, 11 December 2012

Wev Development MashUp

In the last weeks I've been reading about a good bunch of interesting Web Development topics, so I think I'll put up here a list of links and some comments

First and foremost, some JavaScript fun. Years ago, when I first discovered prototype.js, I had a real great time thinking about how some of the functionality was coded and reading through the source code. I've had a similar or even better feeling when reading this nicely laid out version of underscore.js source code. It's one really worth learning experience. The chaining-wrapped objects thing is pretty interesting, and you come across with pretty interesting code fragments like this:

  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
bear in mind that the "this instanceof _" comparison is used to check whether _ has been invoked as a function or as a constructor.

Another thought-provoking javascript snippet that I've found recently is this one:

var toStr = Object.prototype.toString );
toStr([]) // [object Array]​​​​​​​​​​​​​​​​​​​​​​​​​​​
Think that the result, is just like this quite simpler to understand code: param )

I'm not sure how I ran into this excellent presentation about advanced jQuery stuff.

This article in InfoQ about how to speed up Web Applications has been a nice finding. Going further on the topics mentioned there, I also came across this guide.

Performance on the client side leads us to another interesting topic, Repainting and Reflow. This is one of the best articles on the topic that I've could find. One of the main rules to minimize reflows is avoid creating and appending DOM elements in a loop. In those cases we should append the elements to a "root" Node that has not been appended to the DOM yet, and then append the "root" node when all the children nodes have been appended to it. Sometimes we don't have a new root node, cause we want to append the new nodes to an already existing node (think of adding several li's to an existing ul). For cases like this, Document Fragments come really handy.

In my last toy project, I've found myself using CSS classes like "editBt", "saveBt" in order to identify elements in a html structure and bind javascript behaviour to them (these html were sort of templates/widgets, I would have multiple instances of them on the same page, so that's why I couldn't use an ID to identify them). I was not feeling much comfortable using CSS classes for this, so looking around the web I found several articles [1], [2] proposing an interesting alternative, data-attributes. It makes pretty good sense to me, we should use css classes only for presentation (layout and theme), not for semantics, and using them to identify the element as a "Save Button" is quite more on the semantic side. This said, one could think that data attributes should be a better way to implement microformats than CSS classes. The answer is No, as the HTML specification says custom data attributes are only to be used privately (privately in the sense of the current application) and microformats are devised for external use.
If you want to stick to css classes rather than using data attributes, the idea proposed here looks quite good to me, name those classes with a "js-" prefix, to make it clear that they have nothing to do with presentation and are being used just as javascript hooks.

That interesting article that I've just mentioned, takes us to another related topic about which I've been pondering lately, how we should better name our CSS classes. It should be obvious to anyone that using class names like "blueText" is clearly not the way to go, and we should use something that not so openly states the style being applied. However, it can be confusing to decide how semantic our CSS class names should be. The W3C and the html5 spec

but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.

encourage us to use semantic names. Well, the article makes some great points against going too far with that, and I can agree in most of them. If you want to create CSS classes to be reused in multiple projects, you should not taint them with content information that is specific to one particular project.
Furthermore, my view is that as we use CSS classes for structure and layout, its semantics should be based on that, on presentation, and not on the content of the elements to which they'll be applied. I think this sentence in the jQuery UI documentation stands on this side:

The jQuery UI CSS Framework provide semantic presentation classes to indicate...

Let's look at some of the names used for jQuery UI CSS classes:
ui-widget-header, ui-widget-content...
well, these names are semantic in term of presentation, they are telling us that an element is a header or the associated content, but is not telling us what goes inside. We could store there a piece of news, or a book review or whatever... so we're not tied to specific contents.

Update, 2013/03/03: This post seems quite aligned with what I claim above

If a class name is used to describe the content, that class can only be used where that content exists, but when a class name describes a visual pattern, it can be used in many more places. The more abstract the visual pattern, the more reusable the class.

Thursday, 6 December 2012

FIC Xixón 2012

Well, before I grabbed the program for this year's festival I felt rather negative and unmotivated to this edition. I was pretty angry with the very odd decision taken early this year to lay off the director, Jose Luis Cienfuegos, the man that transformed this festival from a provincial event into one of the most respected (among its kind) festivals in Europe. The thing is that after leafing the programme, my suspicions started to banish, as I could feel the selection of films seemed excellent, much more diverse (and more in my line) that in previous editions. I'd like to particularly praise the inclusion of a small section dedicated to the New French Extremity (ok, yes, it would have been more "revolutionary" if it had been done 3 years ago, now I have to admit it's not really unveiling anything too new) and the excellent "Géneros Mutantes" section.

So, without further ado, here it goes the list of films (it was 10 this year) for which I could make it to the showing:

  • Después de Lucía, by Michel Franco, Mexico, Esbilla section (Saturday 2012/11/17) I may sound like a grumpy old man, but I have quite a disdain for nowadays teenagers. Not that I think that my generation was nothing too especial, but current generation looks in a high percentage like a bunch of idiotic, selfish, egocentric, brainless, unfocused fuckers that don't give a shit about anything but their own pleasures, with a willingness to fulfill their desires by all means. So, this film is about how a bunch of middle class Mexican teenagers bully . The film has some really cruel moments, a cruelty that is born from the realization that what the main character is suffering could be happening to many other kids right now. I would say it's pretty good in conveying (same as Miss Bala did in last year's edition) the terrible violence inherent to Mexican society.
  • Masks, by Andreas Marschall, Germany, Géneros Mutantes section (Saturday 2012/11/17) The review in the Festival hand program was not much descriptive, but hopefully this trailer made it clear to me that it could be a pretty interesting work. Well, it didn't cheat me, "Masks" is an impressive terror/thriller film, with a rather original plot that unfolds with intensity over 112 minutes. It has elements that deeply remind me of Dario Argento, and in particular of Suspiria (the astonishing, hypnotic soundtrack clearly plays its part in creating this link) and maybe also some elements of the "French extreme thing". I won't say more, just rent, download or whatever is your thing.
  • Livide, by Julien Maury and Alexandre Bustillo, France, Géneros Mutantes section (Sunday 2012/11/18) The film is directed by the guys behind L'Interieur so it was a must see proposal for me. The setting, an old mansion in a coastal village in Bretagne is really promising, but the development is nothing too special. The plot seems like too fantastic to me, and it reminds me of all the boring modern USA horror films. However, the aesthetics, though in that same line, are really good, and make the film worth seeing.
  • Seven Acts of Mercy, by Gianluca De Serio and Massimiliano De Serio, Italy, Esbilla Section (Monday 2012/11/19). The film is as enigmatic as its title. Nothing is explained about how the immigrant tough girl (as the film unfolds we find that she's Moldovan) got to Turin, why that dirty gipsy family is exploiting her and what she's planning. The same goes for the other main character, the old Italian man. Mixing the lives of both mysterious beings shows to be a good choice to portrait the pain and difficulties of human existence.
  • Children of Sarajevo, by Aida Begic, Bosnia/Germany/France/Turkey, Official Section (Tuesday 2012/11/20). I saw the title in my first glance at the program and I immediately checked it as a must see. I've got sort of an obsession with the Balkan Wars, it's been the last large tragedy in that almost continuous war between brothers that has been the history of Europe, it was so nearby and so far away at the same time... and it's made me thought so many times how my life would have been if I had been born just the same day, but in Sarajevo or Belgrade instead of in peaceful, boring Xixón...
    I was certainly right, this is a beautiful film. It tells us a story of survival in a city and country that try to hold tightly to that threat from which they still hang. A personal story that is wisely used to slap our faces with harsh fragments of the social mess in a postwar land: mafia politicians, a war torn economy being finished off now by privatizations, the barriers between those that lived the horror of the siege and those who somehow didn't, the different attitudes towards religion, identity and recent history... These barriers are masterly presented to us in the shape of an item intended for celebration, firecrackers. Our main character (by the way, her performance is outstanding), a young "born again Muslim" woman who lived the horrors of the war is terrified by the firecrackers with which others happily celebrate the New Year, for her those bursts just bring memories of war and suffering. This film has made me feel like watching again that other extraordinary portrait of that same broken land, Grbavica
  • Shadow Dancer, by James Marsh, UK/Ireland, Official Section (Wednesday 2012/11/21). An excellent fictional story set in the 90's, in the middle of the bloody Irish conflict. A catholic/republican family broken by the painful conflict serves to help us understand how torn apart that whole land was. The story is quite hard as it touches difficult topics like loyalty, trust, revenge... with a rather unexpected outcome. The film made me ask me and ponder over a few things, made me question some of my assumptions, and that's always I deeply appreciate. However much I support people's struggle to decide what state they want to belong to, when that struggle causes so much pain, and the control exerted by the "occupiers" is not that oppressive, is that struggle really worth? Hopefully, the 2 last armed struggles for independence in our continent seem to have come to an end. In the Basque case, I really think maybe in 20 years we'll be welcoming a new state to a "United States of Europe" (well, I'm day dreaming a bit), in the Irish case I guess it's quite more complicated as the population is so terribly divided... well, time will tell...
  • Bathory, by Juraj Jakubisko, Slovakia, Czech Republic, Hungary, UK (Thursday 2012/11/22) This is the most expensive Czechoslovak film to date (hey, sure I know Czechoslovakia is just a faded memory of the cold war... but the film is a Czech and Slovak production, so it's cool to unearth that historical term :-) and the visuals are beautifully well done. It tells the alternative story (that now seems to be much more accurate than the myth of the blood thirsty duchess) of Elisabeth Bathory, where she ends up being a victim rather than a monster. An interesting depiction of a time of where art, lust, cruelty, religion, illiteracy and beauty danced together while Eastern Europeans died in battle against the Ottoman invaders to guarantee the future of our beloved Europe. It's well worth the 150 minutes that I spent in front of the screen.
  • Inheritance, by Hiam Abbass, France, Israel, Turkey, Official Section (Friday, 2012/11/23) I didn't have this film in my list of "must see" films, but it turned up to be an excellent choice, and very appropriate considering that this week war has been raging again in that condemned corner of our planet called Israel, Palestine or whatever. The life of a Palestinian family is used to show us both the many difficulties of living in such a contested territory, and the problems inherent to any Muslim family where some of its members are breaking away from the chains and restrictions imposed by Islam and tradition. In that sense, it can remind us of some films by Fatih Akin (sure Arabs and Turks are different human groups, but both peoples need to struggle to get rid of similar oppressive cultural traits).
  • Le fils de l'autre, Lorraine Levy, France, Enfants Terribles section (Saturday, 2012/11/24) This exceptional film deserves a longer separate review.
  • Our Children, by Joachim Lafosse, Belgium, Luxemburg, France, Switzerland, Esbilla (2012/11/24). Not much to say, entertaining enough for not making you feel like leaving the screening, but fails in achieving anything more creditable. After having watched and felt several really harsh and dramatic stories over the previous days, the supposed drama the main character seems to be going through seems pretty light, indeed, rather than feeling any empathy for her, I had more of a sort of "idiot, wake up, it's all your fault" feeling. I have to admit though, that the brutal end of the story will manage to remember an otherwise quite unremarkable film.

As usual, there's a good bunch of films for which I couldn't make it to the projections, but that seemed pretty interesting (so I'll have to resort to bittorrent with the hope of them showing up there), these are some of them:

Not sure if in order to celebrate the 50th anniversary of the Festival, or because of new ideas from the new guys in charge, or maybe both, there was a nice and simple exhibition on the promenade that leads to the main theatre in town: posters advertising some of the films in this edition, and huge "stickers" on the floor listing the winners of previous editions of the Festival. I rarely pay any attention to the decisions of the jury, as I assume my tastes will have little to do with those of the smart, educated folks that make up the jury, so I was rather surprised (and delighted) to see that one of my all times favourite films, Liljia 4-ever was the winner of the 2002 edition (at that time I was scarcely interested in the festival).

As a negative note, I'm compelled to voice here that during the first days of the festival, the small paper handed out for free was missing the regular section in Asturian Language. Hopefully this outrageous mistake was rectified on the following days.

Finally, I can't conclude this post without giving my overall verdict:
this has been excellent edition (for me, the most excellent so far) of a festival that for a few days manages to bring something interesting to this lost corner of a second class European state, helping us to escape from the 25% unemployment rate, the social cuts, the gratuitous beatings of "rebellious" citizens by the riot police... and so many other miseries of our crumbling capitalist societies...

Friday, 30 November 2012

prototype, [[Prototype]], inheritance chains, contructors...

The JS101 section in dailyjs is always worth a reading. However much I think I know something I always find here some nuance on the subject at hand that I hadn't realized of and makes me mull over it. Reading their entry about prototypes was not different.

Prototypes were a confusing matter for me for a long time. While the idea of a prototype chain to look for methods and properties is simple, powerful and beautiful, it took me time to realize that the prototype chain (inheritance chain) is based on the [[Prototype]] property (accessible in many environments through the non standard __proto__ property), and that the prototype property that we find only in Function objects, is not part of that chain (but is used for setting it up...) Bear in mind then, that functions have both a prototype (pointing to an object which constructor property points back to the function) and a [[Prototype]] that sets their "inheritance chain". This prototype chain for functions contains two Objects: Function.prototype and Object.prototype.
(function(){}).__proto__.__proto__ === Object.prototype;
I like the name they use in the article for referring to [[Prototype]]: internal prototype, to distinguish it from prototype.

As I said, __proto__ is not standard, but if we want to get hold of the [[Prototype]] object, we can do it using ES5's Object.getPrototypeOf

One very important point is that Object.prototype.__proto__ is null, that's the way the interpreter can find the end of the prototype chain. This used to be the only object without a prototype chain, but with the advent of Object.create(), we're now allowed to create other objects with their [[Prototype]] set to null. I already mentioned an odd JS behavior related to this in this previous post

There's one interesting point mentioned in the daily.js article when they talk about Object.create as the only way to obtain an object without a prototype chain (that is, [[Prototype]] points to null). We could think of achieving the same by setting the constructorFunction.prototype to null, but contrary to what we could expect, that does not give us a null [[Prototype]] when creating an instance, but makes it point to Object.prototype. I guess it's one of those corner cases explained somewhere in the ECMAScript reference

To make sure we understand how prototype and [[Prototype]] work, we can do some checks like these (all of them are true):

given: function f1(){};
  • f1.prototype.__proto__ === Object.prototype;
    (the prototype of a function is just a normal object, so it's __proto__ is Object.prototype)
  • Function.prototype.__proto__ === Object.prototype;
  • f1.__proto__ === Function.prototype;
    (notice that functions are instances of Function)

Anyway, there are some cases that can't be inferred, and work that way just cause the standard says so, these are some of them:

  • Function is an odd object, it's an instance of Object, but does get its __proto__set to an empty function, so:
    Function.__proto__ === Object.prototype; is false
    Moreover, I found somewhere this interesting additional info:
    Function.prototype is a function, that returns always undefined and can accept any number of arguments, but why?. Maybe just for consistency, every built-in constructor's prototype is like that, Number.prototype is a Number object, Array.prototype is an Array object, RegExp.prototype is a RegExp object, and so on...
  • Indeed, we should not care much about Object.__proto__ and Function.__proto__, as I can't think of them being used in any inheritance chain
This question in SO has additional interesting notes about the above.

Talking about prototype chains, we should mention the instanceof operator:
ob instanceof MyFunction;
that checks if the given constructor function is in the the prototype chain of the given object (by walking up the prototype chain and comparing the objects it finds with MyFunction.prototype). We can achieve just the same by using Object.isPrototypeOf. We would write:

The best way to complete this post is to add this extraordinary diagram that so perfectly explains all this and that I found here

and to summarize below (also taken from there) what happens when an object is created by a call to a constructor (i.e. var f = new Foo();)

The interpreter creates a new, blank object.
The interpreter sets the new object's underlying prototype to be Foo.prototype.
The interpreter calls Foo in a way that makes this refer to the new object.
When Foo completes, if Foo doesn't return a value (or doesn't return an object), the result of the new expression is the object created in step 1. (If Foo returns an object, that object is used instead; that's an advanced thing most people don't have to do.)

Sunday, 25 November 2012

Le fils de l'autre / The other son

As usual I'm preparing a review for this year's edition of FIC Xixón, but this exceptional film deserves its own separate review. Le fils de l'autre (The other son) by Lorraine Levi is a profoundly human story, a touching and questioning work dealing with such serious topics as our feeling of identity and belonging to a family, a religion, an ethnic group...

Imagine you're an 18 years Israeli guy that suddenly finds out (along with his family) that due to a mistake in the hospital where he was born he got shifted with a Palestinian Arab newborn. This would be shocking enough in any other society, but when in happens in a fucked up place where both families are supposed to hate each other (the invaders that thew us away from our land vs the ones that send suicide bombers to our cafes) it turns into an astonishing exercise of re-evaluation of oneself and everything around. The idea is brilliant, as it is the way it rolls out to show us the lives and the perceptions of "the other" on both sides of the Wall. The selection of the phenotypes of the characters is excellent, tearing apart any ideas of "racial differentiation" between both peoples. The Israeli father (an Israel army colonel) looks almost like an Arab (dark eyes and dark skinned, not the kind of Ashkenazim Jew which ancestors intermixed with central Europeans and that now would look more like a German than like someone with roots in the Middle East), while the Palestinian father is a clear eyed Arab. The film is also pretty good in showing the revolting racist ideal that in a way seems to underlie Judaism (sort of Jus sanguinis applied to ethnicity and religion). The Israeli guy, though having been brought up as a Jew (circumcised, has studied the Torah in depth...) for 18 years, is not a Jew now, cause he has no "Jew blood", and he will have to go through a complicated process of conversion... On the other side, his Palestinian counterpart is now a Jew, that should have all the rights that it involves in the state of Israel. This idea of a religion "for the chosen ones" should be in stark contrast with Islam, that seems like a religion for everyone (apparently this sounds pretty good, but also think than that's why radical Muslims try to force their insane beliefs upon everyone). This said, I'm quite a bit surprised with the reaction of the brother of the Palestinian guy, who at first vehemently rejects him as "one of the others" (I guess Islam says that if he has grown up as a Muslim, he should be considered a Muslim, regardless of his parents' beliefs).

The reactions of the different members of both families are really instructive:
Both mothers react likewise, though deeply in pain, they quickly seem to accept the situation, on the one side, now they have a new son to worry about and to feel proud of, on the other side, nothing has changed with regards to the other son: genes or 9 months in your womb are nothing when compared to 18 years of shared love. From the first moment a feeling of confidence springs up and will help them to assimilate and deal with this new situation.
For both parents it's a bit more difficult, a soldier defending Israel from "the others" versus an engineer that has to work as a mechanic cause there are no engineering jobs in the West Bank because of "the others"... 2 men for which the conflict has had more personal implications, their whole lives, their professions... have been shaped by these borders. First they get engaged in a discussion about stolen lands and suicide bombers... then the gap seems to narrow, but it's still very difficult to find words to share.
I love the attitude of the 2 little girls in both families, these young creatures still not poisoned by this never ending conflict react happily saying "now I have a new brother" and playing together with their barbies.
As for the main characters of this drama, after the initial deep shock, both guys strive to handle this crazy situation and manage to establish a strong relation, not only between them but also with their new families (and even with their new cultures).

I could keep writing paragraphs praising this masterpiece for a good while, but I think it's enough to prompt you to watch it at the first chance you get

Sunday, 18 November 2012

Switch between Tabs and Accordion

Working with jQuery UI sometimes I've hesitated between using an accordion widget or a tabs widget to lay out some data. In both cases the information to be displayed consists of headers and contents, so though the html tags expected by jquery UI to create tabs or accordions are different, it should be pretty simple to switch from one to another.

The idea is to have an object holding a reference to a container DOM element and to a list of headers/contents items, and exposing 2 methods, one for creating a Tab and one for creating an Accordion. You'll use it like this:

var books = [
  name: "First Book",
  text: "

this is the first

" + "
  • aa
  • bb
" }, { name: "Second Book", text: "this is the second" }, { name: "Third Book", text: "this is the third" }, ]; $(document).ready(function(){ var myTabsAccordion = new animatedTabsAccordion("#booksContainer", books); $("#accordionBt").click(function(){ myTabsAccordion.generateAccordion(); }); $("#tabsBt").click(function(){ myTabsAccordion.generateTabs(); }); });

We can do it a bit more nicely looking if we show/hide the widgets using some kind of animation. I had already developed some months ago an animator to show an accordion in an animated way. I've added a hiding animation and expanded it for being used with tabs

You can see the animations on its own here and the animated tabs-accordion here

I've uploaded the final result to GitHub, so you can check the code there.

Tuesday, 13 November 2012

Ubuntu everywhere

Technology evolves so fast that it's quite hard to catch up with all the changes (and more if you're into a broad range of its aspects, from hardware to high level development abstractions). So the thing is that some months ago I was taken aback for how easy it's now to create a bootable USB key (even more, a multiboot USB key). Last time I had looked into that had been several years ago, and at that time it was far from trivial and error prone (using dd in Linux and so on, I don't think back then you had many options for doing it from Windows).

So, PendriveLinux was an astonishing discovery that allowed me to create a multiboot key with Ubuntu and several rescue distros. So, I can boot the Ubuntu ISO from there and do a live session or an install, or run some of the rescue distros if my PC has gone into some trouble. So once the mission was accomplished I didn't ponder on it much more until a few weeks ago, when I felt the need to go one step further, and have a "fully usable Ubuntu" on my key, that I could run from my home laptop, my work laptop and so on. What I mean with this is doing a normal Ubuntu installation to the USB key, and use it normally, installing and removing packages and so on.

The idea seemed quite feasible to me. If creating a bootable USB is now so easy and works so neat, installing a bootloader and the OS to the USB Key rather than to the HD (I mean a normal installation, not just a bootable ISO) should not be a problem. I searched the net seeking for confirmation, and It's then when things turned a bit confusing. Most articles seemed to deal with a slightly different scenario, creating a sort of "Live USB" with persistence (space where you can store your settings and even (I think) install new packages). After doing some good readings I decided to follow this detailed and simple article

There's a first point not mentioned there that has to be taken into account. If you (as I did) decide to partition your USB key to leave a Data partition there where you can store data without messing with the OS installation, you should use the first partition for data and install Ubuntu to the second partition. Well, let me be more specific, you must do that if you want to use that data partition from Windows. While Windows has no problem with viewing partitions in an external USB Hard Disk, when it comes to USB Keys, it will only work with the first partition, so you better use that first one as Data partition.
On a side note, my own experience tells me that Ubuntu has no problem working with all the partitions in a USB key, but Android (at least version 2.3) will only see the first partition of a SD card.

So, I used the Startup disk creator utility mentioned in the article, in a few minutes I had my bootable USB. Nevertheless, the persistence option did not seem to work, cause though I had no problem installing a new package and running it (I installed node.js) once I did a restart, the installation was gone (so I guess it just got installed in memory, which confirms the idea that this sort of installations is just a "Live USB".

I decided then to try what I really wanted from the beginning, doing a normal installation, but targeting my USB key instead of the Hard Disk. Well, the process is that simple as it sounds. Boot a Live Ubuntu ISO, start the installation and when presented with the menu to select a target partition, choose your USB key from the combo box. That's all to it, the difference with the other install explained above is that as this is doing a normal install, it takes much longer (while the "Live USB" creation that I did before is very fast).

Once installed, I could happily verify that my "portable Ubuntu installation" works nice on both my Home Laptop and my Work Laptop (Ubuntu 32 bits runs sweet on both my 32 bits and a 64 bits machines). What surprises me most of all of this is that I used to think that at installation time Linux checked what drivers (Kernel modules) were needed for the specific hardware, copied them to disk and generated some sort of list to load them in following start ups (obviously, it would also check for hw changes at boot time, to load or ask for the corresponding new "drivers"). Well, things seem to be quite more dynamic, and at each start up the OS checks the hardware and dynamically loads the needed kernel modules (so no list with the kernel modules needed for the hw present at installation time). This process is done by udev, and is explained here

When your system boots, one of the startup scripts starts up Udev and prods the kernel. The kernel then sends back a stream of events for all the hardware detected when it started up ("add this device", "add that device", ...). Udev picks up these events as if the devices had just been added, creates the appropriate /dev nodes, sends off the appropriate notifications to HAL, and so on.

I guess this also means that Ubuntu seems to copy a whole lot of different kernel modules to disk (not just the ones needed at install time) so that the can be used if needed

All this is really interesting and makes me wonder if it could also be done with Windows, or whether its installation determines the hardware on which that "image" can run

Monday, 12 November 2012

The Day

Long in short, The Day is a total must see (indeed if more people shared my dubious taste it could end up being a cult piece).

The main elements are common to last dystopic films starting by "The Road": ultra dark photography, a bunch of survivors being chased not by zombies, but by other (dehumanized) humans aiming to feed on them, lack of information about how and why the world has come to this gloomy present (in fact, it would be complicated to explain what the real problem is, as there does not seem to be any radiation and climate seems OK (at least it rains)... but both crops and animal life (excluding humans) appears to be missing...

What sets this film ahead of the pack is its pure intensity and how it combines it with themes like redemption, revenge and deception. The hard and tortured character played by Ashley Bell (and how well she performs it) is also one of the strong points of the film. Also noteworthy for me is the presence of the beautiful Shannin Sossamon (I mainly know her for her roles in Wristcutters and Catacombs, but it seems like she's done a deal of interesting films in between).

Well, I don't feel like extending this post anymore, take it just as a fast gift I'm giving you :-) to prompt you to treat yourself watching it.

Saturday, 3 November 2012

Safe dereferencing in C#

There's one feature in Groovy that I really miss in other languages, the Safe dereference operator. (name = p?.Name)
It's amazing how such a simple thing spares you cluttering your code. This C# (or Java) code:

if (person != null && person.Address != null)
Console.WriteLine("person.Address.City: " + person.Address.City);

can be written in Groovy using the "?." safe dereference operator just like this:

println person?.Address?.City

In the last days I've had to write in C# a good bunch of ugly looking code like the above, which made me raise 2 questions:

  1. Why haven't the cool guys in the C# team added something like "?." to the language?
  2. Can't I find a workaround?

For the second question, I quickly came up with an apparently rather usable solution, but once I started to code it I realized it was not that perfect because of the Reference types, Value types, Nullable types differences... In fact, maybe that's the reason for not having "?." in the language itself.
Anyway, I think my solutions is usable enough to share it here and add it to my toolbox:

public static TResult SafeGet<T, TResult> (this T target, Func<T, TResult> getter) where T: class
  //Type of conditional expression cannot be determined because there is no implicit conversion between 'TResult' and '<null>'
  //return target != null ? getter(target) : null; 
  return target != null ? getter(target) : default(TResult); 

that we can use like this:

Console.WriteLine("p1.Address.City: " + 
   p1.SafeGet(item => item.Address)
   .SafeGet(item => item.City)

instead of this:

  var city = null;
  if (p1 != null && p1.Address != null)
   city = p1.Address.City;
  Console.WriteLine("p1.Address.City: " + city);

Some notes about that so simple code:

  • I'm using the "where T:class" generic constraint, forcing T to be a Reference type. I would also like to accept Nullable types there, but these are considered value types, so I have no way to indicate that in the constraint, which means that unfortunately this solution won't work for Nullable types
  • I initially intended to return null:
    return target != null ? getter(target) : null;
    but then we would get the infamous compilation error:

    Type of conditional expression cannot be determined because there is no implicit conversion between 'TResult' and ''

    The compiler can't be sure that the type being returned there can be null (again for this we would need to be able to indicate a nullable constraint)... so in the end I've changed it to default

I then had a look to see what solutions others had thought up for this same issue, and found one guy following a very similar approach

You can download a sample here

Saturday, 27 October 2012

EXBERLINER, sharing everything

After spending a week on vacation in that perfect Utopia dressed in a dystopic outfit called Berlin (each time I go there I confirm it as my favorite place on this planet), I put a perfect end to the experience by reading the October issue (109) of EXBERLINER, the excellent English written Berlin culture and lifestyle magazine.

This issue is focused on technopolitics, so articles range from an overview of some outstanding Open Source projects being developed in Berlin, to an interview with Alec Empire (Atari Teenage Riot), passing by an interview to Germany's most famous net-activists couple, and an analysis of the first year of the Pirate Party in Berlin's parliament

One topic that keeps showing up in several texts is the idea of "liquid democracy" being pushed by the pirates. Leveraging the easiness of communication in our hyper connected world to increase people's involvement in state decisions does not seem like something much new, but what is new here is that they are really trying to implement it!

The interview with Anke and Daniel Domscheit-Berg touches many different points of interest, but I would highlight their musings about Grundeinkommen (basic income), leveraging technology to reduce the amount of time that people need to work daily, and the inevitable shift to a different economic paradigm ("Third Industrial Revolution")

As for the many Open Source projects mentioned, the winner for me is Wikidata, sort of a global knowledge database to be used among others by Wikipedia. Also, after seeing just the day before how one lady got fined in the tram due to her lack of a valid transport ticket (because of the "open doors" nature of Berlin's transport (same as in Vienna), it's tempting to want to try to save some money and it's also rather easy to forget about purchasing your ticket), the SchaffnerRadar (ticket inspector radar) Android App seems like pretty cool :-)

Well, not that it really has much to do with this post, but as it's related to Berlin... you can check here this album of mine about Berlin Street Art.

Saturday, 13 October 2012

A few days in Poland

In early September I was lucky enough to spend a few days in Poland (Warsaw and Krakow) and I had a really great time there. As someone that every time he's preparing a new trip devours astonishing amounts of information about the place, I feel compelled to put my 2 cents in and share my impressions here.

Krakow was probably the most clear miss in my list of "fairy tale Central European cities", and same for Warsaw with regards to my list of "European metropolis", so, an obvious question is, why did it take me so long to set foot there (and more when I've already been several times in places like Vienna, Prague, Bratislava...)?

Well, I had certain reservations with regards to Poland since many years ago. I had heard and read quite awful things about how ultra conservative the country was, about the mass spread of far right scum (though common to most of Central-Eastern Europe, the Polish case seemed to be worse), crazy ultra-violent football hooligans, and a general "unkindness" towards foreigners (at least if they are not pale blonde well dressed people). All this had made me discard Poland as a target in many occasions, but in the last times I'd read quite different things that seemed to indicate that the whole country was moving in a new direction (church losing influence among younger generations, new punk bands, Blu murals in several cities) so it was about time to see for myself (even when documentaries like this by Ross Kemp and Stadiums of Hate made me doubt again).

As usual, don't expect a travel guide here, you have wikitravel and thousands of other resources for that (by the way, geolover is an excellent one I've come across recently), I'll write here about things that somehow I found interesting, but for many other human beings they'll probably be meaningless.


On the one hand this is a modern metropolis. You find large, wide avenues like Jerozolimski and Marzalkowska flanked by average buildings mainly from the second half of the last century (a few buildings seemed like a more modest version of the Socialist Realism masterpieces in Berlin's Karl Marx Allee). There's a good bunch of sky scrappers, some of them really nice (like ) and above all you have the omnipresent Palace of Culture of Science. Sure Stalin was a mother fucker, but it's undeniable that he had a taste for architecture (or convincing posters). The building is even more stunning than I expected and the views from the 30th floor are more than worth the price (around 5 EUR I think to remember). The high speed elevator that takes you up there also adds to the experience (it takes just seconds to lift you there). It seems like the population has managed to reconcile herself with this present from the man responsible for the murder of millions of Polish people, and now the building is nicely lighted in a beautiful blue light at night. Another remarkable feature of this sky scrapper is that the tower that crowns it somehow reminds me of the baroque church towers all-pervasive to Central and Eastern Europe

On the other hand, Warsaw boasts a cozy, delightful old town (completely destroyed during the WWII it was wisely rebuilt in the fifties, which is quite amazing if you compare it to Berlín, where only selected buildings were restored along with the later rebuilding of the tiny (but cute) Nikolaiviertel). I got to the Old town proper after a pleasant walk along Nowy Swiat. This street reminds me a lot of the so nice Gediminas Avenue in Vilnius (indeed, many things on this trip brought to my mind memories of last year's trip to Latvia and Lithuania). An interesting feeling while being around this area was that it didn't seem like being in the Old Town of a big European capital, it was more like being in the Old Town of a middle size city (I wouldn't know to explain the reason, it's just how I perceived it, I guess the fact of not having too many tourists around played its part). Warsaw's old town does not have any element that particularly stands out and is not too impressive if compared to other European jewels, but it's charming and harmonious and well worth your visit.

As the urban explorer that I am I didn't want to miss the chance to cross the Vistula to the Praga neighbourhood (and that way enjoy the views of this wide river). Unfortunately this is one of those cities with its back turned to the river, or at least not leveraging it too much. Same as with Vienna or Zagreb, the main part of the city developed on one side, so even when now it expands almost equally on both sides, you don't have its banks lined with historic buildings reflecting on it. To the point, Praga is well worth a couple of hours that most tourists tend to deny it. Old pre-war buildings with their facades entirely flaking expose its orange bricks. Many small businesses give it character and helps you get a grasp of the normal city. By the way, little after you cross the bridge you run into a nice Orthodox Church.

I should also mention that entering the West bank when coming by bus from Modlin Airport was rather pleasant, as first you get a fast glimpse of the old town right before entering the tunnel that crosses under it. Then, once in Aleja Jana Paula II you'll see to your left an impressive mural by Blu


This cute city really lived up to my huge expectations. I got to Krakow by train from Warsaw in one of those hyper-hot central European summer days. Unfortunately it seems like I've got a tendency to bring along with me heat waves to this part of the world (I've been above 30 degrees in Vienna, Bratislava, Budapest, Ljubljana, Zagreb...). So when I stepped out of the train I guess we were verging 30 degrees, and the sun really burned. Anyway, the beautiful classic covered corridor painted in green that leads to the outside of the station was more than enough to predict a more than interesting stay there. I had my hostel in Kazimierz, the old Jewish neighborhood, that is currently the bohemian heart of the city. This means I started my exploration in a really nice, lively and authentic zone, but please, don't be fooled by some guides comparing it to Kreuzberg or Montmartre... that's senseless. After getting a fast grasp of the area I headed off to the city centre.

I firstly explored Wawle Hill, wow, it's stunning, a really gorgeous architectonic mix, with beautiful views of the Vistula (though the river does not go through the city centre properly, Krakow seems to leverage this water flow quite better than Warsaw). From there I continued my walk to downtown along Grodzka. There I came across the beautiful St. Andrew church with imposing sculptures of the apostles lined next to it. Go on and you reach the gorgeous Main Square. Based on my previous readings I could imagine how beautiful this square was, but what amazed me the most is how much it reminds me of Prague's central square.

The following days I took care of checking out all the other essential tourist spots, and of all that I want to highlight the Museum in Schlinder's Factory. First, it's a pretty new one, so if you've not read pretty up to date information, you could miss it. Second, the Museum of Wartime Krakow hosted there is probably the best WWII related museum I've been to (and I've been to some pretty good ones like: the information center of the Holocaust Memorial, the Topography of Terror or the Museum of the Occupation of Latvia. I think I spent more than 2 hours there, and I could have stayed event longer if I hadn't been that hungry. There are tons of information about those 5 so hard years for Krakow and Poland in general, and everything seems to have been laid out with great precision and detail. Well, in fact, there are a couple of rooms there that I would say are too realistic, one room with huge nazi flags and another one with its floor tiles with swastikas motifs, to my taste it's like a bit revolting.

I always like to take a glimpse out of the tourist areas, and bearing in mind my interest for Socialist Realism, the Nowa Huta district seemed like the obvious bet. I took tram 22 out of Jozefa Dietta and alighted at the Central Square of Nowa Huta. Well, the place is less interesting than I expected, thought it's astonishing to think that these new and beautiful buildings were built for the proletariat masses working in the gigantic steel works, they are not that impressive as the similar buildings in Berlin's Karl Marx Allee (nevertheless, it's important to realize that these Berlin buildings were intended for the party elites, not for ordinary workers). It's a bit depressive to see how the old communist street names and monuments have been taken over by the pope or Ronal Reagan. Sure the pseudo-communist experiment in Eastern Europe did not work well and population there prefers to forget it, but that should not mean throwing yourself into the arms of alternative opresors

General Notes.

Most likely is that when one thinks about Vegetarian food Poland would not be the first place to come to mind, but indeed it's been one of the places where I've enjoyed the most with food in all my trips. Green Way is a restaurant chain with units in most Polish cities. I kept visiting the one in Krakow (2 minutes away from the Main Square) daily, to be delighted by enormous, delicious ultra cheap dishes. The soups/creams are excellent, same as the soja and tomato beans stew or the Mexican Stew. In Warsaw, I regularly headed to Green. Outstanding place, again with tasty, healthy, enormous, hyper-cheap portions. One day I got a soup of the day that seemed to contain as many mushrooms as I usually have in 6 months :-)

Something that rather caught my eye, particularly in Warsaw, were the enormous fabric advertisements covering almost whole facades of many buildings in the main streets. Wherever you looked there seemed to be one of those signs inciting you to pursue happiness through consumerism. One guy explains it neatly in this interesting essay

Advertisers in Poland seem to be addicted to ‘building wraps’, i.e. mammoth fabric advertisements covering entire buildings. Entire façades of hotels, high-rise blocks and even historic buildings are cloaked in massive fabric screens promoting Coca-cola or ice cream. Behind these temporary and changing surfaces, many of the communist-era structures continue, of course, to yield slowly to the processes of time.

It was also interesting to see how (at least at a street level) the Polish economy seems to have kept more independence than the economy of other ex-Soviet Block countries. I mean, in the Baltic countries, Swedish banks, Coffee chains and supermarkets seem to be everywhere. In Hungary, Czech Republic, Slovenia, Croatia... I noticed a huge presence of Austrian and German banks and supermarkets. These countries have been drawn into the sphere of influence of their Western neighbours (in fact, creating back these old spheres of influence was one of the hidden motivations for Western Europe to push the collapse of the Soviet block and the bloody break up of Yugoslavia).
So far, most banks and supermarkets in Poland seem to be local brands, so it appears as if a big piece of the cake were still there to be taken over...

I shouln't conclude this write up without saying that hopefully my prospect was correct, and Poland seems to have walked a long path these last years towards a much more open, modern and tolerant society. I hardly saw any neonazi shithead, and I could see black people on the streets, left wing slogans on some walls and even a gay pub, and in general I felt a good attitude towards foreigners (at least for tourists).

You can also check this and this galleries that I've uploaded into Picasa

Monday, 8 October 2012

Soundtrack to these last months

It's been a long while since my last write up about music, so seems about time to post something regarding the bands that I've been listening more regularly in the last months (not that I think that this can be of much use to my few readers, but more as a homage to the bands themselves)

  • Downfall of Gaia/In the Hearts of Emperors. I've been a loyal follower of Donwfall of Gaia's neocrust since their first instalments. Their side in this split is extraordinary, these German punks manage to raise their sound to a new level of darkness and raw intensity, brutal blackened neocrust in uppercase. Though every second of their side is excellent I have to particularly praise the very fast passages with black metal melodic riffs, wow, go for it.
  • Axidance/Gattaca, split 2012 Some years ago I wouldn't have expected so many excellent, social aware bands hailing from Russia. Not that I have any sort of distrust in the music skills of the slavic people, it's that sadly enough in Russia most of the rebellious subculture seems to be on the far right... Hopefully things have been changing very fast in the last few years, and a whole social aware scene has developed almost from scratch (thanks among others to What we feel and this blog.
    Axidance are part of this new scene, and play top notch blackened neocrust, long songs, slow parts that give way to very fast blackmetalesque sections. Maybe the Czech guys that make up Gattaca (great name for a band, I absolutely love that film) made a mistake doing this split record. Their side (as their previous works) is pretty good (some sort of good old emocrust), but it's outshone by Axidance's geniality.
  • Keny Arkana, "L'esquisse", 2011. Since the first time I listened (and felt deeply touched) by "The Rage", back in 2008, this French lady rapper has been one of my favorite MCs. Her last work not only does live up to its predecessors, I well might say it's even better. Uncompromising lyrics expressed with an almost perfect flow over good and diverse music
  • Decoded Feedback, "Aftermatch", 2010 This came as a wonderful surprise. Decoded Feedback was the band that along with Hocico introduced me to Dark Electronic sounds (aka Terror EBM aka Aggrotech aka Hellektro...) back in 2005, with their albums Phoenix and Combustion being two of my favorite Elektro albums of all times. I thought they had disbanded once and for all in 2006, but to my surprise I found recently that they had released a new album 2 years ago. This new album is quite different from their previous works, quite less aggressive, with some "old school" electronic sound, but it's amazing. One of those few records I can listen non stop from beginning to end and even repeat it.
  • Arma-X, "Anticonstitucional", 2011. This Asturian far left rapper is a secure bet when you seek for excellent social, leftist lyrics. His last work is no exception, on the contrary, it has some of his best tracks to date (El Carrousel, Et in Arcade Ego, Minas y Dinamita...) Essential.
  • Martyrdod, "Paranoia", 2012 One of the best crust records (no neo crust or blackened crust) in years. Pure Scandinavian power in the Skit System vein, as good if not better. The last song is superb.
  • Seeds in Barren Fields, "sounding the siren song in vain", 2011 Goteborg metal at its best, but less melodic and much more black metal influenced than the average Goteborg sound. Technique, fury and attitude (green anarchists). By the way, their name is probably one of the best I've come across in a long time.

    "Sprung from the vegan metal/hardcore act "through the mist of tears", with roots deeply entangled in punk and political hardcore, these seeds are blooming, bursting out into a fully fledged, and raw as hell, metal assault. SEEDS IN BARREN FIELDS engage, with black flags raised, in a battle against religious moral dogma, capitalism, nationalism, consumerism and social control. Promoting values of freedom such as (green) anarchy, animal liberation and gender equality as an alternative to being a part of a lost, scared and disillusioned mankind"

  • Amebix, "Sonic Mass", 2011 Well, to the total disdain of some of the few people reading this, I have to admit that I've never been a huge fan of Amebix. Of course I fully acknowledge their seminal role, but I started to listen to them quite late, and at that time the bands influenced by them seemed much more interesting to me than their "instigators". This said, their new album sounds impressive to me, with really powerful and interesting melodies. I think they should have called it quite properly "The return of the Gods", and it would have not been pretentious at all.

Monday, 1 October 2012

Unity, Interception, AOP...

Though I've been familiar with Dynamic Proxies, Interception and AOP (on a theoretical basis and on some of my "toy projects") since a long while, it was last year the first time I applied some of this on a Production project. As we were using Unity as IoC, we decided to leverage its interception capabilities for some apparently trivial stuff. We succeeded obtaining the functionality that we were seeking for, but a few things seemed a bit unclear to me, something I mainly blamed on our very tight schedule that made me read too fast through the extensive Unity documentation and online samples

So when I recently came across this excellent series [1, 2 and 3] by Dino Esposito, I thought it would be a good idea to look back to my previous experience and clarify this all for future projects

First we should note that AOP and Dependency Injection are quite different things, but in the last times, most IoC containers provide some kind of (basic) AoP support (Spring.Net, Castle Windsor, Unity. This support is mainly limited to intercepting method calls to insert there code related to our logging, validation, security... cross cutting concern.

This method interception is achieved at runtime by means of Proxy Objects, that either point to the intercepted instance (composition) or inherit from the class being intercepted. Well, this is common ground to Spring, Castle and Unity, but there are a few things in Unity that can lead to some confusion:

  • At least for version 2.0, Unity is completely independent from Enterprise Library (the only relation now is that both are developed by the Patterns and Practices guys). If you want to use Unity's (soft) flavor of AOP all you need is adding these 3 assemblies to your project:
    • Microsoft.Practices.ServiceLocation
    • Microsoft.Practices.Unity
    • Microsoft.Practices.UnityInterception
  • Unity mainly avoids the term "Proxy", using the "Interceptor" term instead. We don't have a ProxyGenerator class as we have in Castle, but the Intercept class does just that, creates Proxies (interceptors)
  • When intercepting calls with Unity, we create a chain of IInterceptionBehavior objects, containing the additional logic that we are injecting. Castle's equivalent to these behaviors are called IInterceptor.

Unity provides us with 2 types of Composition based proxies (Instance Interceptor). You already have an instance of an Object and will wrap it with a Proxy (Interceptor in Unity's parlance): InterfaceInterceptor and TransparentProxyInterceptor
and one type of Inheritance based Proxy (Type Interceptor): VirtualMethodInterceptor

We can create and use proxies without need of an IoC container, though for production applications aiming for decoupling and extensibility, it's obvious that we should create them through a Container

I'll write down a few samples, just based on what we needed in that project last year. Let's say you have a Data Source that you want to mock somehow. Mainly, first you want to serialize the Data Entities returned by the real DAOs, and then you want to use those serialized entities instead of querying the real DAO's-DataSource.

So, if we want to inject in our real DAOs an behavior that will serialize those entities they are returning. For this, we can wrap our real Dao in a Proxy object, this will call the real Dao to retrieve the real entities (from a DB for example) and then will serialize those entities before returning them to the caller code, that is fully unaware of this added behavior.

We can create the Proxy ourselves (I'm using a Composition based Proxy, that is, an InterfaceInterceptor)

IUserDao userDao = new DBUserDao();
            IUserDao userDaoProxy = Intercept.ThroughProxy<IUserDao>(userDao,
                new InterfaceInterceptor(), new[] { new SaveResultBehavior() }
            var users = userDaoProxy.GetUsers("Asturies");

Obviously, to decouple things we'll want to use an IoC, register the Dao type with it and later on obtain the Dao instance from the Container

var container = new UnityContainer();
            container.RegisterType<IUserDao, DBUserDao>(
                new Interceptor<InterfaceInterceptor>(),
                new InterceptionBehavior<SaveResultBehavior>()

            IUserDao userDao = container.Resolve<IUserDao>();
            var users = userDao.GetUsers("Asturies");

The second part, using a MockDao that will just deserialze the previously saved Entities turned quite more interesting, and is the one that last year gave me some problems and made me resort to Castle Dynamic Proxies. The thing is that we don't want (because should be unnecessary) to define MockDao classes. All the behavior we need (find an entity on disk, deserialize and return to us) can be done by the interception code (the IInterceptionBehavior), so no need to define empty MockDao classes. So we want Unity to create a Proxy implementing the necessary I___Dao interface and has the deserialization behavior. The problem stems from the fact that Intercept.ThroughProxy requires us to give it an instance of the class being intercepted, so we would need a MockDao class... Obviously, Inheritance based proxies have the same problem, as the proxy will inheritn from that MockDao class. This problem quite astonished me, as I had previously achieved the intended behavior with Castle Proxies, using CreateInterfaceProxyWithoutTarget

Proxy without target. This one is tricky. You don’t supply target implementation for the interface. Dynamic Proxy generates it for you at runtime, using interceptors to provide behavior for its methods.

At the time we were quite in a rush with that project, so I did not further investigate if there were some quite of equivalent in Unity and just fell down to Castle, but it left me with some bad taste that I've finally cleaned now.

Googling a bit, there are other 2 guys asking just that, the Unity equivalent to Castle's CreateInterfaceProxyWithoutTarget [1] and [2]. Well, there's a (failing) answer to the second question that put me on the right track for this, we have to use NewInstaceWithAdditionalInterfaces and a Casting, just like this:

IUserDao userDao = (IUserDao)(Intercept.NewInstanceWithAdditionalInterfaces<Object>(
                new VirtualMethodInterceptor(),
                new List<IInterceptionBehavior>(){new RetrieveSavedResultBehavior()},
                new List<Type>() { typeof(IUserDao) }
            var users = userDao.GetUsers("Asturies");

Using the IoC, there's something more we need to take into account. We can't register a Type, cause the interesting thing of all this is that we're not defining those Mock classes, we're letting the Proxy Generator to do that. Hopefully, we can register a Factory (InjectionFactory) that will take care of calling the Proxy Generator (Unity's Intercept class) to create the proxy, something like this:

            container.RegisterType<IUserDao>(new InjectionFactory(c =>
                return Intercept.NewInstanceWithAdditionalInterfaces%lt;Object>(
                    new VirtualMethodInterceptor(),
                    new List<IInterceptionBehavior>() { new RetrieveSavedResultBehavior() },
                    new List<Type>() { typeof(IUserDao) }

            IUserDao userDao = container.Resolve<IUserDao>();

You can download the whole sample from here

In these samples I've been using the simplest form of interception, we just intercept all the methods for one given object (in that case it's just what I needed, serializing/deserializing all the calls on that Dao). However, in many occasions we'll need to discriminate, some of the methods will need that added behavior and others not. One solution here is continue to intercept all calls, and let the code in the Behavior class decide if that method needs the extra functionality or if it just should let the call go through without any further action). Well, that's one options, but in those cases what we really should use is Policy Injection with its mapping rules and call handlers (as explained by Dino Espósito in the third article in the series).

As we saw last month, all intercepted methods on the target object will execute according to the logic expressed in the Invoke method of the behavior object. The basic interception API doesn’t provide you with the ability to distinguish between methods and doesn’t support specific matching rules. To get this, you may resort to the policy injection API.

To wrap-up, I'd like to point out that Microsoft seems to refer to AOP as "Policy Injection" which I think adds some confusion. Seems like I'm not the only one with this impression

When asked why the name Policy Injection and not AOP, Ed answers:
... the reality is most of our customers have not heard of AOP or AOSD. Please put yourself in their shoes for a second. We wanted a name that was reflective of the use and benefit the block brings, rather than using an unfamiliar term that only the exceptions understand. We also wanted to have no implicit expectations on the design that may be inherited from AO solutions.
So Policy Injection is AOP, or at least a part of it. The reason why Microsoft did not choose the term AOP seems to be that AOP could have been perceived as a boring academic concept, which was fashionable in the .NET community about year 2003.

Tuesday, 25 September 2012

Object.create and inheritance

It seems like much has been written in the last years advocating the use of Object.create over constructor functions and new. This write up by the almighty Douglas Crockford seemed to lay the foundations for this "movement". Well, I pretty much agree with Crockford in that Object.create is much more in line with the prototypical nature of JavaScript. You create an object and then decide to use it as the prototype for another object, and so on, Object.create seems a much better fit than "new constructorFuntion", a construction imported from class based languages.

However, even when I love the prototypical nature of JavaScript, and all the freedom and plasticity that it provides (modifying the prototype of a function or the [[Prototype]] of another object, creating inheritance relations "on the fly")... I'm afraid I'm too used to the class based paradigm, and in many occasions I need that approach: classes as templates for creating objects, as a way to identify what an instance is (myInstance.constructor...).

Indeed, I think JavaScript gives us the best of both worlds, we can have certain structure by emulating classes, but we have total freedom to escape those restrictions and use the prototype or [[Prototype]] to augment a "class" or instance, use traits and so on... with this in mind, Object.create for me is a useful addition, but not a replacement.

I thought it was just me that was missing something about the Object.create advantages, so finding 2 articles [1 and 2] by 2 rather respectful guys, that very closely align with my thoughts, made me feel some relief :-) The main idea in both articles is that Object.create can help us to improve the class based (constructor based) inheritance in JavaScript. Furthermore, Ben Nadel article does a very interesting exploration on how to create a "classical design" (Person-Child with instances of each one) just using Object.create, and draws the conclusion that it doesn't seem to fit well.

So, the idea from both articles is that we would continue to write constructor functions and add methods to the constructorFunction.prototype object, but would create the inheritance chain with:

Child.prototype = Object.create(Person.prototype);

instead of:

Child.prototype = new Person();

This way we avoid invoking the Person "constructor function" when setting the prototype chain, I guess in most cases this is not a big problem, but anyway it's better if we can avoid it.

There's something that both articles are missing and that I consider important, setting the constructor property of the prototype objects in the Prototype chain, that is, in old school inheritance we do:

Child.prototype = new Person();
Child.prototype.constructor = Child;

with the new approach we'll do:

Child.prototype = Object.create(Person.prototype, { constructor: {value: Child} });

This way we can use myInstance.constructor to obtain from the prototype chain the function that was used to create this instance (think of C#'s Object.GetType()). We can argue that this is very static approach of little use in such a dynamic language where irrespective of how an object was created we can freely augment it ending up with something that has little to do with the original "template" used for its creation. Yes, I rather agree, for JavaScript we should mainly think in terms of Duck typing, but well, that's a matter of choice (or style), and depending on that having the correct .constructor property can be important.

So, in the end this is how the code would look:

// Shape "class"
function Shape() {
  this.x = 0;
  this.y = 0;
  console.log('Shape constructor called');

Shape.prototype = {
  constructor: Shape,
  move: function(x, y) {
    this.x += x;
    this.y += y;

console.log(" " +;
var s1 = new Shape();
console.log("s1.constructor: " +;

// Rectangle "class"
function Rectangle() {
  console.log('Rectangle constructor called');;
//very important, remember we have to use the new "properties syntax"
Rectangle.prototype = Object.create(Shape.prototype, {
 constructor: {value: Rectangle},
 rectangleOperation: {value: function(){

There's one interesting point mentioned in the daily.js article when they talk about Object.create as the only way to obtain an object without a prototype chain (that is, [[Prototype]] points to null). We could think of achieving the same by setting the constructorFunction.prototype to null, but contrary to what we could expect, that does not give us a null [[Prototype]] when creating an instance, but makes it point to Object.prototype. I guess it's one of those corner cases explained somewhere in the ECMAScript reference

function Shape() {
//this is pretty interesting, even if we define the Shape prototype as null, an instance object created with it ends up getting a [[prototype]], the Object.[[prototype]]

Shape.prototype = null;
var s1 = new Shape();
if (!Object.getPrototypeOf(s1))
 console.log("s1.__proto__ is null"); //prints nothing

if (Object.getPrototypeOf(s1) === Object.prototype)
 console.log("s1.__proto__ === Object.prototype"); //this is true

Finally, another interesting use for Object.create that comes to my mind, is for mapping "data objects" to "full objects". I mean, a normal object has data and behaviour, but when we sent it over the wire (let's say an Ajax call asking for JSON data) we just receive the data, so we need to map it back to a full object with also includes behaviour (we mainly need to set the [[Prototype]])

I think this example will make it clear (note the use of a fieldsToProperties function, as Object.create expects an object with properties, not just with data fields)

//interesting use of Object.create to map a "data object" returned from the server to a full object
function fieldsToProperties(obj){
 var res = {};
  res[key] = {value: obj[key]};
 return res;

//Employee "class"
function Employee(nm){ = nm;

Employee.prototype = {
 constructor: Employee, 
 generatePayroll: function(){
  console.log("generating payroll for " +;

//let's say I receive this Employee object via an Ajax call, so I have only data and want to add the Employee functionality to it
var e1 = {
 name: "xuan",
 age: 30,
 city: "Uvieu"

e1 = Object.create(Employee.prototype, fieldsToProperties(e1));