Friday, 14 November 2014

Well Done Europe

In the last years I've lost almost all interest in space exploration. Indeed as I've been drawn more and more into geography, history, human societies (that's why I so much love/need traveling) my interest in science has quite decreased (save for programming). Maybe for that, I've welcomed the success of the Rosetta mission even more than I would have done years ago. It's cause more than in the scientific discoveries that this mission can achieve, I'm interested in the "European rediscovery" that it can bring about (and well, the fact that part of the mission were managed from Toulouse also makes it more appealing).

After so many years being instilled with that feeling of disenchantment and decadence by our enemies, even the more proudly Europeans among us have ended up believing their lies, that Europe is over, that we're an old, declining society with no more future than using the memories of our glorious past to try to attract tourists or students from the new "big players": China, India, Arab medieval kingdoms... I hope this small success could be a key to open that prison of apathy and self-pity in which Europe has been locked up. It would be false to say that "Europe is back" cause we've always been here. In spite of the crisis, of our lame governments, of the USA... Europe has continued to be for all these years the most advanced and dynamic society in the world. After having been almost destroyed for so many internal wars we voided the chances of new ones by tearing down our internal borders, we've avoided depopulation by welcoming and integrating newcomers (however much I hate the radical Islam or the conservative trends with which some of these new inhabitants have tried to infect the continent, the overall result of this immigration flow is a clear enrichment of our society). We've continued to create and innovate, and we'll continue to do so, cause Europe is a land of Future, all we need is to believe in ourselves. If during so many centuries of fratricidal wars we developed the most advanced culture in this world, just think what we can achieve if we were to completely erase our internal borders and open the external ones to anyone willing to contribute to these achievements and be one of us.

As the French media has been saying these days, "Bravo Europa"

Sunday, 2 November 2014

Kurdistan

It's quite odd that someone like me, with such an interest on Geography, History and Social issues, and that so strongly supports people's right to self-determination, has never paid much attention to the Kurdish people and their fight for their rights, but this previous sort of indiference has now turned into a deep admiration.

I can remember having come across with posters of some left wing Kurdish organization in Frankfurt in 2010 and how they called my attention, but thought of it as some isolated case, as all the mess of the last decades with Fundamentalist Islam has made me think of the Middle East and Left politics as antagonists terms (which is particularly painful if one thinks of the many left wing groups that in the 70's existed in the region, from Palestine to Afghanistan, the Arab Socialism, the Iranian communists later on slaughtered by that beast called Khomeini...). This last May in Berlin, while enjoying the delightful atmosphere of the May Day celebrations (it's really one beautiful experience), I found a lot of stands of left wing Kurdish organizations (along with Turkish ones, which makes the whole thing particularly inspiring), but for whatever the reason, my lack of interest in the Kurdish people remained.

It's been in the last weeks, when witnessing the heroic fight of the Kurdish Army and Kurdish volunteers against Islamic State that my interest in them has grown to the point of admiration. Almost one half of the Kurdish troops are women, courageous, unveiled women willing to give their lives in the fight against the biggest monstrosity the world has witnessed since the Nazi Germany times (the other day my uncle draw a comparison that I pretty liked between the advent of Islamic State and the arrival of an alien race willing to enslave and destroy Humanity). PKK forces, yes, that group branded as terrorist by the Turkish government (that so "friend of the West" government with a clear Islamist agenda, that supports Islamist terrorists in Syria, that represses Turkish left-wing organizations, kills demonstrators and that continues to deny the Armenian Genocide), helped rescue the Yazidis in Mount Sinjar from the torture and death that the Islamic State had in store for them. While starting as a Marxist-Leninist organization, they have moved now into more modern left-wing positions, with a deep commitment to the freedom of the different human groups (Arabs, Christians, Yazidis...) living in their territory.

It's also very interesting to see what's happening in the Syrian Kurditan, Rojava with the People Protection Units (YPG). This militia works on a democratic basis and as happens with the rest of Kurdish troops (PKK, Peshmerga) have the support of the non Kurdish population in their territory. While I'm not much fond of Vice News in general, this video is pretty interesting.

This last months Kurdish people living in Toulouse have been gathering on occasion at Place du Capitole to try to raise concern about the drama being lived in their land.

I could be wrong as I've said I had never been interested in Kurdish affairs until recently, but the Kurdish nationalism seems to me as having mainly a left wing flavour, which makes it an inclusive nationalism (or better, let's call it a sovereign movement) rather than an exclusive one.

