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
but
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(Array.prototype.slice.call(arguments, 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 (person.country && person.country.capital && person.country.capital.name)
  console.log(person.country.capital.name);
 else
  console.log("undefined");
 */
 
 console.log("the capital of my country is: " + safeGet(person, "country.capital.name"));
 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)
  return;
 
 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...
 p.country = p.country || {};
 p.country.capital = p.country.capital || {};
 p.country.capital.name = "Uviéu";
 */
 
 safeSet(p, "country.capital.name", "Uviéu");
 console.log("the capital of my country is: " + p.country.capital.name);

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

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;
 }
 else
  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
 nameSpace("org.deployToNenyures.base");
 org.deployToNenyures.base.version = "0.0.1";
 console.log(org.deployToNenyures.base.version);
 
 //namespace already exists, so does nothing
 nameSpace("org.deployToNenyures.base");
 console.log(org.deployToNenyures.base.version);
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 = Function.prototype.call.bind( Object.prototype.toString );
toStr([]) // [object Array]​​​​​​​​​​​​​​​​​​​​​​​​​​​
Think that the result, is just like this quite simpler to understand code:
Object.prototype.toString.call( 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...