Thursday 28 December 2017

Je suis Charlie, Plus que Jamais

(I am Charlie, more than ever) If you read this blog I guess you know I love Charlie Hebdo. Those who have never read it will think about it as an irreverent assemblement of cartoons, for me, much above that, they are an amazing set of editorials, interviews, research reports and columns, one of the few remaining works of real jounalism. I won't say that I always fully agree with their cartoons (for sure I 100% subscribe all those critizising religions, but some of those that deal with dead or sickness are sometimes not to my taste), but all in all Charlie Hebdo represents for me Resistence, resistence to the Islamisation of Europe and to the rise of other far-right movements, and the resistence to abandon our believes in an inclusive, multicolor and open society.

This year I can think of at least 3 editorials by Riss that have been just extraordinary, the one about the Islamist attack in Barcelona (that came with the outstanding "Islam, religion of peace... eternal" cover), the one attacking the separatist maphia in Catalonia, and the one before the second round of the French presidential elections. Regarding the cartoons, one of my favorites was a small one about the Islamist attack in Marseille (unfortunately I can not find it now), and for sure I loved the ones about the Tariq Ramadan pig.

I found bad tasted the cover right before the dead of Johnny Halladay. I have a particular respect for illness, so I don't like joking about it. On the other hand, after Johnny's death Riss wrote something really beautiful. He reflected on how Charlie had never been particularly kind to Johnny (I have no opinion on this guy, so I can not say how much criticism he deserved), but anyway, after the Charlie Hebdo massacre Johnny decided not just to be Charlie, but also singing in the hommage. As Riss said, he really didn't have to do it, but he decided to do so, and for that they appreciate it.