Before finishing, I want to note what should be obvious, that while I have an enormous contempt for the current Turkish Islamist ultra-nationalist government, this disdain does not extend to the Turkish population. Obviously the idiots that vote for Erdogan and/or those that continue to deny the Armenian Genocide are scum to me, but there are many secular, civilized Turks that oppose and rebel against their tyrannical government. Even today, hard-line far-left groups (it has sort of a 70's feeling to me) operate in the country.

Friday, 24 October 2014

The Power of Eval

In this interview Eric Lippert does an interesting statement about the power of JavaScript's eval:

As for if there will be an eval-like facility for spitting fresh code at runtime, like there is in JavaScript, the answer is sort of. I worked on JavaScript in the late 1990s, including the JScript.NET langauge that never really went anywhere, so I have no small experience in building implementations of JS "eval". It is very hard. JavaScript is a very dynamic language; you can do things like introduce new local variables in "eval" code.

Yes, I had already noticed and profited of the astonishing behaviour of JavaScript's eval time ago. You're invoking a function, but in a way it's as if its code were running right inside the calling function (from a "classic" perspective you get access to the Stack of that calling function). So you can write code where the code inside eval gets access to variables in the current function scope or where eval declares new variables in such scope that can be used later on, like this:

var name = "xuan";
 console.log("name: " + name);
 eval("name += 'lluis';");
 console.log("name: " + name);

 eval ("var city='Toulouse';");
 //access to a variable defined in an eval works fine
 //so it's as if eval were adding the variable to the executio context of the enclosing function
 console.log("city: " + city);

and even like this (where a closure is accessing a variable that was created later than the closure itself:

var var1 = "hi"; 
 var closure = function(){
  console.log("closure start");
  //normal access to trapped variable  
  console.log("var1: " + var1);
  //access to trapped variable defined in an eval run after defining the closure
  console.log("var2: " + var2);
  var2 += " world";
  console.log("var2: " + var2);
  console.log("closure end");

 };
 eval("var2 = 'hello';");
 console.log("var2: " + var2);
 closure();
 console.log("var2: " + var2);

You can find the code here

So powerful and given how JavaScript Execution Contexts and [[scope]] work, the implementation does seem quite natural (well, for the case of defining a var in an eval and accessing to it later on it seems like the interpreter is adding that variable to the execution context of the enclosing function).

This is clearly much more powerful that the sort of eval that you can implement yourself in C# via Reflection (no need for Roslyn, Mono and linqPad has had this for many years).

All this reminded me about a post JavaScript needs blocks that I had come across some time ago. It's written by a Ruby guy and from my non Ruby perspective (that probably means that I'm not getting the full idea of the article) I don't see any major need for blocks in JavaScript. Anyway, I was thinking you could implement something similar to blocks by passing "code strings" and running them with eval. But there's a problem that I've found with such approach, trying to return from inside an eval. It would be a bit adventurous to think that such return would exit the enclosing function (this has nothing to do with the [[scope]] chain, so for such behaviour the interpreter would have to be designed with this case in mind). So to my surprise, when I did a test I found that JavaScript does not allow returning from inside an eval!

//trying to run this:
eval("return 1;");

//in node.js you'll get:
Illegal return statement
//and in FireFox you'll get:
SyntaxError: return not in function

Perl is the other language that I use on a regular basis that features an eval function. From the documentation:

In the first form, often referred to as a "string eval", the return value of EXPR is parsed and executed as if it were a little Perl program. The value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This means, that in particular, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards.

So yes, if you run some tests you'll see that the code inside eval will have access to the local variables of the enclosing function and to package ones, but local variable declared inside eval will exist only there, won't be accessible outside. Regarding a return statement inside an eval, it'll return from the eval itself, not from the enclosing function.

I've always complained about Perl not coming with a REPL, but well, thanks to eval writing a basic one on your own is that simple as this:

#!/usr/bin/perl
# repl.pl
# A simple REPL for Perl
#
# Copyright (c) 2014 by Jim Lawless (jimbo@radiks.net)
# MIT / X11 license
# See: http://www.mailsend-online.com/license2014.php
   
$t="\"Jimbo's Perl REPL\"";
while($t) {
   chomp $t;
   print eval($t),"\n";
   $t=;
}

Monday, 20 October 2014

Method Missing And AUTOLOAD

I firstly encountered the ability for an object to invoke a default method when an invokation is attempted on a missing one many years ago, when all the frenzy (at the time) around Ruby prompted me to have a look into the language. This feature in Ruby is called method_missing, and at the moment seemed to me like the most "innovative" feature that I could find in the language (for different reasons I didn't like the language too much and have never paid it any attention ever since). At that time, when JavaScript seemed stagnated because of the very different views (wars) on how the language should evolve (all that ECMAScript 4 madness), Mozilla decided to push the language forward adding different experimental features, some of them (generators, let scope, destructured assignment) will finally make it into ES6, others have fallen into oblivion, some of them sadly (I loved the list comprehensions thing copied from Python). One of them was __noSuchMethod__, that as the name suggests, was the same as method_missing.

Years later I came across this same feature in Groovy, and at in parallel the same feature was made possible in C# through TryInvokeMember when using dynamic. All this made me think of this as a state of the art feature (but to my surprise I've found a long list here of languages supporting this idea), so when I started to learn Perl I felt shocked when finding out that such an apparently deprecated language (the true is that the language continues to grow in power and is at this moment a really, really modern language (though quirky, that's for sure)) could sport such a modern feature. The support for this is given under the name of AUTOLOAD, and though I guess it was not born with O.O. programming, proxies or AOP in mind... it really plays nicely.

The basic use is like this:

package Person;
	use strict; use warnings;

    sub New {
		my $class = shift;
		my $self = {
			Name => shift
		};
		bless $self, $class;
		return $self;
	}

    sub SayHi{
		my $self = shift;
		return $self->{Name} . " is saying Hi";
	}
	sub AUTOLOAD {
        my $self = shift;
		my $methodMissing = our $AUTOLOAD;
		$methodMissing =~ s/.*:://;
		
		#do not intercept calls to a non defined DESTROY 
		if($methodMissing eq 'DESTROY') {return;}

        print "unknown method: " . $methodMissing . " invoked on " . $self->{Name} . " with params : " . join(', ', @_);
    }
1;

Notice that I've added a line to prevent action when a missing DESTROY is invoked.

And thanks to it creating Proxies is so damn simple like this:

package AroundProxy;
	use strict; use warnings;

    sub New {
		my ($class, $targetObj, $interceptorFunc) = @_;
		my $self = {
			targetObj => $targetObj,
			interceptorFunc => $interceptorFunc
		};
		bless $self, $class;
		return $self;
	}

	sub AUTOLOAD {
        my $self = shift;
		my $methodName = our $AUTOLOAD;
		$methodName =~ s/.*:://;
		
		#do not intercept calls to DESTROY (as most classes won't define it and we'll get a warning)
		if($methodName eq 'DESTROY') {return;}
		
		return $self->{interceptorFunc}->($methodName, $self->{targetObj}, @_);
    }
1;

sub aroundTest{
	print "". (caller(0))[3] . "\n";
	my ($p1) = @_;
	my $proxy = AroundProxy->New($p1, 
		sub{
			my $methodName = shift;
			my $targetObj = shift;
			print "$methodName started with params:" . join(", ", @_) . "\n";
			my $res = $targetObj->$methodName(@_);
			print "$methodName finished\n";
			return $res;
		}
	);
	print $proxy->SayHi() . "\n";
}

Bear in mind that Perl supports multiple inheritance. If you had a class inheriting from several classes that in turn define AUTOLOAD, the AUTOLOAD that will be invoked will be the one of the leftmost class in the inheritance chain (@ISA array), just the same that is done to resolve any other method.

I won't close this post without taking the opportunity to complain about ES6 not including this feature. Some will argue that it's covered by ES6 proxies (using the get trap), but it's quite different. With proxies you're creating a new object to wrap the existing one, if we had methodMissing we would have it directly in the object, which means the possibility of addressing more complex use cases: we could expand an existing object with methodMissing and later on remove it, so we could be enable/disable dynamically the feature in one object

Sunday, 12 October 2014

Canceling "Functional Style" Iteration

Somehow the other day I ended up in this StackOverflow question about how to get out (break) from an Array.prototype.forEach "functional loop". I gave it some thought before reading the answers, and all I could think of was throwing an specific Exception that you could later on catch and swallow. All this brought to my mind memories of those times when the venerable prototype.js was all the rage, as I thought to remember that they were using something similar for the each method that they were mixing into Array.prototype.

To my surprise, when looking into the current documentation, I could not find any mention about it. However, you'll find some old discussions referring to that solution:

So hopefully I was not hallucinating. This led me to think why at some point they decided to remove that feature from prototype.js. Well, if we think of each/forEach as the equivalent of the classic for (..;..;..) I think it makes sense. The most common (correct I would say) use of the classic for (..;..;..) loop is to traverse a whole collection (i.e. the stop condition is having reached the end of the collection). If you are going to traverse a collection until other certain condition is met, the normal, semantic way to do it is by means of a While loop. So if you need to break from a for loop, in most cases I think you should switch to a while loop.

This said, it occurred to me that probably we should have some sort of Array.prototype.while method, something like this:

//function stopCondition(item, index, array) returns true to indicate stop
//function action(item, index, array)
Array.prototype.while = function(stopCondition, action){
 var curPos = 0;
 while (curPos < this.length && !stopCondition(this[curPos], curPos, this)){
  action(this[curPos], curPos, this);
  curPos++;
 }
};

var items = ["Asturies", "Armenia", "Austria", "France", "Germany"];

items.while(
 function(it){
  return it[0] != "A";
 }, 
 function(it){
  console.log(it.toUpperCase());
 }
);

I think it's obviously much better that using forEach and a "break" exception that we'll later on ignore:

try{
 items.forEach(function(it){
  if(it[0] != "A"){
   throw "break";
  }
  console.log(it.toUpperCase());
 });
}
catch (ex){
 if(ex != "break"){
  throw ex;
 }
}

Well, actually rolling out your own prototype.while function is unnecessary. In the end what we are doing is selecting elements until a condition is met and applying a function to them, so we already can achieve the same effect by leveraging some of the functionality provided by for example lodash.js: first for doing the selection and then a normal forEach.

var _ = require('./libs/lodash.js');
_.first(items, function(it){
 return it[0] == "A";
})
.forEach(function(it){
 console.log(it.toUpperCase());
});

Saturday, 11 October 2014

The Returned

I've just come from watching The Returned. The setting can seem rather weird, an allegedly Zombies film from the last year in La Cinemateque de Toulouse, a venue mainly dedicated to classic, cultured works. Moreover, it was a Spanish-Canadian film, shot in English (because of Denis Villeneuve I tend identify Canadian cinema with the French speaking Quebec), and with Spanish rather than French subtitles. Funny, isn't it?

The "arty" modern terror style shot that opens the film already gave me pretty good feelings. After that came what is (mainly) not a zombies film, but an intense action drama/thriller, where the infectious disease is just the base on which a gripping, emotional and desperate story develops, showing the best and the worst of the human condition. Unconditional love and treason fuck together to spawn pain and suffering, fear and hate removes from some human beings the last traces of civilization. This is also a story of survival, of how pressure sharpens our instincts for the best and for the worse.

u

The final part of the story is bitter and painful, and we see how the past comes to haunt you determining the future, old errors causing new horrors. OK, enough writing, I'm sleepy and I can not add much more other than strongly recommending you to give it a watch.

Sunday, 28 September 2014

Notable Toulousains

There are several renowned people associated with Toulouse. If you live here for some time, chances are that you'll find out on your own about 2 of them: Paul Sabatier and Pierre de Fermat, as 1 of the main faculties of the city and one of the most important Lycees (High Schools) are named after them. Another one, Jean Jaures, was also an affiliate of the city, but his presence extends over the whole country (and the Sud in particular): streets, sculptures and all sort of references. I'd never heard of him before coming here, but he seems like a really interesting man, a social-democrat (way before Social Democracy had turned into the bad joke it's now) with profound anti-militarist feelings that caused him his death in the aftermath of the WWI that so much he tried to avoid (by the way, the story of how his assassin found death in hands of Spanish Republicans is really interesting, sometimes Justice just happens).

If you ever pay a visit to the interior of Le Capitole or to the Musee des Augustins, and I would urge to do so, as both are very pleasant visits (and free each Sunday for the former and each first Sunday of the month for the latter), 2 painters will become quite well known to you: Henri Martin, and Paul Gervais. Bearing in mind that Gervais lacks of an English entry in Wikipedia, and that the one for Henri Martin is very basic (the French one is much more complete), it seems like they didn't gain much international recognition, but I find them both pretty interesting.

As for Henri Martin and his neo-impressionism, while I really like the room bearing his name in le Capitole, with different images of the Garonne (with Jean Jaures in one of them) and the year seasons (I particularly like the Autumn and Winter ones), the work that really caught my attention since the first moment is Beauté, displayed in Musee des Augustins, a really outstanding representation of female beauty.

For Paul Gervais, I mainly know his works in Le Capitole, both in his eponymous room an in La Salle des Ilustres. I've also admired his work in the Palais Consulaire (last week, during the "Journees du Patrimoine" there was free access to many buildings usually closed to the public), and I know he has some paintings in "les Augustines", but I've overlooked them in previous visits, so I have some homework for the next one. All his works known to me revolve around the same noble goal, the careful and delicate portrait of female nudity.

This is done in a very interesting way, a nude beauty that aims to be enjoyed and admired, and it achieves this by doing such contemplation a part of the scene. In all these works, these nude women are not alone, but accompanied by dressed men turned into permanent worshipers of these goddesses. In this sense, "la bain de la Padilla" is probably his most shocking work:

If this man had lived in our times, he well could have become a painter of strippers :-D