Sunday 22 January 2012

Incendies

Icendies is a masterpiece. Astonishing, shocking, beautiful... the list could go on for so long and anyway it would not manage to describe how good this Canadian film is.

The starting point is pretty good: two Quebecois twins get astonished when her mother's last will is revealed to them, they have to go to the Middle East (from where her mother fled to start a new life in Canada) and find their brother and father (of whose existence the knew absolutely nothing). Though (I'm not sure why) no real names are used for the locations (not even for the country), having a few notions of recent history is enough to guess that the country is Lebanon.

The search begins, and it will walk them through a painful path that will help them better understand their mother. A harsh path of discovery where they'll be confronted with all the attrocities that swept Lebanon in the last decades. I've watched (and read) many more films, documentaries, articles... about the war in the ex-Yugoslavia than about Lebanon (ok, yes, I'm an Eurocentric bastard), so I'd never thought that much about how many similarities can be drawn between both bloody conflicts. Christians killing Muslims, Muslims killing Christian, torturing, raping, training child soldiers that will turn snipers that will shoot other kids dead... that's war, in all its cruelty... forget about heroes, medals, humanitarian actions, high tech advances... war is senseless bloodshed, hatred that will last for decades, neighbours killing neighbours, vomit, attrocity... and this film clearly shows it.

If the above paragraph has not sparked your interest yet, I'll add that the final twist of the story is outstanding, superb, harsh, beautiful, unprecedented... and will fucking blow you away. You won't find many chances to invest 2 hours of your life in anything that great as this film

Killing in the name of God...

Wednesday 18 January 2012

Cool uses of C# dynamic

There's no doubt the dynamic feature of C# is an advance one that should appeal to anyone interested in Programming languages. That said, one can also end up thinking it's one more of those things that is fun to brag about "hey, look how cool my language is", but that is not much useful in real life scenarios. I'll try to beat this thought by showing here some really interesting samples of useful application of the dynamic thing

  • Parse JSON. OK, we've got the JavaScriptSerializer and the DataContractJsonSerializer, but in both cases we need to deserialize to an existing class. What happens if we don't know upfront the properties we'll be dealing with, or we just don't want to spend time typing the corresponding class declaration? Well, we can just parse the JSON string into an ExpandoObject, which fields would be Arrays, strings, numbers or other ExpandoObjects when dealing with other objects. It's really rather simple to implement (and of course it was not an idea of mine, I just got it from here:
    public static ExpandoObject Expando(this IDictionary dictionary)
    {
        var expando = new ExpandoObject();
        var expandoDic = (IDictionary)expando;
     
        foreach (var item in dictionary)
        {
            bool alreadyProcessed = false;
     
            if (item.Value is IDictionary<string, object>)
            {
                expandoDic.Add(item.Key, Expando((IDictionary)item.Value));
                alreadyProcessed = true;
            }
            else if (item.Value is ICollection)
            {
                var itemList = new List<object>();
                foreach (var item2 in (ICollection)item.Value)
                    if (item2 is IDictionary)
                        itemList.Add(Expando((IDictionary<string, object>)item2));
                    else
                        itemList.Add(Expando(new Dictionary<string, object> { { "Unknown", item2 } }));
     
                if (itemList.Count > 0)
                {
                    expandoDic.Add(item.Key, itemList);
                    alreadyProcessed = true;
                }
            }
     
            if (!alreadyProcessed)
                expandoDic.Add(item);
        }
     
        return expando;
    }
    
  • Googling a bit we find a more powerful solution, the ElasticObject depicted in the AmazedSaint's blog. The most amazing thing of this object, and that sets it ahead of for example the inherently expandable objects that we have for example in JavaScript, or of an good-old dictionary, is that if we access a non existing property of another non existing property, both properties will be created!!! I'll give an example:
    • JavaScript:
      var ob = {};
      ob.name = "xose";
      ob.address = {};
      ob.address.street = "Leipziger strasse";
      
      //we have an exception here, the favorites property does not exist, and as we're doing a get, not a set, it crashes
      ob.favorites.book = "1984";
      
    • c#
      dynamic ob = new ElasticObject();
      ob.name = "xose";
      
      //we don't need the line below, the ElasticObject would take care of creating the missing address property as a new Elastic object if needed
      ob.address = new ElasticObject();
      ob.address.street = "Leipziger strasse";
      
      //works fine
      ob.favorites.book = "1984";
      
  • ExposedObjectProbably this is one of the most useful applications of dynamic that I've come across with, it's obvious, but finding this post was a real eye opener. In some occasions I've needed to use Reflection to get access to some private property or method. This is fine (I'm not going to discuss here whether accessing private stuff is a good idea or not), but we get a quite a lot of "noise" (the reflection operations distract us from the real aim, just getting or setting a value), and is far from wrist friendly. Well, there's a much more elegant solution, use dynamic and wrap your object in an ExposedObject. It will take care of using Reflection on its own. Notice that if we were not wrapping our object in ElasticObject and just using dynamic, the Reflection mechanism to which the C# Runtime Binder resorts would not allow access to private items.
      dynamic p1 = new Person("Iyan", 36);
      
      Console.WriteLine("using Reflection:");
      PropertyInfo pr = p1.GetType().GetProperty("Name");
      Console.WriteLine(pr.GetValue(p1, null));
      
      Console.WriteLine("using dynamic:");
      Console.WriteLine(p1.Name);
      try
      {
       Console.WriteLine(p1.age);
      }
      catch(Exception ex)
      {
       //with the normal dynamic behaviour we get an exception when trying to get access to private items
       Console.WriteLine("Exception: " + ex.ToString());
      }
      
      Console.WriteLine("using ExposedObject:");
      dynamic expP1 = ExposedObject.From(p1);
      Console.WriteLine(expP1.Name);
      Console.WriteLine(expP1.age);
    

    All this reminds me a bit of this previous post. Even if we don't use an implementation of DynamicObject, just the dynamic keyword, it's terribly useful yet (let's think of another scenario where it can be applied, we want to "deserialize" some key-value data into different objects and don't want to create specific mappers, just match keys in the data to properties in the objects). Not only we make our code much more readable, but we even get some performance gains thanks to the caching mechanism used by the DLR (as Eric Lippert confirms here)

    With Reflection you do not get any cached behaviour, which means that operations are generally slower, but there is no memory cost for maintaining the cache and every operation is roughly the same cost. With the DLR, the first operation is very slow indeed as it does a huge amount of analysis, but the analysis is cached and reused. That consumes memory, in exchange for increased speed in subsequent calls in some scenarios. What the right balance of speed and memory usage is for your application, I don't know.

    As a side note, I must say that this is a jewel of a blog, with some absolutely amazing posts as this one about GPGPU