There's one weekly column that is sometimes amazingly good. It's written by Philippe Lanconn, who has such a beautiful way to write about life, death, the passage of time and its effects on us. This journalist survived the attack but was badly hurt. His jaw got basically destroyed and he has undergone multiple surgeries after that (and the healing process has not finished yet at all). His columns talk very often about it, about the pain, about the recovery, about how that day changed his life in so many ways (not just for the physical effect of his injuries, but for the moral effect of the lives that were stolen that day), other times he talks about completely different topics. There was one column after Fidel Castro's death that absolutely impressed me, "the third Death of Fidel Castro". Basically this was the third time Philippe was writing an article about Castro's death, as he had already been asked to write articles in 2 previous occasions years ago, when Castro was just about to die. From his articles this year there are 2 closing sentences that I think will remain with me for the years to come.
One of them said something like (I'm in Asturies, so I don't have the magazine with me) "You feel young when there are others that depend on you, you realise that you've got old when now it's you who depends on others".
The other one closed his column from last week, where he talked about the death of Johnny Halladay, and is such a beautiful statement on how some things can bring back memories and parts of our lives that seemed so far away "Une chanson, quoi qu'elle vaille, reveille des morts qu'on a en soi" (One song, whatever it's worth, wakes up the dead that we have inside).

Thursday 14 December 2017

Lisbon is Booming

I was lucky to live in Lisbon for a couple of months some years ago thanks to a job assignment. I liked the city a lot, and I've gone back as a tourist a couple of times since then, the last time just a few weeks ago. My first time there I enjoyed the city a lot, but I would not have put it in my cities top, at that time I had a sort of obsession with Eastern Europe, and I think Lisbon, while very beautiful, did not feel exotic enough to an Asturian . It's interesting that years later, with the personal evolution brought up by having travelled quite a bit more, having lived for quite a while in another country and just by the passage of time... I've come to consider Lisbon fascinating and a real top city.

It's clear that I'm not the only one, cause the city is booming. When I was there in 2008, just before the start of the crisis, the city center was littered with abandoned buildings and others that while still inhabited where in a total state of disrepair. Now many of those buildings have been totally refurnished (almost rebuilt in many cases) and many more are being rehabilitated (when you enjoy the views from any of the nice viewpoints you'll see construction cranes everywhere due to these intensive rehabilitations). Most of these works are being done by international real state firms targeting foreign customers (the advertisements are mainly in English), so seems like many foreigners are buying, either because they are moving there themselves (living, second residence?) or for renting to others that will move. The city is succeeding in atracting start-ups and creative minds, transforming abandoned factories into incubators, coworking space and so on (the very popular LX factory seems to have been just the beginning

I'll share my reflections about why I think so many people want to live (full or partial time) in the city now. Of course the availability of space in those previously abandoned factories is essential for those wanting to start a business, but there are many formerly industrial cities that have now this kind of availability (to a greater or lesser extent), so which are the other factors that make Lisbon more attractive? Bear also in mind that while I guess that rentals for these work spaces will be cheap, this is not the same for (either for buying or for renting) apartments. What I saw in the window of some real state agency quite shocked me, prices seemed more expensive than France (excluding Paris, of course)

As I said before, the city is very beautiful and charming, but hopefully this is common to so many European cities. There's an essential factor in putting one city out of the rank of "nice to live" places. I explained it here. I'll repeat again how totally absurd (to the point of offensive) it felt to me when time ago I watched a program on TV saying that Warsaw planned to rival Berlin in attracting "creative guys". I think a free and open society is essential for a creative and open mind to consider to join that society, and Eastern Europe is, in general terms, too conservative, religious, nationalistic and xenophobic to be considered attractive. Whatever beautiful the city center of Warsaw (with its cute rebuilt and the new, nearby and shiny skyscrappers), Bratislava, Budapest (and its decadent charm)... could be, when you see bastards attacking the gay pride parade, or demonstrating against any kind of (non-white, blond and blue eyed) immigration... one feels more like putting them out of the European Union than like moving there... Portugal is a normal Western country, some people are more progressive, some are more conservative, but the overall feeling is good (indeed it shares with Spain the honour of not having any Far-Right political party with any significant strenght). So if other conditions are met (and I think they are), it could rival Berlin.

With Eastern Europe (and maybe the Baltic countries also) totally out of the equation. Let's think about other pros on the Lisbon side when compared to other big European cities:

Urban Architecture (from before the 40's) Lisbon architecture is quite unique, with all those buildings with facades covered in tiles. For sure you can not compare it to the wonders of French architecture, so let's say it's on pair with the architecture you'll find in Germany, Belgium, Netherlands, Danmark... but while you can draw more or less similarities between the constructions in these countries, those of Lisbon are totally specific to Portugal. On the bad side, most modern architecture in the city is of no particular interest (and you even have some ridiculously ugly things like the Amoreiras Towers).

Life cost is particularly important if you're planning to move somewhere with a start-up, to work from home, to retire or to live part-time. In those cases your salary is probably not adapted to the place where you are going to live, so you'll like to find a place where these costs are not higher than in your home country. This means that if you don't have a Parisian salary, moving to Paris (the most beautiful city in the world) can be very painful. Same applies to Copenhagen, Amsterdamn... As I've said the high prices of flats in Lisbon quite surprised me, but food, public transport... are in the normal to low spectrum.

Weather. For sure the weather in Lisbon is nice. Sunny and warm most of the year, it rains enough to have a "sufficiently green" landscape for most of the time (so this beats any place in the Spanish Mediterranean). I guess I would miss to go below cero a couple of days per year, but not big trouble. By the way, you have way too many kilometers of beach a step away from the city, and related to this, did you know that there's a good deal of Brazilian immigration in Lisbon? This has to mean that you'll find Brazilian girls on the beach!!! Other than that, if you're into surfing, you have plenty of good spots also.

Diverse life quality factors: Lisbon is a "multiracial" city. You'll have black people from the former colonies, an East-Asian community... Not such a mixed society like other parts of Europe, but for sure much more than Northern Spain. Public transport is good and the airport has cheap flights to almost any other corner of Europe (and though the Metro system covers only some parts of the city, one line will take you to the airport in no time for less than 2 euros!) The city core (the 1/2 million people part) is relatively dense and compact, so no crazy distances between the most interesting areas. Portuguese sweets are pretty good, and coffee is absolutely delicious and cheap. Lisbon also spots some amazing museums. One drawback is that due to it's hilly nature the city is quite bike unfriendly.

These factors explained, there's one city that I love and that indeed reminds of Lisbon in several ways, Marseille. Marseille is amazing, probably one of the most underrated cities that I can think of. The geographical frame of the city is fascinating (better than Lisbon maybe), there's amazing architecture, both old and new, the weather is nice, the beachs are nice and you are 3 hours far by train from Paris. For being France it's a cheap city (flats are cheaper than in Toulouse of Bordeaux), and being France you live in an open and mixed society. Indeed, during my third visit to Marseille it struck me that it could turn into the Mediterranean Berlin, but it seems it's not going to be like that. So why?

Well, the huge advantage of Lisbon over Marseille is not specific to Marseille (and the particularities of its bad reputation), it applies to basically any Western European city/country (save for Portugal, most of Spain and to a lesser extent Italy and Greece). So here it goes, the part that will make this post worth reading if you have managed to get until here... There are no Muslims!!! I mean, the Muslim population is minimal. I did not see any veiled woman in the whole weekend. I did not see any motherfucker with the salafist dress code. I did not see Maghrebian teenagers with their fucking "racaille uniform" comitting petty crimes while waiting to be radicalised. I did not see new mosques sprouting on every corner like poisonous mushrooms (I just remember having seen a big, "historic" one back in 2008. I did not see any fucking poster or sticker against "Islamophobia"...

For sure there are Muslims in Portugal (you even have them in my isolated Asturies...), but the fewer they are the more likely it is that they will try to integrate rather than creating a separate community intending to live by medieval rules and intendending to impose them on others... I have Muslim friends that I really appreciate, but the existence of "nice ones" (even very nice ones) that enrich our societies, can not be a distraction that prevents us from seeing the dangers of the "not good ones" (that as years go by are becoming the norm) and the "very bad ones".

Right now the Muslim problem in France, Belgium, Germany, Sweeden... is still not so dramatic like for forcing you out of the country (unless that you are Jewish) because Muslims are not so many, but you know that they tend to have many kids and that new ones continue to come... so it's clear that in 20 or 30 years they will be the majority in some cities, and some countries will be in the verge of religious war (because I'm pretty sure that many of them won't want to integrate at all). It's already been some time that when I read about one city one of the first things that I do is checking the percentage of Muslim population, to get an idea of to what extent it can be a good place to live. I think more and more people will begin to look into this kind of statistics very seriously, to prepare the scape for when the situation in their cities goes out of control. Lisbon looks like a really good refuge.

Few days after coming back from Lisbon a report showed up in the news with some terrifying (but totally in line with what I expected) predictions about the number of Muslims in Europe by 2050. There are 3 different scenarios depending on the strength of the migration trends, but the worst (and most likely to me) is just devastating. Well, at least France will no longer be the most islamised country in Europe, it will be surpassed by Sweeden (that will "enjoy" of a 30% of Muslims!!!) and Germany. Also the situation in Spain will not be too bad (and I'm completely sure that in Asturies the percentage will continue to be very low).

I had just read some summaries and had not checked the original full report until now. It's amazing to see how correct my "street feeling" was, Portugal is now by far the country in Europe (excluding Eastern/Baltic countries) with the lowest percentage of Muslims, only a 0.4%!!!, and the prediction for 2050 (even in the worst case scenario) is only 2.5%. We've talked a lot about refugees in the last years (war refugees, economical refugees, climate refugees in the future...), n a few years probably we'll have to add a new group to the list, atheist/Christian Europeans becoming "religious refugees", moving from their Islamised cities to the last remaining "normal" countries/regions in "non-conservative" Europe (Portugal, Northern Spain...)

Saturday 9 December 2017

Lambas vs Arrows

I pretty like that anonymous functions via arrow functions in Javascript use the same syntax that anonymous methods (that involve the creation of delegates) via lambda expressions and statements in C# (=> rather than -> in Java). Notice that the C# Expression Bodied Members about which I wrote some time ago, are a different story, they do not involve delegates and indeed are not anonymous.

Apart from the common syntax, there are some differences and similarities that I'd like to remark

C# lambdas

  • They can be async and contain await:

    Func<string, Task<string>> asyncFn = async (txt) => {
                    Console.WriteLine("before");
                    await Task.Delay(2000);
                    Console.WriteLine("after");
                    return txt.ToUpper();
                };
    

    but they can not contain a yield. So can not be used for Iterator methods. This code:

    //error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression
                Func<IEnumerable<string>> IteratorFn = () => {
                    yield return "A";
                    yield return "B";
                };
    

    will throw this compilation error: error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression

  • They can be immediately invoked, but you need to provide the type of the delegate that you are creating. So this will fail to compile:

    //basically the compiler can not work out the delegate type to be created
    string result = ((string txt) => txt.ToUpper())("hi");
    string result = ((string txt) => txt.ToUpper()).Invoke("hi");
    

    but this verbose code will work:

    string result = ((Func<string, string>)((txt) => txt.ToUpper()))("hi");
    result = new Func<string, string>((txt) => txt.ToUpper())("hi");
    Console.WriteLine(result);
    

    The reason why it fails in the first case is that the compiler can not infere the Delegate type that it has to create. It's well explained here.

  • Lambdas can be recursive. Thought they are anonymous we can recursively invoke them by using the name of the variable it has been assigned to and that has been trapped in a closure. The odd thing is that the variable has to be declared before, in a separate line from the assignment).
    So while this does not compile (Use of unassigned local variable Error):

     Func<string, int, string> recursiveExpand = (txt, n) => {
      if (n == 0)
                        return "";
                    if (n == 1)
                        return txt;
                    return txt + recursiveExpand(txt, --n);
                };
    

    This will compile fine

    Func<string, int, string> recursiveExpand = null;
                recursiveExpand = (txt, n) => {
                    if (n == 0)
                        return "";
                    if (n == 1)
                        return txt;
                    return txt + recursiveExpand(txt, --n);
                };
    

JavaScript arrows

  • Same as in C# they can be async and contain await:

    let asyncFn = async (txt) => {
     let res = await new Promise((resolve, reject) => setTimeout(() => {
      resolve(txt.toUpperCase());
     }, 3000));
     console.log("processing done");
     return res;
    };
    

    but they can not contain a yield. So can not be used for generator functions. In Javascript a generator function has to be defined with function*, you can not define it with *(). It seems the reason for this is simply that the ES6 designers did not feel this feature worth the effort it would need to be implemented.

  • Arrows can be immediately invoked. This code will run fine:

    let salesSeason = true;
    let obj = {
     name: "Soumission",
     price: (()=>{
      let basePrice = 400;
      if (salesSeason){
       return basePrice - (basePrice * 0.10); 
      }
      return basePrice;
     })()
    };
    console.log(JSON.stringify(obj));
    
  • You can define recursive arrows with no need to declare the function variable in a separate line.

    let recursiveExpand = (txt, n) => {
     if (n == 0)
      return "";
     if (n == 1)
      return txt;
     return txt + recursiveExpand(txt, --n);
    };
    console.log(recursiveExpand("A", 3));
    

Saturday 2 December 2017

TypeScript Typing

I have to admit that I'd never had any particular interest in JavaScript "superset-style" languages. I've loved JavaScript since I first understood how its base features: prototypes, object expansion and closures worked, and as over the years it has been getting more and more features, I'd never seen the point of moving to one of these "compile to javascript" languages (CoffeeScript, TypeScript...). With this in mind, my only reason to learn TypeScript seemed to be that it's becoming almost compulsory in some environments.

Well, I have to say that I'm amazed. The first beautiful surprise is that as it incorporates all the last-generation ES features, you can just use it as a "javascript version X" to "javascript version X-n" compiler. In that sense it's a nice replacement for Babel.js. It's interesting for example to see the different compiled code of a source that uses async/await. Compiling to es2016 will use a generator, compiling to es2017 will directly use async/await. Apart from this, some people will just use it as if it just were a sort of statically-typed Javascript.

This statically-typed vision is pretty limiting. You can use the language like that if you want, but indeed the "typing discipline" used by TypeScript is much more than that. You'll read in several places that TypeScript uses Duck Typing, well, from my understanding this is not correct, it uses Structural Typing. Even the TypeScript documentation does not seem to care and uses both terms as synonymous here, so I'll try to explain how I see the difference between both terms. It's normally said that Structural Typing is Compile-time Duck Typing, but I think the thing is a bit more complex. This article quite a bit of light on it.

Duck Typing. Duck Typing (like in JavaScript) only cares about the properties or methods that you are accessing (or will be accessing) at runtime. You don't define contracts (specify the type of an argument or variable), you just try to access to a property/method and if it fails you get an error. This is normally done at runtime and that's why we associate Duck Typing with dynamic languages, but it seems there are languages which compilers can do these checks at compile time: C++ and D templates

Structural Typing. This has been a pretty interesting discovery for me. You define contracts (for example the type of arguments to your method) and these contracts are checked at compile-time. In TypeScript you define these contracts via classes, interfaces or just via inline type definitions. The important thing is that contrary to what is done in C# or Java, in order to verify that contract the compiler will not check if the object is an instance of a class in which type hierarchy you can find the class or interface of the contract (this is called nominal typing, because you are checking type names). What the TypeScript compiler does is checking Type compabiliby by checking the shape (structure) of the object with the shape defined by the class or interface. If the shape matches (the object has the requested methods and properties), the contract is fullfilled, regardles of the names of the types in that object type hierarchy.

An interesting point is that with runtime Duck Typing a calling a function passing it the same object could succeed of fail depending of other factors, for example in this JavaScript code the first call works fine, but the second one throws an exception:

function getTax(item){
 if (salesSeason){
  return 0.10 * item.getSalesPrice(); 
 }
 else{
  return 0.10 * item.getPrice(); 
 }
}

var salesSeason = false;
let item = {
 name: "black jeans",
 getPrice(){return 21;}
};
getTax(item);//Works fine

salesSeason = true;
getTax(item); //throws exception, TypeError: item.getSalesPrice is not a function

However, in this TypeScript code Structural Typing will make the compiler give us errors for both calls:

interface ISalesItem{
 getPrice(): number;
 getSalesPrice(): number;
}

function getTax(item: ISalesItem){
 if (salesSeason){
  return 0.10 * item.getSalesPrice(); 
 }
 else{
  return 0.10 * item.getPrice(); 
 }
}

var salesSeason = false;
let item = {
 name: "black jeans",
 getPrice(){return 21;}
};
getTax(item); //compiler error

salesSeason = true;
getTax(item); //compiler error

Just to end this post, another beautiful idea in TypeScript is that the compiler was designed since its inception with a Language Service layer. I guess it was a quite natural decision for Anders Hejlsberg, that at that time had been working very hard on Roslyn.

Sunday 26 November 2017

AsyncFunction and GeneratorFunction

Since ES6 not all JavaScript functions have the same behaviour. Depending on whether they have been created using the function statement, via the method definition sugar inside a class or as an arrow function they will spot different features. You can read about it here, but basically, arrow functions can not be called as constructors and use a static, lexical this; methods (created via method definitions) can not be called as constructors; super can only be used inside methods...

Anyway, I thought that in spite of having different features all function objects where directly instances of Function but I've found out that this is not the case, and we have 2 additional function types (both inheriting from Function): AsyncFunction and GeneratorFunction. When you define and async function, either directly as a "normal" function, via the method syntax or as an arrow function, you are creating an instance of an AsyncFunction, and when you define an async method, as a "normal" function or via method syntax (you can not use arrows to create generators), you are creating an instance of a GeneratorFunction. You can run this code to see that I'm not lying.

class Person{
 constructor(){
 }
 
 sayHi(){
 }
}

function sayBye(){
}

let saySomething = (msg) => console.log("saying: " + msg);

function* myGeneratorFunc(){
 yield "hi";
}

async function myAsyncFunc(){
}

console.log(Person.constructor.name);

console.log((new Person()).sayHi.constructor.name);

console.log(sayBye.constructor.name);

console.log(saySomething.constructor.name);

console.log("-----------------------");

console.log(myGeneratorFunc.constructor.name);
console.log(myGeneratorFunc.constructor.constructor.name);

console.log(myAsyncFunc.constructor.name);
console.log(myAsyncFunc.constructor.constructor.name);

console.log(myGeneratorFunc.constructor.constructor === Function);
console.log(myAsyncFunc.constructor.constructor === Function);

/*
Function
Function
Function
Function
-----------------------
GeneratorFunction
Function
AsyncFunction
Function
true
true
*/

And as I said above both function types inherit from Function (xxx.constructor.constructor === Function)

Friday 24 November 2017

Multiple Iteration

I've come across with a pretty interesting difference in the behaviour of JavaScript generator functions/methods and that of C# iterator methods. Though the names are different (a very wrong decision on Microsoft side, using enumerable/enumerator/iterator rather than iterable/iterator/generator, that is what most other languages do), in both cases we talk about those magic funtions/methods that contain some yield statement and that the compiler will translate into a state machine.

In Javascript a generator function returns a generator object, an object that is both an iterable and an iterator. When you ask the generator object for an iterator (via [Symbol.iterator]) it returns itself. Because of this, trying to iterate multiple times on the same generator object will result in that the iteration will only take place the first time, for the ensuing ones, as the iterator is already at the end, no iteration will happen. I mean:

function* getCities(){
 yield "Toulouse";
 yield "Xixon";
 yield "Berlin";
}

let citiesGenOb = getCities();

let citiesIterator1 = citiesGenOb[Symbol.iterator]();

console.log(citiesGenOb === citiesIterator1 ? "same object" : "different object"); //same object

console.log("- first iteration:");
for (let city of citiesGenOb){
 console.log(city);
}

console.log("-------------");

console.log("- second iteration:");
//no iteration is done, citiesGenOb[Symbol.iterator] is returning the same object
//that was already iterated to the end in the previous loop
//very interesting, this behaviour is different from C#, here the generator object (this is both iterable and iterator) is returning itself, rather than a copy
for (let city of citiesGenOb){
 console.log(city);
}

let citiesIterator2 = citiesGenOb[Symbol.iterator]();
console.log(citiesGenOb === citiesIterator2 ? "same object" : "different object"); //same object


/*
same object
- first iteration:
Toulouse
Xixon
Berlin
-------------
- second iteration:
same object
*/

The generator and the iterator (returned by the implicit call to citiesGenOb[Symbol.iterator] done by the "for...of" loop) are the same object, so once we have iterated the first time, the iterator is at the end and trying to iterate it again will iterate nothing.

In C#, an iterator method returns an object of a class created by the compiler and that implements both the IEnumerable and IEnumerator interface. Based on the Javascript behaviour one could expect that invoking the GetEnumerator method of an instance of this class would return the same instance, but the C# compiler is doing different, let's see some code:

private static IEnumerable<string> GetCountries()
{
 yield return "France";
 yield return "Belgium";
 yield return "Portugal";
}

IEnumerable<string> countries = GetCountries();
var enumerator1 = countries.GetEnumerator();

Console.WriteLine((enumerator1 == countries) ? "Same reference" : "Different reference"); //Different

//the Iterator method is returning an IEnumerable/IEnumerator object, but the thing is that calling to GetEnumerator returns a new instance, rather than the object itself
//Because of that the 2 loops do a whole iteration, and enumerator1 and 2 are different objects.
Console.WriteLine("- first iteration:");
foreach(string country in countries)
 Console.WriteLine(country);

Console.WriteLine("- second iteration:");
foreach(string country in countries)
 Console.WriteLine(country);

enumerator1 = countries.GetEnumerator();

Console.WriteLine((enumerator1 == countries) ? "Same reference" : "Different reference"); //Different


var enumerator2 = countries.GetEnumerator();
Console.WriteLine((enumerator1 == enumerator2) ? "Same reference" : "Different reference");

/*
Same reference
- first iteration:
France
Belgium
Portugal
- second iteration:
France
Belgium
Portugal
Different reference
Different reference
*/  

What seems to happen is that when you call GetEnumerator in your IEnumerable/IEnumerator object, if the object has not been iterated yet, you obtain the same object (that's the first case, where I get "Same reference"), but if it has alredy been enumerated, you get a new instance!. This way you can iterate multiple times the same IEnumerable/IEnumerator object (as you can see, both "first iteration" and "second iteration" do a complete iteration).

Decompiling the IEnumerable/IEnumerator class created by the compiler (instances of which are created by the Iterator method) we can see:

Notice that in Javascript if we have function that expects an iterable that it will iterate several times, rather than passing it a generator object, we should pass the generator function itself, so we can invoke it each time we want to perform the iteration.

Wednesday 15 November 2017

Javascript Default Parameters

As default parameters, Object.assign and destructuring assignment have made it into the language the way to work with optional parameters and default values has changed. I've been writing some examples to get used to the current options and I'll be explaining it here:

Let's say we have a function (or method, but not a constructor) expecting a few parameters. The old-school way to deal with default values was this:

function formatString(st, pre, post){
 pre = pre || "[";
 post = post || "]";
 return pre + st + post;
}

That was a nice Javascript idiom, but since default parameters were added to the language we can do just this:

function formatString(st, pre="[", post= "]"){
 return pre + st + post;
}

That's nice for functions expecting just a few parameters, but if we have many values to pass, we will be joining them in an "options object". This is not just a consequence of javascript missing named arguments, even if we had them (like in C#) having a method signature with a large list of parameters is rather painful and an "options object" is a much better option. For this case we can use destructuring assignment like this:

function formatString(st, {
   pre = "[",
   post = "]"
  } = {}){
 return pre + st + post;
}

console.log(formatString("hi"));
console.log(formatString("hi", {pre: "X"}));
console.log(formatString("hi", {pre: "X", post: "X"}));

If we have a constructor function where we are receiving several values to be assigned to the instance being created, we can do like in the first 2 examples above:

class Formatter{
 constructor(pre, post){
  this.pre = pre || "[";
  this.post = post || "]";
 }

}

class Formatter{
 constructor(pre="[", post= "]"){
  this.pre = pre;
  this.post = post;
 }
} 

But if we are passing an options object which properties we will be assigning to this, we'll have to use Object.assign:

class Formatter{
 constructor(options){
  let defaults = {
   pre: "[",
   post: "]"
  };
  Object.assign(this, defaults, options);
 }
 
 formatString(st){
  return this.pre + st + this.post;
 }
}
 
let formatter = new Formatter();
console.log(formatter.formatString("hi"));

formatter = new Formatter({pre: "X"});
console.log(formatter.formatString("hi"));

formatter = new Formatter({pre: "X", post: "X"});

Given that I mention Object.assign, ES Next features a pretty nice way to join several objects into a new one by means of the spread in object literals

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };
var clonedObj = { ...obj1 };

// Object { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }

Tariq the Rapist

Some weeks ago Charlie Hebdo published an excellent article comparing the "Law of Silence" in Hollywood around the sexual aggressions to women with the "Law of Silence" around radical Islamists in most of the islamized (occupied) neighbourhoods in France (and Belgium for the matter). They proposed to start a campaign similar to "#balancetonporc" (report your pig), that should be called "balancetonyihadist". I absolutely like the idea, but indeed I would prefer a "report the Islamist", as I don't care if they have already, or are about to commit violent actions, as long as they follow an Islamist/Salafist/rigorist Islam they are our enemies and should be expelled from our countries (or imprisoned for life if there's no other choice). Also, unfortunately I think the "Law of Silence" around Islamists is not only a matter of fear ("they'll burn my shop or my car if I inform on those beasts in the 'quartier'"). I think in too many cases the sense of community (that has moved from a positive "help each other" to disgusting, segregationist "communitarism") plays a huge role. I think too many muslims think like this: "I don't fully agree with these 'radicals', but they are 'my people', not like the 'white (or yellow) French infidels'.

Anyway, there has been some nice news in the last weeks. Given the hate and despite that Islamists feel for women, it's not strange that Islamists show up in the list of sex-abusers being reported. Some weeks ago the Islamist scum Tariq Ramadan was accused by Henda Ayari, a woman that after having being brainwashed into Salafism managed to escape from this sect and embrace freedom and dignity some years ago. During the dark times when she was an Islamist she was raped by one of the most popular Islamists, that bastard so admired by the "Islamo-Gauche", Tariq Ramadan. After her, more women have reported being raped by him. You can say that he has not been judged and I should be applying the "Presumption of Innocence" principle. On one side, that principle applies to Human beings, not to medieval beasts. Bearing in mind that for an Islamist abusing, punishing and raping women is just like breathing, I don't think this principle should be applied. If one has to choose between believing what normal people (the abused women) say, and believing what a beast full of contempt for anyone not belonging to the "Islamist clan" says, the choice is pretty clear to me. On the other side, anything that can damage the image of this motherfuckers seems good to me, so the faster and louder we spread the news, the better.

Charlie Hebdo did some excellent cartoons of this "cool and calm" Islamist shithead, and received (once again) dead threats for it...

The official media of the anti-Laique, anti-French, pro-Islam, pseudo-left "movement", Mediapart, was fast to attack Charlie-Hebdo again, and in a delirious statement accused them of being part of a lost left which obsession against Islam sides them with the far-right... I would love to see the offices of Mediapart (assuming that they have physical offices for putting online the hate-speech of a bunch of islamo-collaborationists) burnt to ashes, and the traitor Edwy Penel searching for a job in Qatar...

HUNT DOWN THE ISLAMISTS AND THEIR COLLABORATORS!!!

Wednesday 1 November 2017

Async Recursion

For no particular reason the other day it came to my mind how recursion and asynchrony played together. I've played with some examples and I'm putting them here.

Let's just start with the synchronous, recursive version:

function syncOperation(item){
 return item * item;
}

function recursiveCalculation(items){
 if (items.length == 0){
  return 0;
 }
 
 let curItem = items.shift();
 return syncOperation(curItem) + recursiveCalculation(items);
}

let items = [5, 4, 8];
console.log("result:" + recursiveCalculation(items));

Next the function becomes asynchronous and will invoke a callback function once it's finished. This is similar to asynchronous loops where in the callback you invoke a function that will launch the next iteration of the loop. Here in the callback we invoke a function that will launch the next recursive call.

function asyncOperation(item, callback){
 console.log("asyncOperation");
 setTimeout(function(){
  let res = item * item;
  callback(res);
 }, 1000);
}




function bootStrapRecursion(items, endCallback){
 let result = 0;
 let processItems = (items, newResult) => {
  result += newResult;
  if (items.length == 0){
   endCallback(result);
  }
  else{
   let curItem = items.shift();
   asyncOperation(curItem, newResult => {
    processItems(items, newResult);
   });
    
  }
 };
 processItems(items, 0);
}

let items = [5, 4, 8];
bootStrapRecursion(items, function(result){
 console.log("async result: " + result);
});

Now We move into the modern world, the asynchronous function returns a Promise rather than invoking a callback.

function promisifiedAsyncOperation(item){
 return new Promise((resolve, reject) => asyncOperation(item, resolve));
}

I've come up with 2 ways of using it. Either we return a Promise that we will resolve from the end condition of the recursion


function bootStrapPromisifiedRecursion(items){
 return new Promise((resolve, reject) => {
  let result = 0;
  let processItems = (items, newResult) =>{
   result += newResult;
   if (items.length == 0){
    resolve(result);
   }
   else{
    let curItem = items.shift();
    promisifiedAsyncOperation(curItem).then((newResult) => processItems(items, newResult));
     
   }
  };
  processItems(items, 0);
 });
}

 let items = [5, 4, 8];
 bootStrapPromisifiedRecursion(items).then(result => console.log("promisified result: " + result));

Or we do Promises nesting


function bootStrapPromisifiedRecursion2(items){
 let result = 0;
 let processItems = (items, newResult) =>{
  result += newResult;
  if (items.length == 0){
   return Promise.resolve(result);
  }
  else{
   let curItem = items.shift();
   return promisifiedAsyncOperation(curItem).then((newResult) => processItems(items, newResult));
    
  }
 };
 return processItems(items, 0);
}
let items = [5, 4, 8];
bootStrapPromisifiedRecursion2(items).then(result => console.log("promisified result: " + result));

Finally, we move into next generation javascript using the async/await magic words. This way the code looks almost the same as in the non asynchronous initial sample


async function recursiveCalculationAsyncAwait(items){
 if (items.length == 0){
  return 0;
 }
 
 let curItem = items.shift();
 let auxRes = await promisifiedAsyncOperation(curItem);
 return (await recursiveCalculationAsyncAwait(items)) + auxRes; 
}

async function runAsyncAwait(){
 let items = [5, 4, 8];
 let result = await recursiveCalculationAsyncAwait(items);
 console.log("async/await result: " + result);
}
runAsyncAwait();

One important point to bear in mind is that with asynchronous recursive calls we won't have stack overflow issues whatever deep our recursion is. Being asynchronous we are not pushing frame after frame in the stack. The asynchronous call returns immediatelly and the stack frame is released.

Monday 16 October 2017

Dictionaries, Keys and Hash Codes

It's (or should be) common knowledge that objects used as keys in Dictionaries/Maps (Objects that are based in hash tables...) must be immutable [1], [2]. In few words, the Hash code of an object being used as key will be used to obtain the index in the internal structure in the hash table to locate the object. If you mutate an object, its hash code should also change, so it will no longer work for finding the right bucket in the Hash table. You can read a .net centric explanation here

In .Net when using an object as Dictionary key, the GetHashCode method will be used, and in case of collision it'll move to the the Equals method (and you should have overriden both methods in your class as the default Object.GetHashCode is considered not fit for dictionaries). Something similar is done in Java and Python.

ES6 introduced the Map class, and one of its advantages over using plain Objects as dictionaries is that we can use any object as keys (and not just strings). Object.prototype does not have a "getHashCode" method, so well, it seems a bit strange. Checking the MDN documentation on Maps it says that key equality works according to the semantics of the === operator. This means that if you use as key an objec (other than a string or a number), the key comparison will be based on the memory address of the object, so if you mutate the object, it will continue to be valid for accessing the dictionary. I mean:

let myMap = new Map();

let key1 = {name: "aaa"};

myMap.set(key1, "this is a value");

console.log("first item: " + myMap.get(key1));
//output: this is a value

key1.name = "bbbb";

//the modified object that we use as key is still valid!!! 
//"===" semantics/reference equality is being used

console.log("first item: " + myMap.get(key1)); 
//output: this is a value

This seems like a rather bizzarre behaviour for a Map/Dictionary. You can see here how people implement a "more standard" one.

Notice that MDN says according to the semantics of ===. Obviously one expects access to a Map item to be O(1), so for sure the runtime is not going to traverse the whole Map comparing the keys with "===". To simulate "===" sematics and have instant access, I guess one possibility is to get the hash code of the memory address of the object used as key.

Related to this, given that JavaScript objects behave similarly to a Dictionary of string keys (you can add or remove items and the lookup is supposed to be almost immediate), one could assume that they would be implemented as a Hash Table. Hash Tables are very fast, but they are slower that property access in a other class based languages (C#, Java, C++...) where the access to a specific property will always use a same offset from the beginning of the object (so you save the time of running the "getHashCode" function). Well, I can read here that for example V8 uses dynamically created hidden classes, making property access as fast as in C++.

I noticed this sentence: A Map may be perform better in scenarios involving frequent addition and removal of key pairs. in the MDN comparison. It rather fits with the V8 policiy. Each time you add a new property to an Object I guess V8 needs to create a new hidden class, and that comes at a (small) cost that most of the times is pretty much compensated by the very fast property access that the new class provides. However, if you add/remove very frequently, maybe the time saved in property access does not compensate the time spent in the hidden class creation.

Sunday 15 October 2017

Hendrik Beikirch Back in Toulouse

L'année dernière j'ai déjà écrit sur le magnifique et monumental fresque murale fait par Hendrik Beikirch à Toulouse (quartier Empalot). Comme je l'ai expliqué dans ce post, le bâtiment ignoble sur lequel le fresque a été fait, va être démoli. C'est pour ça que, et compte tenu que les habitants du quartier aiment bien cet fresque, la ville de Toulouse l'a invité à faire une autre fresque le mois dernier. Je suis allé voir le résultat ce weekend, et encore une fois, c'est magnifique!

Essayer d'écrire en Français m'épuise encore, je vais passer à l'anglais...

So another 12 stories building block 200 meters far from the one of the previous year was chosen to be gifted by this amazing piece:

In this picture you can see both murals:

Hendrik Beikirch had already visited Toulouse before these works in Empalot. In 2015 he took part in that year's edition of the Mister Freeze Urban Contemporary Art and Graffiti exhibition. He painted this not so massive but equally beautiful mural in the Mountaudran are. It's still in good health nowadays.

By the way, the Mister Freeze Urban Art festival has kept improving year after year. In 2015 it was good, in 2016 it was very good, and this year is's been just amazing. I should find some time to dedicate a post to this last edition.

Friday 6 October 2017

Low-Rise Cities

I've ever loved skyscrappers. My first times in The City and Canary Dwarf in London I was amazed, and in my first visit to La Defense in Paris I was on the verge of extasis. When I visited Frankfurt, it was mainly cause it's nicknamed "Mainzhattan" :-). Gothick cathedrals have always captivated me, and I tend to see Skyscrappers as a continuation of them.
As of today, I continue to enjoy the view of a skyscrapper dominating a cityskype, but I've turned more selective. It's not that they need to be architectonic masterpieces, but there are some aesthetical minimums that if not reached turn the skyscrapper (or any high-rise building) into a real pain. It's not just a matter of materials, in some occasions I find more interesting some restored high-rise residential buildings of the 70's that some recent glass and steel buildings. For example some of the skyscrappers in Tallinn are pretty "untasty".

The other big change in my perception of skyscrappers is their location. In the past I absolutely loved huge concentrations of skyscrappers, now I tend to prefer isolated ones (1, 2 or 3) scattered over different points of one city. They act as reference points for the urban landscape and I pretty apreciate the contrast with the low or mid-rise surrounding buildings. Related to this also, I don't see the need (or the good taste) of going much higher than 200 meters. I pretty much like Brussels for example, with several towers between 80 and 150 meters spreading all over the cityscape, and with a "non oppressive" small concentration of them in the Gare du Nord area. I also quite like how it goes in Berlin.

Regarding high-rise buildings (I consider like that buildings between 40 and 80 meters), it's a bit the same. I like them a lot, but not massive concentrations of them. Coming from a city (Xixon) where there are no skyscrappers, but half of the city is made up of buildings above 40 meters, disorderly glued ones to others... I can understand that some people are not particulary fond of them (and if you've ever been to Vigo or A Corunha it's even easier to understand).

When I arrived to Toulouse I pretty missed (and continue to miss, waiting eagerly for the planned Tour d'Occitanie and the intended Tour Fenetre de Pista) having at least 1 skyscrapper, and this lack felt odd to me, I was not familiar with cities of this size and healthy economy that didn't have a single skyscrapper (at this moment no building rises above 70 meters). On the other side, I felt quite pleasant its low-rise nature. You find quite a few buildings between 10 and 15 stories, but there are not massive areas full of them, so putting aside that most of them are from the 60's/70's, are ugly and desperately need a total facade refurbishing, they work a bit as the reference points that I mentioned earlier. The low-rise nature of the city center and certain neighbourhoods is really nice, but I absolutely can not understand that they have been constructing tons of buildings of 3 or 4 stories in the last decade (hopefully as of late there seems to be a tendency to construct a bit higher). Low density means a crazy level of urban sprawl that means that you'll never manage to have an efficient public transport system. Just to give you an idea, the future third Metro line that will go from one end to another of the Metropolitan area (the one of 750.000 inhabitants, not the urban area of 1.250.000) will be 25 kms long!!! I think it should be forbidden to construct new buildings of less than 5-6 stories, and 7-9 ones should be the norm. Indeed, overtime I've started to appreciate the mid/high rise mess of my hometown (also because many of them have undergone an amazing facade renovation).

In general terms French people dislike mid/high-rise buildings, and deeply hate skyscrappers. I think it's a sort of trauma caused by how bad things have gone in the social housing states (cités) of the 70's. For me for sure architecture has nothing to do with this disaster. There are some housing states (at least in Toulouse) that are mainly low-rise (Les Izards) and that have ended up turned into no-go areas. It's not a matter of architecture, it's a matter of Islam, fake victimization and pure senseless hate for the old colonial power. There's also a sort of Tour Montparnasse syndrome. Most Parisians hate it; to the point that time ago one candidate to the mayor's office intended to demolish it! (fuck, J'adore cette tour!!!, it makes an amazing contrast with the perfect and so Parisian neighbourhoods around it). Another reason why it's pretty uncommon to see skyscrappers in the French landscape outside Paris it's that there are some very strict security rules. Buildings above 60 meters need to have a permanent unit of fireworkers, so this makes maintenance crazily expensive, and even for cities that seem to be more friendly to high rise buildings (like Marseille and Lyon) it's difficoult to get more than one skyscrapper per decade.

Ma si belle Tour de Montparnasse

I love cities, and I got quite interested in whether there are other relatively big cities that at this day lack any skyscrapper. From my trips, I could think of a few candidates, but I didn't know if maybe there would be some office building or some huge residential block in the outskirts. So I've been investigating in wikipedia and Emporis, and I've come up with a listing (for sure there can be errors, maybe outdated data or some skyscrapper in the metropolitan area that did not show up in the listings I've checked). Notice that I'm not including here churches, historical buildings or TV/Airport towers.

  • Washington DC. This pretty shocked me. The strong height restrictions that have always been in place cause that no building rises above 60 meters.
  • Dresden. It seems no building goes beyond 60 meters
  • Edimbourgh. Tallest building is 64 meters and is just an ugly tower block in a housing state. No proposed skyscrappers as far as I know.
  • Glasgow. Quite a few 70-60 meters towers in housing states. There's some proposal for going higher, but nothing confirmed so far.
  • Dublin. Seems the Irish are "very French" regarding buildings height. Right now the highest building is below 70 meters, but there are approved plans for some buildings between 90 and 70 meters (that have caused quite controversy).
  • Belfast. A couple of buildings around 80 meters.
  • Stuttgart. This one rather surprised me. In one of the most wealthy European cities just a couple of buildings reach 75 meters (hey, like my hometown!!!)
  • Athens. They have a 100 meters building done in the 70's leveraging one moment when they managed to skip the very strict law that prevents buildings from going above 40 meters!!!
  • Bremen. It has a recent office tower reaching 80 meters
  • Strasbourg. Its top is below 80 meters, no plans for rising higher.
  • Malaga. Right now nothing goes beyond 60 meters. There's a controversial proposal for a 130 meters hotel
  • Zaragoza. They have a couple of buildings around 80 meters.
  • Budapest. This beautiful, decadent city has an unintersting tower reaching 85 meters, for the rest is rather low-rise and skyscrappers remain a very controversial topic.
  • Helsinki. A not particularly interesting residencial building tops the city (that as a whole is not particularly beautiful) at 86 meters.
  • Copenhagen. A hospital in the suburbs reachs 120 meters. Then it has several towers between 100 and 80 meters (some of them very beautiful) scattered over the whole city. I pretty like its urban landscape.
  • Geneve. Pretty surprising for such an international city, even more when Zurich and Basel have been moving high in the last years. They just have an old, uninteresting, 90 meters residential building in a "cite".
  • Thesaloniki. Seems like nothing goes beyond 50 meters!
  • Nice. Quite similar to Toulouse. Contrary to Lyon, Nantes or Bordeaux, the 70's, when French laws were not so strict, did not gift them with a remarkable office tower or an ugly residential tower in a "Cité", that would rise beyond 70 meters. There does not seem to be plans for breaking this dynamic

I've also found quite a few other cities that just got their only (or very few) skyscrapper in the last years

  • Seville. They've built a pretty nice glass and steel tower in the last years. Other than that, no building seems above 60 meters.
  • Rome. They seem to have woken up lately, maybe trying to catch up with Milan and Naples.
  • Turin. It's been in the last years when the have had the luck to see the completion of 2 pretty beautiful towers (200 and 160 meters). Notice that before that the city's roof was a 100 meters building of 1933!!!.
  • Goteborg. One recent tower reaches 100 meters. Then a few towers of 80-70.
  • Bilbao. Well, this is a quite particular case. In the city proper there is a single building well above 100 meters (the beautiful Iberdrola Tower, 166 meters). Then there's a new, not particularly cute, residential tower next to the bus station, and then the city is full of mid/high rise buildings absolutely everywhere, so indeed it's a very vertical city. Notice that in Baracaldo (just next to Bilbao) you find the 100 meters BEC tower and some rather noticeable and interesting residential towers.
  • Marseille. The magnificent 150 meters CGA-CGM tower was completed in 2010, and the slightly shorter Jean Nouvel tower should be completed next year. These 2 towers aside, Marseille is very vertical for being a French city. The breathtaking views from La bonne Mere show tons of mid/high-rise buildings, reminding me of Bilbao

Sunday 1 October 2017

Islamists and Delinquency

There's an evident link between radical Islam and delinquency. A big part of the Islamists that go to rape and enslave women in Syria have a background as dealers, common thieves and so on. The same goes for those committing attacks in Europe, indeed, in many cases these ones have not left behind their past as petty criminal, and have been dealing and committing robberies until the day before their attacks. One root reason why these bastards fall easily into Islamism is that they are most of the time very poorly educated people (better to smoke joints in the park than going to high school...) and in most cases they are not particularly smart individuals... This bunch of ignorant bastards are easy prey for any of those Saudi paid and educated imams managing the radical mosque of the neighbourhood, for the Video game style yihadist propaganda on the net or for a previously radicalised prison mate.

It's not only that petty criminals are easier to indoctrinate, it's also that the more criminality exists in one neighbourhood, the more isolated from the rest of the city it will become. The closer and more communitarist the area becomes, the easier it will for the disaffected population to be lured into the Islamist trap. So for the Islamist indoctrinators, every time the police is prevented from entering a "quartier sensible", or the firemen are attacked while trying to do their work, or an ambulance is set on fire (like last month in "Le Mirail" in Toulouse), or a teacher is silenced, insulted and even physically attacked, it's a step in the right direction. That's the main reason why these "thinking heads" of the islamization of Europe, while advocating a "society" where people will get an arm chopped for having committed a robery, approve and support delinquency in the neighbourhoods that they are trying to dominate.

The other day, reading an impressive and terrifying investigation in Charlie Hebdo about the Islamization of the High Schools in the Northern neighbourhoods of Marseille (it's even worse that I would expect), I came across with another motivation for Islamists to tolerate and get involved in delinquency. One High School director explains how in 2004 (yes, the islamization process to destroy our societies has been working from well before many people think) a group of dealers used to insult some young teachers, calling them bitches and infidels for wearing a skirt... After the intervention of the police there was some "negotiation" between the school and these pieces of crap to calm down the situation. The director was quite intrigued by how it was possible that these "very strict" Muslims would be involved in a vicious activity (drugs are forbidden in Islam, they are "haram") like dealing drugs, and discussing with them he learnt:

"They've sweared to me that they only sold drugs to "whites", the French youngsters, and that this was their way to practice jihad. To fuck their brain, their defenses, to break their shit society. That day, I understood that these guys, even if they were lying, were at war with you, with us, with me".

So they conduct jihad by poisonig "the infidels" with drugs. Quite in line with the last directives by Daech and other Islamist beasts, asking for poisoning water supplies, supermarket foods... they also ask for burning forests!!!

Just before publishing this post I learn with sadness about this new Islamist attack, this time in Marseille, in one of world's most beautiful train stations, a place that I particularly love. Hopefully the terrorist has been shot dead by the Security Forces.

More than ever, Let's hunt down (dead or dead) the Islamists

Friday 29 September 2017

Expirable Promises

I'd read some samples of using Promise.race to implement timeouts for Promises (reject the promise if it has not finished after x time). You can see an example here. Looks good, but it's not what had come to my mind when thinking about this issue and not having had the race function into account.

Given that I can not reject and existing promise, I would have to create a new one, that would be rejected if the timeout expires, or resolved if the original promise finishes before the timeout. I call this new promise an "expirable promise". Let's see the code

function createExpirablePromise(pr, expirationTime){
		let nP = new Promise((resolve, reject) => {
			let timeout = setTimeout(() => {
				reject("timed out");
			}, expirationTime);
			pr.then((result) => {
				clearTimeout(timeout);
				resolve(result);
			});
		});
		return nP;
}

If we are given a function that returns a promise we can create a function that returns an expirable promise like this:

//fn is a function that returns a promise
//we return a function that retuns an "expirable promise"
function createExpirableFunction(fn, expirationTime){
	let expirableFn = (val) => {
		let pr = fn(val);
		return createExpirablePromise(pr, expirationTime);
	}
	return expirableFn;
}

With the joyful addition of async/await to the javascript arsenal, we can write a cute sample like this:

//example of a long running async operation
//function that returns a Promise
function formatter1Promisified(st){
	return new Promise((res, rej) => {
		console.log("formatter1 running");
		st = st.toUpperCase();
		setTimeout(() => {
			res(st);
		}, 3000);
	});
}


async function testUsingAsync(){
	let expirationTimes = [1000, 4000];
	for (let i=0; i < expirationTimes.length; i++){
		let timeout = expirationTimes[i];
		try{
			let res = await (createExpirableFunction(formatter1Promisified, timeout))("Hi"); //timeout expires("Hi"); 
			console.log(`succeeded with timeout: ${timeout}, result ${res}`);
			break;
		}
		catch (ex){
			console.log(`failed with timeout: ${timeout}`);
		}
	}
}



testUsingAsync();

Tuesday 19 September 2017

Promises and Tasks

.Net Tasks and JavaScript Promises are rather similar, as both are used for the same. They hold a value that will be available at some point, moment at which they will invoke some code that we've provided to them as a continuation. There are differences though. In the multithreaded world of .Net the creation of a promise can involve the execution of another thread (when we do Task.Run for example), this is not the case with Promises, as at the Javascript level everything is single-threaded. Another difference is the parameter passed by to the (callback) function that will be executed as a continuation. While Promise.prototype.then will pass just the result of the precedent Promise, Task.ContinueWith will pass the Task itself. This stems from the fact that while we can access the result of a Task via the (blocking) Task.Result property, the only way to access the result of a Promise is by the Promise itself passing that result to us.

I've found another not so obvious difference that I'll share here. In .Net there was only a 2 years gap between the introduction of Tasks (.Net 4.0 in 2010) and the arrival of the magic async/await pair (C# 5 in 2012). In JavaScript the gap between Promises and the introduction of ES7 async/await in some environments (let's put aside libraries that simulated it via iterators) has been much bigger. This means that in .Net the exposure of programmers to ContinueWith has been rather low when compared to how much Javascript developers have dealt with then. To work with "then" we need to clearly interiorize this: Given a Promise P1, when we invoke then on it and obtain a P2 promise, if the callback/handler function that we have passed to then returns another promise (P3), then P2 will not be resolved until when P3 is resolved. This allows us to chain calls to "then" rather than nesting them. I mean (from Exploring ES6):


asyncFunc1()
.then(function (value1) {
    asyncFunc2()
    .then(function (value2) {
        ···
    });
})


The flat version looks like this:


asyncFunc1()
.then(function (value1) {
    return asyncFunc2();
})
.then(function (value2) {
    ···
})


The above is well explained in MDN:

A Promise in the pending status. The handler function (onFulfilled or onRejected) gets then called asynchronously (as soon as the stack is empty). After the invocation of the handler function, if the handler function:
...
• returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

In .NET the behaviour of ContinueWith when the delegate passed to it returns in turn a Task is not so straightforward. This internal Task can be either an Attached Child Task or a Detached Nested Task. By default it'll be a Detached Nested Task, meaning that the outer task does not need of this internal task to be finished to be finished on its own. So this behaviour is different from JavaScript. If we want that the completion of the outer task depends on the completion of the inner task, we have to create this inner task with the TaskCreationOptions.AttachedToParent flag. It is explained here and here.

... the Task being created registers with that parent Task as a child, leading to two additional behaviors: the parent Task won’t transition to a completed state until all of its children have completed as well, and any exceptions from faulted children will propagate up to the parent Task (unless the parent Task observes those exceptions before it completes).

I've tested it myself, but the code using Tasks is rather ugly and odd and won't upload it here. Hopefully using async/await abstracts us of all of this.

The Last Face

To make things clear from the beginning, forget all the crap reviews that you could have read, The last face is an excellent movie. Tough, touching, almost captivating, and the performances of Bardem and Charlize Theron are impressive.

When I found that there was a film directed by Sean Penn and starred by Bardem and Charlize Theron I assumed that it had many chances to be a good film. The plot: 2 doctors working on humanitarian missions in war ravaged Africa end up falling in love, but the relation proves to be too difficoult given their circumstance. Well, the "love story" thing is not my cup of tea, but the attrocities in the different African conflicts are of quite more interest to me, so all in all it still could be a good watch. Then I read the critics and felt shocked. Seems like all the "educated and intelectual critics" (and the so cool attendants to its premier in Cannes) were treating it like shit, mocking it and calling it "the laughing stock of Cannes" and "refugees porno"... I felt quite puzzled, so I decided to see by myself.

The film is amazing. Its 3 components: brutality of senseless conflicts in Africa, the risks taken by Humanitarian workers in their uncompromising devotion to saving unknown lives, and the difficoult (to say the least) love story between two of them, play together masterfully. There are many gripping moments like for example when a kid is being forced to shoot his father (that will literaly blow your head away), or the amazing speech of Charlize Theron in a fund raising event. Also when Charlize advocates for focusing efforts on trying to stop the conflicts and allowing development, questioning what sense it makes to try to save these human beings now, just to keep them living in biggest misery, and Bardem tells her that even in all this misery, they manage to find dignity and joy, loving their children and living on. This film is emotional and inspiring, and I really can't understand the bad reviews. Well, maybe I can.

It seems like much criticism comes from relating this film to the White Savior complex. So it seems portraying whites trying to save black lives is a sort of "neocolonial product". It's as if all these humanitarian heros were just trying to purge the "evil white man" culpability, and furthermore they have no right to fall in love (precisely people that show so much love for others sacrificing their comfortable lives as doctors in wealthy western countries to go deep in hell... ) Fuck off, all this criticism denotes all the stupid colonial shame so predominant in western (sort of) leftists. This film is not about colonialism (the past), it's about people dying now and people that will continue to die tomorrow... And by the way, sure many bad things were done in the past, but thinking that all the current misery is just a consequence of "evil white colonial powers" is an oversimplification and for sure will not help at all.

Maybe some "critics" will also dislike the introduction of the AIDS drama in the film by means of a white woman and not an African. I don't think the intent is to denounce how devastating AIDS is Africa, but to remember us that it's even one more threat stalking these doctors that do not doubt in getting soaked in the blood of a stranger to try to save his life.

Monday 18 September 2017

Cool Neighbourhoods

When in Copenhagen last month I went for a stroll to Norrebro, a neighbourhood about which you'll hear quite different opinions. From Alternative, arty, multicultural paradise to non-integrated immigrants ghetto passing by Far-left stronghold. I was there just a few hours, but I guess there's a bit of true in each of those opinions. I mainly got the Alternative/Arty/leftwing cool side of the coin, but a shop with a "burkinis" advertisement also gave me a glimpse of the communitarist-islamist crap side. Anyway, the overall impression was nice, and the place reminded me a bit of Berlin's Kreuzberg (my lovely Kreuzberg)

I searched the net to see if this Norrebro-Kreuzberg link was a common impression and I ended up reaching this site ranking the best "Hipster" neighbourhoods in Europe. Notice that the terms Alternative and Hipster, while lacking of a clear and universal meaning, mean pretty different things to me. I guess I'm interested in "Alternative" (but not "too alternative", as I grow older I tend to enjoy a bit of gentrification and "boboization" and a decrease in the number of squats) and not that much in "Hipster", but the thing is that alternative areas tend to become targets for a Hipster invasion, so probably these Hipster neighbourhood should be quite interesting to me.

I've been to some of the places listed there. Some are amazing, but others did not leave any particularly remarkable impression in me when I was there, so I wondered about the criteria they used to rank a neighbourhood as "Hipster". At the same time, I wondered also about the criteria that (in good part unconciously) I use to put an area in my "list of cute alternative hoods". I'll give you a list of the criteria that I think I follow:

  • A tolerant, international, multicolor, multilanguage population
  • Stree Art everywhere
  • Community managed micro-gardens, pots lining the streets and climbing the buildings (Marseille!!!)
  • Aboundance of old buildings (early XX century is still OK) some beautifully restored, some still waiting for better times, but few abandoned ones. Being dotted with some ugly 60's/70's mid-rise buildings can be a plus (like in Kreusberg).
  • Independent Book stores, art shops
  • Creative spirit, social links among residents
  • Nice cafes with outdoor sitting
  • Affordable prices and availability of small studios so that a single person can pay the rent and live alone (like in France) rather than sharing the flat with strangers (like in UK)

There's an element that I have not put in the list cause it's so important that if not present the neighbourhood can not even be taken into consideration. The neighbourhood must be in a city (and hopefully a country) where islamism, racism, xenophobia, homophobia and nationalism are illnesses that have hardly affected the population (well, indeed, having some isolated cases of these scumheads can be nice to hunt them on the streets and inspire some reivindicative art and social awareness). An open society that won't pay attention to how much melanine you have, how you dress, who you fuck with, where you or your ancestors were born... This said, it would be very difficoult to me to consider cities in the USA or most of Eastern Europe as sound candidates to be high in an "alternative places" list. This also applies to the capacity of a city to attract creative minds. Sometime ago I felt shocked when I read somewhere that Warsaw was going to be the next Berlin in terms of creative industry and appeal for digital entrepenours. Come on, Warsaw has a nice skyline and a beautifully rebuilt downtown, but Polish society is in general very conservative and religious (old style Christianism, not the universalist and "altermundialist" kind of Christianism that we see with certain frequency in Western Europe), nationalistic and not particularly keen of people that are "different"... A place like that can not be a hotspot for creative minds.

Without meeting that premise, a place can for sure be still interesting to pay a visit, but won't be a "lovely place where I'd love to live for a while".

I can see here the criteria that they used for their rank. Basically it makes their cities list rather useless to me.
They don't mention at all anything regarding the tolerance and openness of the society... and use stuff that I could not care less, like Vintage fashion, vinyl shops, co-working spaces... Having being a vegetarian for half of my life I'm pretty happy to see that veganism has become more and more common, but seeing it associated to "trendiness and coolnes" rather kicks my balls... Also, I use my bike rather often to move around Toulouse, but I don't see the presence of "independent bike shops" as particularly important.

Saturday 9 September 2017

Collioure

Collioure is quite of a hidden gem, or at least, given that I found it by chance and had not heard about it before, that's how it seems to me. During the summer there's a special train "Le train des plages" that for a reduced price (still not cheap, but trains in France are pretty expensive) takes you from Toulouse to different Mediterranean resorts spanning between Narbonne and the Spanish border. Over these years I've been several times in Leucate, that is 2 hours far from Toulouse, so it's pretty good for a day trip to the beach. There are 3 different beach villages in the area (La Franqui, Leucate Plage and Port Leucate), and a cute small village, Leucate Village, nice for taking a coffee in the "Place de la Republique", between a morning bath in La Franqui and several afternoon baths in Leucate Plage. These beachs are OK, but lack of any particular charm (they're mainly a simple touristic resort built from the 70's), but if you like swimming in calm and warm water, they are a nice option for a summer day in Occitanie.

Last year I visited one day in Port la Nouvelle, OK for some swimming, but the lack of any charm here is almost painful... So this year I decided to give it a try to some of the more distant locations (3 hours), I settled on Collioure mainly cause the village and the beach are just adjacent to the train station (no need to take a shuttle bus like in other destinations) and because one of the beachs had (at least partially) sand, rather than painful pebbles. I leveraged this first trip to stop for a couple of hours in Perpignan where I pretty enjoyed a fast stroll around the city center that was good to show me that the city well deserves a full day visit (I guess this autumn).

Once in Collioure I was immediately amazed. The narrow pedestrian streets of the city center with those 2 or 3 stories buildings in bright colors, with those nice art shops and the beautiful plants growing next to most buildings and climbing up their walls (I absolutely love this) really captivated me.

Then I got to the sea side to be confronted with the views of the Notre Dame des Anges church on one side and the imposing Chateau Royal on the other. As I hate pebbles (I guess I have delicate soles) I headed to the second beach (Port d'Avall), on the other side of the chateau (where part of the surface is sand). Wow, it's just beautiful. Swimming in the calm, warm water with the castle on your left and the nice buildings and nearby small mountains behind you is one of those memories that will be coming up to my mind every now and then.

It seems people have been mesmerized by this small village for quite a while, which made it one of the essential locations in the development of Fauvism. Matisse and Derain lived in the village for a while, producing here some of their main works.

Collioure also hosts the grave of the Spanish left-wing poet Antonio Machado, who died in exile in this village, few days after having crossed the border fleeing from the fascist beasts that were destroying his country and would keep it in the darkness for the ensuing 40 years.

On a related note, something pretty interesting in the portion of French coast going from Leucate to Marseille is the proliferation of lagoons between the coast line proper and the main land, it's what is called "etangs". The first time I noticed this was when going by train to Montpellier. When approaching Sete I could see water to both sides of the rail track! Sete sits just between the sea and the lagoon, being traversed by canals and bridges, and though it's not a "French Venice" or something of the sorts... is well worth a visit. When you take "le train des plages", the portion between Narbonne and Port la Nouvelle is pretty amazing, the train goes along a narrow land strip traversing the lagoon, which is surrounded by small mountains with some ugly factory on their feet and eolic parks on their tops.

Wednesday 23 August 2017

Oresund Bridge

Maybe you know that there is a bridge that joins Denmark to Sweden, bridging the 16 kms gap between Copenhagen and Malmo. Maybe you've seen some pic like this:

A beautiful piece of engineering, for sure. But if you see a picture like this you'll probably be shocked!

What the fuck? A bridge to nowhere? This is a joke or what?

Well, I didn't go through that astonishment cause I had watched this documentary before. There they explain that the Oresund link is indeed a tunnel and a bridge.
The Copenhagen side of the link is just next to the Airport, and having started a high rise bridge there would have caused trouble with air traffic. A 16 kms tunnel would have been too expensive, so the solution was to mix both. A 4 kms tunnel starts in Copenhagen and goes up into an artificial island where the road/tracks run for 4 kms until reaching the 8 kms bridge that ends in the Swedish coast.

Crossing it by train as I recently did is pretty fast. When travelling from Denmark to Sweeden, when you emerge into the surface you'll see the so famous Turning Torso on your left, dominating the whole region of Scania.

By the way, I should write a post about this trip, but as maybe I won't find the time, I'll mention it here. Copenhagen is a really beautiful city. There's not any astonishing spot, but the city as a whole is really cute. I pretty loved the predominance of harmonious architecture, the main canal and its modern buildings, the imposing Christianborg, the lively, relaxed atmosphere...

Regarding Malmo, probably you've heard about it because of the Turning Torso skyscrapper. Well, honestly there is not much more to it. There are a few nice old buildings, but the old town is really, really small, and for the rest, there a few more nice modern buildings like Malmo live, the water front is OK, there is a small canal... but in general the city reminded me of Xixon, A Corunha or some of the cheap, modern and not particularly tasty areas of Toulouse... so, it's not bad, but for sure it's not too interesting.

Monday 21 August 2017

Some C# dynamic coolness

In the last days I've found some interesting things regarding the use of C# dynamic. I'll put it here.

Implementing Multiple Dispatch. The common use of dynamic is calling a method in a dynamic object. We are getting runtime single dispatch based on the object on which the method is invoked. Either the object itself if it implements IDynamicMetaObjectProvider, or the runtime via reflection, will find the method to invoke. I was not aware that this also applies when the dynamic object is used as parameter. The runtime will check its type and if several methods with the same name exist but with different argument types, it will invoke the correct one based on the runtime type. You can find a cute example here. This is pretty interesting because the runtime will use Reflection to match types with methods, doing on your behalf something that in the almighty JavaScript you would have to do on your own. By the way, this brings to my mind this explanation by Eric Lippert of the differences between using Reflection "manually" and Dynamic

Dynamic and Anonymous Types. At the time of its inception (C# 3) Anonymous Types were pretty limited. The compiler will create a class for your Anonymous Type, but you have no access to its name (so you can not do a cast), meaning that you can only access "freely" to its fields inside the method where they are created (you'll declare it as var and the compiler will use the correct type inside that method). If you return an instance of an Anonymous Object from your method, you'll be returning just an Object (you can not cast them to an inteface nor anything), so in order to access its fields you'll have to use Reflection manually.
Well, we know that dynamic will take care of using Reflection of its own (and pretty effectively thanks to caching), so we can do this:

//It's just the same if we set the return type to "dynamic" or "object" in both cases the compiler will generate a method return "Object"
//static dynamic CreateObject(int flag)
static object CreateObject(int flag)
{
  return new {Name="Francois"};
}
    
static void Main(string[] args)
{
 dynamic ob = CreateObject(0);
 Console.WriteLine(ob.Name);
}

You should notice an important limitation. Fields in Anonymous Types are internal, and when dynamic uses Reflection it plays by the rules, so it won't work if the Anonymous Type was defined in another Assembly.

Json.Net, JValue and implicit conversions. Json.NET has had an excellent dynamic support since quite a few years. This makes accessing the tree of properties in a JObject a real bargain:

var jsonString = @"{
 ""city"" : {
  ""name"": ""Toulouse"",
  ""population"" : 466000
 },
 ""otherData"" : ""aaaa"" 
}";
dynamic obj = JObject.Parse(jsonString); //returns a JObject
string cityName = obj.city.name;
Console.WriteLine("City Name: " + cityName);   

JToken (from which the different JContaine, JObject, JValue objects inherit) supports the dynamic machinery by implementing IDynamicMetaObjectProvider and returning a DynamicProxyMetaObject<JToken> (that extends DynamicMetaObject). The use of dynamic for dynamically accessing properties (or methods) of an object is what we are used to, but when you get to the last element, the "name" in my sample, you have a JValue object, so how does the assignment of a JValue to a string work?
This has quite confused me. It seems like there should be some sort of implicit conversion. Well, the thing is that DynamicMetaObject provides a BindConvert method. I've been having a fast look into the Json.NET source code and honestly, I get a bit lost with all those proxies, metaObjects and binders, but I assume somehow the BindConvert somewhere is who is doing "the magic".