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