Sunday 15 January 2012

Emulate Java Enums in JavaScript

In this recent post I described one technique to get Java like OOP enums in C#. It's time now to do the same in JavaScript.

As JavaScript is such an special language, the approach quite defers from the one I used in C#. Probably there are 1000 better ways to do this, but anyway, it seems enough for me, so I'll share here w what I've come up with. I've got a Enum "base class" from which all our enums will inherit. This base class contains the name property (the main value assigned to the enum) and the values "static" method (that for convenience we'll mixin to the derived Enum "classes"). We don't need a valueOf method cause we can just use the "[]" accessor.

//--------------  Enum "class" --------------------
//base class for all anums
var Enum = function(name){
 //add static methods to the derived class
 //enumerized is a flag, let's do the mixin only once
 if(!this.constructor.enumerized){
  Enum.doEnum(this.constructor);
  this.constructor.enumerized = true;
 }
 this.name = name;
 this.constructor._addEnumValue(this);
};

//mixins "static" methods to each enum "class"
//@type: the enum "class"(function)
Enum.doEnum = function(type){
 type.enumValues = [];
 //"static" methods, for convenience will mixin them to each enum class
 type.values = function(concreteEnum){
  //should return a copy of the array
  return this.enumValues;
 }
 /* Not needed, just use [name]
 type.valueOf = function(name){
 },
 */
 type._addEnumValue = function(obj){
  this.enumValues.push(obj);
 }
};
//----------------------------------------

//--------------  Planet "class" --------------------
var Planet = function _Planet(name, mass, radius){
 //invoke base constructor
 Enum.call(this, name);
 this.mass = mass;
 this.radius = radius;
};
Planet.G = 6.67;
Planet.prototype = new Enum();
Planet.prototype.constructor = Planet;
Planet.prototype.getSurfaceGravity = function(){
 return Planet.G * this.mass / this.radius * this.radius;
};
Planet.MERCURY = new Planet("MERCURY", 3, 2);
Planet.VENUS = new Planet("VENUS", 4, 6);
//----------------------------------------

//----------- testing ---------------
var mercury = Planet.MERCURY;
var venus = Planet["VENUS"];

print("MERCURY data:");
print(mercury.name + " " + mercury.getSurfaceGravity());

print("VENUS data:");
print(venus.name + " " + venus.getSurfaceGravity());

print("planets: ");
var planets = Planet.values();
for(var i=0; i<planets.length; i++){
 print(planets[i].name);
}

And the source

*Note: As you may have figured out, I'm putting in quotes "class" and "static" cause these are concepts that we can't purely apply to a prototype based language like JavaScript.

Sunday 8 January 2012

The Whistleblower

The Whistleblower is such a good film that I hardly know what to write. There's a good bunch of films dealing with the terrible fact of human trafficking (specifically Eastern European women forced into sexual slavery in Western Europe) but this is one of the most compelling I've seen. Sure that knowing it's sadly based on real events make it quite more tough (thought I think it didn't leave such an impression on me as the shockingLilja Forever)

Human trafficking and sex slavery is one of the most miserable crimes that I can think of. While I firmly believe that the exchange of money for sex should be regarded as one more economic transaction (if we leave religious dogmas aside, I don't see any difference between buying food, buying sex or buying software... the problem is when the seller is being forced to sell), I think that anyone involved in human trafficking should have his genitals cut off in a public square and left bleed to death. But this terrible crime is even worst when it's perpetrated by those ("humanitarian" forces) that are supposed to bring law and keep peace in an already devastated place. Members of a military contractor (DynCorp) and local corrupt police officers enslaving and taking prey on young women trafficked into post-war Bosnia, and the UN trying to cover all the fucking mess... well, sounds harsh, doesn't it? What's even more revolting of all this is that I knew hardly a word about this, and well, we could say that I'm a rather social conscious person... so I guess 99% of the population knew nothing about all this shit.

Well, if after reading the paragraphs above you don't feel like downloading and staying glued to the screen with your mouth wide open for the almost 2 hours of emotional action of this film, I think your mind lives in a different planetary system from mine...

Friday 6 January 2012

Access to closure variables 2

For some reason some days ago an old idea about which I had written time ago came to my mind again. Getting access to the free vars of a closure from outside. At that time I said that was not possible in JavaScript, but now I felt like toying around with the idea a bit.

Well, it seems odd that in such a dynamic language where you can get access to the function name, your caller, the parameters, the string representation of a function... you're not given a way to access the vars trapped by a closure. It's a matter of getting access from one running function to the vars of the function where it was declared (declared, not called, this is something that sometimes led me to some confusion, closures trap variables from the function where it was declared, not from the calling function). If we know how closures are implemented in JavaScript, we know that we would need to get access to the internal [[Scope]] property, but it seems to be only accessible to the interpreter, not to us, it's a bit the same as with the [[Prototype]] property (well, [[Prototype]] is more or less accessible now by using the new Object.getPrototypeOf(object) or the the non-standard accessor __proto__). I did some googling-binging to confirm my impressions, and on one side they were confirmed, but at the same time this search also brought up the (partial) solution

The idea is simple, instead of trying to "hack" into the closure, let's go the other way, being the designer of the closure who must decide if he wants some of its variables accessible, and in that case make them accessible. For that, all we need is to create a second closure trapping that same variable and returning it. Let's see a simple example:


var printAndCount1 = function(){
 //our closure "factory"
 var counter = 0;

 

//our "main" closure
 var closureFunction = function(msg){

  print(msg);

  counter++;

 };


//closure used to have access to the trapped var 
closureFunction.getCount = function(){

  return counter;

 };

 

return closureFunction;

}();


printAndCount1("msg1");

print("called: " + printAndCount1.getCount() + " times");

Simple, right? Now, we cold want to generalize this a bit and have a function that gives access to any trapped var that we ask for, the almighty eval comes to our rescue:

closureFunction.getClosureVar = function(varName){

  return eval(varName);

 };

Finally, we could have a sort of general function that we could hook on any closure creating scenario. When we call eval the code being evaled runs just in the same scope where the call is done, this means that if we declare a function inside the eval call, it will trap the scope of the function where eval is being called, so we could do something like this:

var getClosureVar = "function(varName){ return eval(varName);}";

var printAndCount1 = function(){//our closure "factory"
 var counter = 0;

//our "main" closure
 var closureFunction = function(msg){

  print(msg);

  counter++;

 };

//create the closure used to have access to trapped variables
 eval("closureFunction.getClosureVar2 = " + getClosureVar + ";");

 

 return closureFunction;

You can find the code here. In it, you can find some minor "improvement" (use the function.toString() thing...)