Monday 24 December 2018

TypeScript, async and Return Type

The other day when writing one TypeScript async method I got into some doubts that made me revisit the last part of this post, the one about the wrapper Promise that the compiler creates for an async method and how this won't be resolved until the internal Promise is resolved. Basically I have one async method that invokes to async methods to return a Person object.


class Person {
    constructor() {
        this.name = "";
        this.city = "";
    }
}
function getFirstId() { //returns a Promise of a string after 1 second
    return new Promise((res, rej) => {
        setTimeout(() => res("1AB2"), 1000);
    });
}
function getPerson(id) { //returns a Promise of a Person after 1 second
    return new Promise((res, rej) => {
        let p = Object.assign(new Person(), {
            name: "Francois",
            city: "Paris"
        });
        setTimeout(() => res(p), 1000);
    });
}

In JavaScript (ES2017), I know I can write the client code in 2 ways:

Doing a return await

async function getFirstPerson() {
    let id = await getFirstId();
    return await getPerson(id); //this return happens after 2 seconds
}

let per = await getFirstPerson(); //all in all we wait 2 seconds

Doing a return

async function getFirstPerson2() {
    let id = await getFirstId();
    return getPerson(id);  //this return happens after 1 second
}

let per = await getFirstPerson2(); //all in all we wait 2 seconds

The first case is pretty clear, return await getPerson(id); returns a Person, that resolves the wrapper Promise that was created and returned when the function was first invoked. The second case is what I explained in that previous post. return getPerson(id); returns a Promise of a Person, and the wrapper Promise won't be resolved until this one is resolved. So for most aspects both codes are equivalent.

The doubt for me when writing equivalent code in Typescript was with the return types. For the second function I was writing:

async function getFirstPerson2(): Promise<Person>{
    let id = await getFirstId();
    return  getPerson(id);  //returns really a sort of Promise>
}

let per = await getFirstPerson2();
    

The TypeScript compiler allows this and compiles it to the JavaScript above. The return is not returning a Person, but a Promise of a Person, with joined to the wrapper Promise created by the runtime gives us a sort of Promise of a Promise of a Person. Anyway, as the external await will wait for the resolution of the inner Promise, the TypeScript compiler is happy with the Promise function signature.

As I explain in the comments to the JavaScript code, depending on whether we do return await or return the return happens 2 or 1 second after the invokation. Anyway, the external await waits for 2 seconds since the method call is launched. There's one more difference related to this that could be important, exception handling. Let's say the Promise returned by getPerson were rejected. In the return await case, a try-catch in getFirstPerson will catch the exception, I mean:

async function getFirstPerson(fail: boolean): Promise<Person>{
    try{
        let id = await getFirstId();
        return await getPerson(id, fail);
    }
    catch{
        console.log("exception caught in getFirstPerson");
        
    }
    return new Person();
}

async function main(){
    console.log(Date.now() + " before calling getFirstPerson");
    //no need for a try-catch here, the one in getFirstPerson catches it all
    let p = await getFirstPerson(true);
    console.log(Date.now() + " person: " + JSON.stringify(p));
}

In the case of return we are just returning the Promise, so we'll need the try-catch for the outer await also, I mean:


async function getFirstPerson2(fail: boolean): Promise<Person>{
    //only catches the getFirstId rejection, but not the getPerson
    try{
        let id = await getFirstId();
        return getPerson(id, fail);
    }
    catch{
        console.log("exception caught in getFirstPerson");
    }
    return new Person();
}

async function main2(){
    console.log(Date.now() + " before calling getFirstPerson");
    //we need a try-catch here for the getPerson rejection
    try{
        let p = await getFirstPerson2(true);
        console.log(Date.now() + " person: " + JSON.stringify(p));
    }
    catch{
        console.log("exception caught in main2");
    }
}

Saturday 22 December 2018

Tour Perret, Amiens

There's a belt of 'department capital cities' surrounding Paris conveniently placed at little more than 1 hour by train (Rouen, Amiens, Reims, Orleans, Troyes) from the magical city, that seem perfect for a day trip. Years ago I did it with Rouen, and lately I had thought many times of going on with exploring some of these cities, but in the end the idea of wandering around Paris always ended up winning over this kind of day trip. Last week I was lucky to spend a few days in Paris again, and finally decided to go for something new and do a day-trip to Amiens the capital of the historical territory of Picardy.

Amiens is mainly known as Jules Verne city. Hey, but Nantes also claims that title, right? Well, indeed he spent his life in Nantes, Paris and Amiens... a smart guy I have to say. Amiens is a lovely city, at least its city center (I did not go any further). Having been in Lille some years ago I already knew that the beautiful architecture of Northern France is very similar to what you find in Belgium, but what quite surprised me is that Amiens has quite of a Brugges feeling. The small canals and the beautiful single-family houses in the St Leu neighbourhood (and the rain, cold and humidity...) brought me many memories of my autumn trip to Brugges years ago. All the city center is really beautiful and is well worth a visit, and the massive gothic cathedral is just gorgeous, but there's an architectural element that I found particularly striking, and that grants the city the right to be in modern Architecture books, the Tour Perret.

The Tour Perret was built in the early 50's and with its little more than 100 meters height it was for some time the tallest building in Western Europe (quite funny to find that in a small city in a country where for good part of the population the irrational hatred for buildings higher than 8 stories makes up one essential part of their identity...), but this kind of past ranking is not particularly interesting to me, what seduced me (mesmerized me almost) is its architecture. The tour is amazingly thin, a square base with 4 windows on each side (becoming 3 in the upper levels). Made of grey reinforced concrete, when seen from the distance one could almost think of it as the belfray of some gothic church, so it's really amazing how nicely it fits in the city scape. A perfect reference point that makes an amazing contribution to the beauty and charm of this small city.

This building is just opposite the main train station, gare du Nord, that was built at the same time also by Auguste Perret in a similar style. It looks pretty massive and interesting (even more with the carefully placed Christmas lights)

Sunday 16 December 2018

FIC Xixón 2018

One of the first posts in this blog, back in December 2009, was about that year's edition of the first posts in this blog, back in December 2009, was about that year's edition of the Xixon Film Festival (FIC Xixon). For the next 3 editions I continued to post my impressions on that year's edition, until 2013, when I was no longer in town during the festival. After a 5 years gap, this November I was in town again during part of the festival, so it was time for me to return. In these five years the festival has gone through some hard times I think. The funding has been reduced (which has forced to cutting its length 1 or 2 days), the director that started in 2012 was questioned for most of his time leading it (I won't add anything to that debate, just say that the only edition under his command that I could experience, 2012, seemed excellent to me) until being replaced for the 2017 edition, and the hardest hit for me (that indeed made me doubt about the survival of the festival) was the closing of the only private cinemas in downtown (that were where most of the films were screened).

Last year I read on the local newspaper an interview to the new director where he was rather positive about the outcome of that edition. The guy seemed pretty modest and sincere, and explained how in spite of all this difficoulties, they had managed to host a pretty decent festival increasing the attendance and the interest of young locals. Currently the festival is held in 3 locations in downtown: Teatro Jovellanos (the beautiful public theatre that has always been the festival's main site), a small, uncomfortable, screening room in "Antiguo Instituto" (this is not new), and a new screening room in the renovated "Escuela de Comercio" (I've never been there, so I can't say how it looks). There's another location in a cultural center quite far from downtown (CMI Pumarin Sur) , that is not new either, and another one in "Teatro de la Laboral", a nice theatre in an amazing, massive complex, but very far from the city center. Finally, 3 rooms in one cinema (Yelmo Cineplex the only commercial cinema in town) located in a mall quite far from the center. With this in mind and being pretty busy with work lately, I was only interested in films screened in "Teatro Jovellanos". I attended to 2 of them.

Saturday 17, The Load, Serbia, Ognjen Glavonic. I pretty enjoyed this fictional work based on a true, little known, dirty event of the Serbia-Kosovo war. A truck driver (before the war he had another job, but now it's the way he's found to put food on the table) has to drive a load from Kosovo to the outskirts of Belgrad. The trip is not particularly exciting but has some odd situations and is good at showing us how in the middle of war people try to go on with their lives, couples get married, teenagers behave as tennagers... As the film develops we (and the driver) will find out that he's carrying the corpses of Kosovar civilians killed during the war, that will get secretly buried in a mass grave in Serbia far from international view. The final part of the movie is poetics and fantastic. Our driver goes through a sort of catharsis talking to his son about how his grandfather had fought against fascism in WWII and decides to document somehow what is happening. The director was present in the cinema and there was a general discussion with him at the end of the film. I could also exchage some impressions with him at the exit. All in all, the guy was an antifascist that had gone through the very difficoult process of doing a work like this in such a nationalistic country like Serbia in order to fight fascism. Absolutely praiseworhty, even when I felt a bit like he was falling too much in the typical European self-demonization. For sure telling this story to make public a hidden and hideous event is important, but we should not forget that Kosovars did as bad, if not worst crap during and after the war, than Serbians. By the way, I absolutely loved the HxC Punk song that closes the film.

Monday 19, One Day, Hungary, Zsofia Szilagyi. Honestly, I did not plan to attend to this film, but one friend of mine wanted to go to 1 session and this one came fit. I have to say that it's been quite a surprise. The plot did not seem to appealing, a day in the life of a Hungarian worker, wife, mother of three and married to an unloyal husband, but it shows masterfully how stressful and painful normal life can be. The film is intense, and at some moments becomes oppresive, immersing us in the little hell in which life has turned for this ordinary woman. One could say that it is disgusting to try to make look the normal life of a European woman with good health as a calvary of pain and suffering, but (have no idea if this was the intent of the director) it works pretty well to remind us of how good we can be at drowning us in misery with our little problems, forgetting how others have to deal with real shit day after day.

Sunday 2 December 2018

Post and No DTO class

Working on an Asp.Net project I've come across a problem that reminded me of an old post. I have one action in one controller that just expects a simple value (a string) as parameter. The action is not for querying data, and though we are not doing a real REST API, at least I wanted to use a POST and not a GET, and pass the value in the post body (not as a querystring).

When passing multiple values the normal thing is just creating a sort of "DTO" object with those values as fields, send it as JSON and let the ModelBinder do its work. But for a single value (or a couple of them) it felt bad to me to create a class with just a single field. This seemed a perfect case for using dynamic. I mean:

//Client side code
  addItem(item: string): Observable {
    return this._remoteService.post(this.url,
      {
        item: item
      });
}


//server side code
        [HttpPost]
        public HttpResponseMessage AddItem(dynamic dto)
        {
            //wrong, myService receives a "null" value
   return Request.CreateResponse(HttpStatusCode.OK, this.myService.AddItem((dto.item as string)));
        }

The thing is that the myService.AddItem was receiving a null value. Checking with the debugger I could see that the dto object with its "item" field was reaching fine the controller. The model binder was using Json.Net and deserializing it to a JObject. JObjec and "dynamic" are designed to work together, so why was I receiving null when passing over the dto.item???

Here is where that old post of mine comes into play. In my code I'm using the as operator to tell the compiler that dto.item is a string, dto.item as string. The problem is that such statement is false, dto.item is a JValue (containing a string we can say), so when the runtime finds that we don't have a string but a JValue (you can read more here), as fails and returns null. So in this case we have to use the cast operator, (string)dto.item, that here does not behave as just a "hint", but performs a explicit conversion from JValue to String. If you are confused, read my old post, where this thing of cast vs as and the 2 different behaviours of the cast operator (hinting vs converting) are well explained.

//server side code
        [HttpPost]
        public HttpResponseMessage AddItem(dynamic dto)
        {
            //works fine
   return Request.CreateResponse(HttpStatusCode.OK, this._virtualDocument.AddFavoriteToCurrentUser((string)dto.item));
        }

Of course I could be using Content-Type: application/x-www-form-urlencoded as explained hereand the ModelBinder should work fine, but there are some differences depending on the ASP.Net version, and I prefered to just follow the json route.

Friday 30 November 2018

The Sea of Trees

I've never considered myself a particularly smart or cultivated person. I should read/have read many more and better books, travelled more and earlier, interacted much more with people that had things to teach, all in all learn much more from everything... cause I've always wanted to have a good understanding of our world. Anyway, and particularly taking into account how the cultural level of our society has dropped in the last decades, I try to think that I could be placed in the "not too idiotic" group of people. However, from time to time something happens that makes me think that maybe I'm much more of a redneck that I would like to think and accept. It has happened lately with my reaction to one film "The Sea of Trees" as it happened more than one year ago with The Last Face, another excellent film.

I watched The Sea of Trees a bit by chance. It was available in the "videotheque" of the multimedia device in the bus carrying me to Madrid. I had plenty of films in my own tablet, but decided to give this one a chance without even checking the wikipedia review. Wow, I loved this film. It felt really powerful to me. One Western middle age guy runs into a Japanese counterpart in The Japanese Suicide Forest where both intended to put an end to their lives... Little by little the story that has brought the Western guy here is revealed. A lost wife, a lost chande for happiness, a lost chance to express feelings, to repair what was not really so broken... and all the remorse that comes with it... A constant reminder of how nothing in our lives can be predicted: falling sick, overcoming it, and suddenly, an abrupt end just when you thought life was showing you its sweet face again... A story of how a real pain can help to erase an unnecessary, self-inflicted past pain and dream of a future... This is a very emotional film, a film to learn from for sure (or more specifically, to study again what I tought was a lesson learned for me and indeed I was starting to forget), a film that hurts, seduces and in the end provides hope, where remorse for the past ends up providing light for the future, easing the wounds that seemed ready to bleed forever...

So well, after watching it I decided to check some reviews, expecting to read how much this work had moved and touched others... but to my surprise most comments were really negative, bordering the insulting... Pretentious, sappy, empty... well, all those are calificatives that could not be further from my experience with this film... then, it's up to you to decide, believe what some cool Cannes critics say, or believe what this boring, uneducated moron says.

Saturday 17 November 2018

Capharnaum

I watched Capharnaum in the American Cosmograph some days ago. When I decided to attend the session I was not particularly excited. The review in the monthly program was good, but not particularly outstanding, but as Lebanon and its chaotic society is always an appealing topic for me I thought I should watch it (also, Toulouse is no longer my primary residence and when I'm there I pretty much feel like going for some indy cinema).

I was just blown away by this masterpiece. Maybe this is the best film that I've watched since Incendies. It's amazing how a handful of artists (this film is ART in uppercase) can transform misery and suffering into beauty and hope, because the daily fight of the SURVIVORS portrayed in this masterpiece is so inspiring. This film is so profoundly humane that really helps us keep alive the humanist inside us. When many of us are fed up of many of those so called refugees that are not escaping from any war (is there a war in Morocco or Albania? ), that were persecutors rather than persecutees (all those that helped the Islamists in Syria and are now fleeding cause hopefully they've lost their bloody war), and just come here with the intent to take as much as they can from our society without providing anything (anything positive I mean) in exchange... it's really good to show the lives of real refugees, people who have lived in the shit for decades (I won't enter to discuss the so difficoult Israel-Palestine affair, but Palestinian refugees living in Lebanon experience a life of misery and hopelessness like few others), and how they fight day after day for their subsistence. It's also good to be exposed to the fair amount of dignity in those migrants like the Ethiopian or Filipino women that work so hard to try to build a better life in such a harsh country like Lebanon. With this kind of migrants there is no doubt about how fucked up their previous lives had to be in order for them to choose such an uncertain path. They are not doing it hoping to live on social benefits for the rest of their lives... like some of those coming to Western Europe in the last years.

The refugee/migrant kids and women in this film are the personification of courage, dignity and solidarity, a solidarity among the poorest where religion, skin color or ethnicity do no exist, just human beings fighting together for survival. These are the migrants that I would love to see replacing all the Islamoracaille that is tearing apart our societies from inside at the same time that they steal from it as much as they can.

Tuesday 30 October 2018

Jamal Khashoggi

I'm pretty upset with the murder of Jamal Khashoggi, particularly with the reaction from Western countries. OK, maybe you're a bit bewildered now, wondering what's the problem, whether it's that I think that he had deserved it or whether it's that I would expect a much stronger reaction from Western governments. Well, neither of them. For sure it's terrible that a repressive government murders an innocent, but well, it's something rather common... In this case, the murdered person was just an average guy, I mean, he was not a humanitarian worker, a human rights activist or nothing of the sort, he was just a journalist that was slightly critical of the hideous Saudi kingdom, so well, I see no particular reason to pay more attention to this victim than to any other "average" victim.

Anyway, for sure I'm pretty happy with any kind of punishment to the Saudi bastard kingdom, whatever is prompting it. What bothers me so much is that all these years we've had so many much more important reasons to attack Saudi Arabia, and I don't mean just at an economical level, I mean many good reasons for sending the military and burning the whole country to ashes... and we've done nothing, on the contrary, our governments have continued to do business with them, allowing them to persist in their aim to destroy our civilization.

Since 1979 the Wahabist kingdom has been spreading all over the world their sickening fanatical vision of how society must work, trying to subdue our free societies to their Islamic vision. They have been the main factor in the "reislamisation" of the second generation of migrants in countries like France, and hence the main responsible for the communitarism, the oppression of women and not muslims or "not muslim enough" inhabitants in the neighbourhoods controled by the islamists, the increase of rapes, homophobic and antisemitic attacks (most of this kind of violence in Western Europe comes from "rigorist" muslims), the increase of criminality... Just note that for "radical" muslims the "non-believers" have no rights, so we can be robbed, extorted, raped or killed without any moral problem... So Saudi Arabia has been attacking us for decades and our governments have continued to do business with them as if nothing were happening, and suddenly the murder of a journalist (by the way, a guy that that though allegedly "a moderate muslim" was still a supporter of the Muslim Brotherhood and a good friend of the Erdogan IslamoFascist beast) has prompted this reaction!!! What the fuck?

Sunday 21 October 2018

Class Properties and Arrows

The other day I came across a piece of TypeScript code that confused me a bit. In a class definition, among normal method definitions, there was a line like this (the "oddThing" declaration):

class A{    
    
    public normalMethod(msg:string):string{
 //whatever
    }

    public oddThing = (msg:string):string => {
        //whatever
    }
}

So, what is that arrow function doing there? Well, it's called class properties and at some future version should make it into standard javascript. So we are declaring a property and initialising it inline, rather than in the constructor (something very common in C# or java). So that declaration is equivalent to doing this in the constructor:

constructor(){
    this.oddThing = (msg:string):string => {
        //whatever
    };
}

In the end, that declaration and inline initialization is pretty normal for data, but what seems odd is why to do that for a "code block" rather than just using a normal method definition?
Well, the idea is pretty clear if we think about the big difference between arrow functions and normal functions (that is what is used for normal methods), the value of "this". While in "normal functions" "this" is dynamic and depends on the object used to get the function and invoke it, in arrow functions "this" is static, it's bound to the function at the moment of the declaration (similar to doing a Function.prototype.bind). So if we intend to use "oddThing" mainly by passing it around (think of callbacks, event listeners...), and not through an instance of the class where it's defined, using this property declaration instead of a method is a good option (or we could just create a closure trapping the intended this or use "bind").

I've put some code together:

class Formatter{

    public format3: (string) => string;

    constructor(private txt1:string){
        //equivalent to what we do with format2
        this.format3 = (msg:string):string => {
            return this.txt1 + msg + this.txt1;
        };
    }

    //normal method
    public format1(msg:string):string{
        return this.txt1 + msg + this.txt1;
    }

    //class property assigned to an arrow function rather than using a method 
    public format2 = (msg:string):string => {
        return this.txt1 + msg + this.txt1;
    }
}

let formatter1 = new Formatter(" || ");

let formatFn = formatter1.format1;

console.log(formatFn("hi"));
//so PROBLEM, "this.txt1" is undefined

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

//we could use the typical closure trick to trap the intended "this" (formatter1)
formatFn = function(txt:string):string {
    return formatter1.format1(txt);
};
console.log(formatFn("hi"));

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

formatFn = formatter1.format1.bind(formatter1);
console.log(formatFn("hi"));

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

formatFn = formatter1.format2;
console.log(formatFn("hi"));

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

formatFn = formatter1.format3;
console.log(formatFn("hi"));

//output:
// undefinedhiundefined
// ----------
//  || hi || 
// ----------
//  || hi || 
// ----------
//  || hi || 
// ----------
//  || hi || 

Update 2019/05/10By the way, this technique is perfectly valid in C# assigning lambdas to a field/property. In C# you can assign lambdas to a field/property, but that lambda can not use "this", the compiler will spit a "this" is not available in the current context error.

class Person
{
 public string Name = "aa".ToUpper();
 Func NameToUpper;
 
 public Person(string name)
 {
  this.Name = name;
  this.NameToUpper = () => this.Name.ToUpper(); 
 }
 
 //does not compile:
 //"this" is not available in the current context
 //public Func NameToUpper2 = () => this.Name.ToUpper(); 
}


Wednesday 17 October 2018

Symphonies of Salvation

I grew up as a person (I got into it at my late teens, so my physical growth was mainly done) as part of the punk-HxC scene. On the music side, I enjoyed most of its different subgenres, with particular interest first in GrindCore and then in Crust, Screamo and its different derivates/hybridations. On the social/political one, it greatly helped to shape the person that I am now (from my critical/questioning attitude to my food habits). Around 2003 I began to grow disenchanted with many of its social/political aspects, and that disillusionment moved me away from the music styles themselves. I started to dive into pretty different sounds, like extreme electronics, post-metal, post-rock and more and more social rap.

In the last months I've gone through quite a lot of personal stuff, and somehow I've ended back into many of those bands that were so important to me in the late 90's, and they've helped me a lot, as they had done at that time. I've also been discovering many new bands, their "successors" we could say, but that will be the topic for another post. I've got hooked again with 90's French screamo, mainly Ananda, Undone and Anomie (I absolutely recommend these amazing posts giving a so complete retrospective of that scene. As it had happened 20 years ago, walking along that path of emotional, intense French sounds necessarily led me again to its dark reflection to the other side of the Atlantic, those Canadian bands that explored the darkest boundaries of the genre, Union of Uranus and One Eyed God Prophecy (Drift do also deserve a special mention). It's hard to explain to what extent the person that I was in my early twenties got trapped into the magic sounds of One Eyed God Prophecy, and it's been beautiful to see how the so similar and so different person that I'm now in my early forties has got mesmerised again by those same sounds. Life is a constant battle against different enemies, and bands like this give me now the strength that they gave me in the past, some medicines never expire.

In the late 90's we were not exposed to the overdose of information that universal access to internet has made possible, and at that time I hardly had any data about OEGP. Searching information about them I've felt quite surprised when seeing that not much has been put up about them (or Uranus) in these 2 decades... which is due to the rather shocking fact that they are not considered a particularly cult/foundational band by good part of the current screamo scene. It seems really odd to me, and it's funny to read this interview to Orchid (a later band seen by many as a cult band) stating We were obsessed with One Eyed God Prophecy and all the Per Koro bands and were trying our hardest to rip them off.

This said, I've come across an amazing 3 pieces retrospective about Acme, Uranus and One Eyed God Prophecy. The choice of these 3 bands as the major representatives of new HxC punk sounds that would continue to grow and evolve over the next 2 decades all over the planet is really appropiate. However, I have to say that though I love Acme and I still get goose bumps in the rare occasions when I listen to their 7", I would have chosen another band to accompany Uranus and OEGP in that podium, maybe His Hero is Gone.

Saturday 6 October 2018

Tear Down the Bastille

As you well should know in the unlikely case of being an avid reader of this blog, I love Paris and consider it the most beautiful city in the world. Walking along the left banks of the Seine facing the Louvre on the other side in a dark winter afternoon is an almost magical experience for me. However, you can also find some ugly pieces of architecture. Some of the most hated buildings in Paris from the last decades are the Tour Montparnasse (that I love), and the Pompidou Centre (that I don't dislike). Most people do also deeply hate the high-rise appartment blocks that you can find in some areas of Paris intra-muros, like Italie 13, les tours de Orgues de Flandre, Front de Seine, and some other mid-rise housing states in the Belleville/Menilmontant area. Well, I have to say that I quite like those areas. For sure, save for some of the ones in Front de Seine, the architecture of these tower-blocks is not remarkable, but they add architectural diversity and reference points.

It seems like in the last years the Louis Vuitton Foundation (I have not seen it in person yet, but I guess I'll pretty like it) and the new Holy Trinity Ortodhox Cathedral (it quite disappointed me, indeed I think I prefer the old, Alexande Nevsky one) have become new targets for the dislike of Parisians and visitors alike.

In my last visit to Paris I came across one construction that since my first visit quite caught my eye for its ugliness. Over the years, this impression has not improved, I'm talking about Opera Bastille. This building looks really ugly to me, probably in other location it would not look so bad, but in the middle of Paris it really stands out.

Reading the wikipedia article I've learnt that it was part of the Grand Travaux of the Francois Mitterrand era. I thought these "Grand Travaux" had been just the Louvre Pyramid, le Grand Arch de la Defense and the Biblioteque Francois Mitterrands, 3 works that I absolutely love, but the article lists some more projects. One of them, the Ministry of Finances, is not particularly appealling to me, and the another one, The Arab World Institute, I just hate it, not for its architecture, but for what it is.

City of so many contrasts, when going from Bastille to the Seine I came across one very nice and unexpected surprise, Le Bassin de l'Arsenal.

Tuesday 11 September 2018

Mixin and Compose

While thinking of a possible design I came up with an idea that seemed interesting to me. I was thiking of having a main class and organizing additional behaviours in objects to be used as mixins. We would create instances of the main class and add extra behaviours by combining them with different mixins as we saw fit. OK, nothing out of the ordinary, the interesting part is that some of the behaviours (methods) I would not just want to add them, but to compose them (create a new method that calls to the other methods).

What I mean is that if I have a class with a method "process", and I mixin with one of its instances some object that also has a "process" method (we have a collision then), we would end up with a new "process" method that invokes both methods. Probably this is not the generic behaviour that we want for our mixins and collisions, in other occasions we would want the last "process" method to be added to override the previous ones, or maybe just throw an error, but for some situations it's a behaviour that makes quite sense.

So I've cooked a mixinAndCompose basic implementation and sample:

class Particle{
	constructor(position, velocity){
		console.debug("Particle constructor");
	}

	evolve(){
		console.debug("Particle updates position based on velocity");
	}
}

//animation logic to be "mixed in"
const alphaAnimateLogic = {
	initAlphaAnimate(minAlpha, maxAlpha, currentAlpha, initialDirection){
		this.minAlpha = minAlpha;
		this.maxAlpha = maxAlpha;
		this.currentAlpha = currentAlpha;
		this.initialDirection = initialDirection;
	},
	
	additionalMethod(){
		console.debug("additionalMethod: " + this.currentAlpha);
	},


	evolve(){
		this.currentAlpha++;	
		console.debug("Particle updates alpha values");		
		this.additionalMethod();	
		
	}
}

//bouncing logic to be "mixed in"
const bounceLogic = {
	initBounce(xLimit, yLimit){
		//...
	},
	
	

	evolve(){
		console.debug("applying bounce logic");
	}
};

//---------------------------

function mixinAndCompose(target, mixinObj){
	for (let propName of Object.getOwnPropertyNames(mixinObj)){
	 	if (typeof(mixinObj[propName]) == "function" && typeof(target[propName]) == "function"){
			console.log("composing: " + propName);			
			let targetFn = target[propName];
			let mixinFn = mixinObj[propName];
			target[propName] = function(...args){
				targetFn.apply(this, args);
				return mixinFn.apply(this, args);

			};
		}
		else{
			console.log("adding: " + propName);				
			target[propName] = mixinObj[propName];
		}
	}
	return target;
}


let particle = mixinAndCompose(new Particle(), alphaAnimateLogic);
mixinAndCompose(particle, bounceLogic);
particle.initAlphaAnimate(0,10,0);
particle.initBounce();
console.log("--------");

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

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

particle.evolve();

This strategy to deal with mixins in collisions could also make sense in some occasions for collisions in Multiple Inheritance

Saturday 8 September 2018

Victimist Asshole

I had forgotten to post about this issue at the time the controversy broke out, but I think it's still worth to write here some lines of disdain for this very visible example of an immigrant that rejects to fully integrate and embrace the society that has given him everything he has.

Ozil is (apart from an asshole) a German football player of Turkish descent that has quit the German national team because he says to be "victim of racism and discrimination". He claims that when the team wins he's considered a German, but when they lose people consider him a Turk. If that were true that would be horrible, but that's not true at all. The criticism to this idiot started after he showed up on TV smiling and shaking hands with the Turkish fascist president Erdogan. As we all know Erdogan is an enemy of the Western civilization, an ultra-nationalist Islamist that among many other crimes denies the Armenian genocide, massacres the Kurds, funds and promotes the Islamists and asks German citizens of Turkish descent not to integrate in the European culture and be ready to be a "Trojan horse". Obviously, having such kind of friends have made many people in Germany to openly criticice Ozil and think that he did not deserve to be part of the German team. I assume it would have been the same if he had shown up with a poster of Adolf Hitler. Showing appreciation for an assasin like Erdogan should have caused the immediate exclusion (now and forever) of Ozil from the German team.

Rather than showing remorse for his actions (he even refused the requests from a free-speech organization to speak out agains Human Rights violations in Turkey), this piece of crap has tried to turn the persecutor into victim (why is it that Muslims are so prone to do so?). The guy that supports a discriminatory leader (Islamism and ultra-nationalism are the mother of all discriminations) says that he is a victim of racism (from the so evil German society that accepted his parents in the country and provided him with health care and education...) It's just disgusting...

The Ozil bastard has tried to sort out things by saying that he has 2 hearts (a German one and a Turkish one). I've said it before, if you are born, raised and educated in a country that has treated you as one more citizen, I can not understand the obsession with "the land of your ancestors". It's normal and OK that you have a certain feeling for the land of your family, but considering that as the basis of your identity seems so stupid to me... It's so deterministic, you are what your ancestors were, not what you choose to be??? Regarless of how stupid this "split heart" thing seems to me, of course it's up to each individual to decide which is his identity, but for sure, if he intends to represent/defend one country (either by playing in the national team, joining the army...) he must have a single loyalty, which is clear not to be the case for the Ozil rat.

Friday 7 September 2018

Mandela's Nightmare

I guess when someone thinks about South Africa the main things that come to mind are the sickening Apartheid system of the past, Nelson Mandela and the current crazy levels of insecurity, gangs violence and murder. Maybe you have also read about how after the end of Apartheid the pressure from Financial Markets prevented the ANC from carrying out effective social policies, and on the contrary forced them into a privatisation campaing that is at the root of the failure of this African nation. One could think that the race unequality has been replaced by class unequality.

Watching this documentary one learns that racial tensions and segregation have been getting worse and worse in the last years, but this time it's the "white" population who is suffering racism. It would be wrong and unfair to just say that wealth has changed from white hands to black hands. A huge majority of rich South Africans are "white", and "whites" continue to be a majority in companies high ranks and land ownership. But this said, we've seen an explosion in the number of "whites" living under poverty levels and being dragged into shanty towns. This has been caused by the stupid "positive discrimination" policies forced upon by the government. Companies are obliged to prioritize the hiring of "black" employees. Probably this new color of discrimination is not having too much effect in highly qualified jobs as there are not many "black" candidates, but for lower positions, it's doing almost impossible for many "whites" to find a job and pushing them into poverty.

Poverty is equally sad whatever the color of who is suffering it, and race/ethnic supremacy is equally disgusting whatever race or ethnicity is endorsing it. Now, it's "Black"/African supremacy what is on the rise, thanks to the EFF anti-white racist party. We can see in the documentary how some "Black" rappers-criminals are also preaching hate against "whites", advocating for assaulting them and grabbing their lands. This is not just some theorical crap, "white" farmers are being attacked all over the country. As a response, "white" communities are closing over, and the dream of a multicolor/multiethnique South Africa seems now as far away as during the old Apartheid times. Mandela's dream still waits...

Thursday 23 August 2018

Function Currying

The other day somehow I came across some discussion about Currying. Currying in computer programming is a confusing technique, first because quite a few times the term is wrongly used for referring to Partial Application, and second, because I've always found it pretty difficult to find it any use (contrary to Partial Application, that for sure can be pretty useful).

After some thinking I've managed to envision one use case for currying, and indeed it has led me to do a sort of variation over the normal currying. I'll show it here. If you want an explanation of Currying vs Partial Application, you can for example check it here.

Lodash provides a curry function, but anyway I've written my own basic implementation:

function curry(fn){
 let args = [];
 let originalFunc = fn;
 let argsNum = fn
 return function curriedFunc(arg){
  args.push(arg);
  if (args.length >= originalFunc.length){
   return originalFunc(...args);
  }
  else{
   return curriedFunc;
  }

 }
}

And now the difficult part, coming up with one case where currying could be useful!
Well, let's say that I have a function "retrieveAndProcess", that takes care of retrieving items one by one (through a "getNextItem" function), and then passes all those items to a second function "processItems". The thing is that our main function does not know how many items "processItems" needs. So our main function contains a loop that calls to getItem and processItems until this second one returns the processing result, rather than a function. This "curried" processItems is a closure that can keep the different items that it receives until that it gets all the ones that it needs and can process them all at once. Let's see an example:

function* userDataGenerator(){
 yield "Francois";
 yield "Toulouse";
 yield 42;
}


function format(name, city, age){
 return "My name is: " + name + ", I live in: " + city + " and I'm " + age;
}


function getUserDataAndFormat(formatFunc){
 let generatorObj = userDataGenerator();
 let formattedData = curriedFormatFunc(generatorObj.next().value);
 while(typeof formattedData == "function"){
  formattedData = formattedData(generatorObj.next().value);
 } 
 return formattedData; 
}

let curriedFormatFunc = curry(format);
console.log("Formatted user data: " + getUserDataAndFormat(curriedFormatFunc));

After writing that sample I realised of a variation of function currying that could be useful. Let's say that we have a function that can work with a variable number of parameters (imagine we had an Array.prototype.sum). It could be interesting to create from it a curried function that works for a specific number of parameters. For example I have a function that calculates the average of any number of items, and I want to create a curried version that will work for just 3 elements. Let's see what I mean:

//expects a function that can work with a variable number of parameters 
//and returns a curried version that will work for a concrete number of parameters (argsNum)
function curryWithMaxParameters(fn, argsNum){
 let args = [];
 let originalFunc = fn;
 if (argsNum === undefined){
  argsNum = fn.length;
 }
 return function curriedFunc(arg){
  args.push(arg);
  if (args.length >= argsNum){
   return originalFunc(...args);
  }
  else{
   return curriedFunc;
  }

 }
}


function* ageGenerator(){
 yield 10;
 yield 12;
 yield 14;
}

function average(...args){
 return args.reduce((it1, it2) => it1 + it2) / args.length;
}


function requestAndCalculateAverage(averageFunc){
 let generatorObj = ageGenerator();
 let averageAge = averageFunc(generatorObj.next().value);
 while(typeof averageAge == "function"){
  averageAge = averageAge(generatorObj.next().value);
 } 
 return averageAge; 
}

console.log("testing currying for a given number of parameters");

let curriedAverage3ItemsFunc = curryWithMaxParameters(average, 3);
console.log("average age: " + requestAndCalculateAverage(curriedAverage3ItemsFunc)); //12

Friday 17 August 2018

Paris Futur

I love cities and architecture and though I have to admit that I have a rather particular taste, the fact that I consider Paris as the most beautiful place on earth does not deviate so much from standard liking. Anyway, apart from my obvious fascination with historical Paris, I find also an enormous delight in modern Paris. One could think it boils down just to La Defense, but there are quite a few more interesting planned, new, recent or relatively recent, modern developments in Paris. For example I pretty much appreciate the Biblioteque Francois Mitterrand, the modern, mid-rise buildings in the Rive Gauche and Batignoles ZACS (notice also that both ZACs are crowned up with one/two skyscrappers) and of course, the so disliked Tour Montparnasse (it seems like years ago it ranked second in a web poll about the ugliest buildings in the world). I absolutely love how majestic it looks isolated in the middle of classic, Hausmannian Paris, a reference point visible from anywhere in the city. I admit that its dark, "sad" exterior is not its strong point, so finding out that the tour is going to be fully revamped has been pretty nice news (moreover considering that in the last decade several conservative candidates to the mayor's office had proposed to demolish it...). You can read here that Montparnasse will get a vegetalized, transparent facade, and will even grow 18 meters thanks to a greenhouse on its top!

Searching more information about it I've come across an excellent site referencing some of the main new architectural projects in Paris, Paris Futur. I already knew about many of the projects shown there, but it's really nice and convenient to have them listed together in the same place. La Defense continues to thrive, with the construction of 2 new skyscrappers already started (Tour Hekla and Jardins de l'Arche), and other 2 projects almost ready to start (tours Sisters and the new headquarters for Total). On the other side, high rise buildings in Paris intramuros continue to be controversial to say the least, and the opposition of different groups of rednecks continues to hinder the construction of the amazing Tour Triangle. There's one project that is not mentioned in ParisFutur but that has managed to defeat the "Anti-Tour" opposition and is well under construction, Les Tours Duo by Jean Nouvelle. Right in the border with Ivry sur Seine, but still inside the Peripherique!

Monday 6 August 2018

Task.Run in JavaScript

Web Workers have been for sure a great addition to Javascript, but its usage has always seemed a bit odd to me. So you create an "execution unit" (the spec does not say if it'll be implemented as a threat or a process) from a js file that contains the code for that execution unit, and communicate with it via messages. So these messages should prompt the worker to run some action which result will be returned to you via a message. Comparing it to other environments, one could think of this as if each Web Worker were a ThreadPool of a single thread to which I send actions. This is fine, but I felt as if there was an scenario that was missing.

My first experiences with threads (in C#, like 15 years ago) involved creating a Thread object and passing to it a function object (a delegate). That code would be run by the thread and the thread would finish. This is quite close to how things work at the OS level with the CreateThread Win32 API. Creating Threads on your own this way is no longer recommended in the .Net world, as thread creation is expensive and we should leverage the Thread Pool. Task.Run provides us with a familiar "interface" (we pass it a delegate to be run), leverages the thread pool and furthermore returns a Task, so we can easily chain the next code to run (via ContinueWith or even better with await).

Let's say that I don't care that much about the code running in the ThreadPool or in a new one, what I really like is the "interface" provided by Task.Run: pass the code to run as a function and await for its result. So, could I somehow replicate it in Javascript? A web worker receiving a function to be run and returning a Promise on which I could await. Hopefully yes, we can do it

There are some ingredients that we have to mix to make this possible:

  • We have to create a Promise
  • We have to create a Web Worker and pass it a function via postMessage. The Web Worker should run this function. We can not directly post a function to the worker, so we'll pass it serialized into a string, and then the Web Worker will run it via eval
  • Once the function is finished, the Web Worker has to resolve (or reject) the Promise

The code for the Web Worker itself is pretty simple, in principle we'll put it in a separate "WebWorkerCode.js" file and pass its url to the Worker constructor

//e is an array with 2 elements: the function in string format and an array with the arguments to the function
onmessage = function(e){
    let fnSt = e.data[0];
    let args = e.data[1];
    
    //we need the () trick for eval to return the function
    let fn = eval("(" + fnSt + ")");
    let workerResult = fn(...args);
    console.log('Posting result back to main script: ' + workerResult);
    postMessage(workerResult);

}

Then we have a class (PromiseWorkerHelper) with a run method. The "constructor" creates a worker that waits for us to post it the function to execute. The "run" method creates a Promise, gets hold of the resolve/reject handlers of the Promise and posts the function to the worker. Once the worker finished with running the function will post a message with the result, that will be received by PromiseWorkerHelper that at this point will resolve the promise.

class PromiseWorkerHelper{
    constructor(){
        //one shot object, we create it and invoke its run method just once
        this.alreadyCalled = false;

        //this.worker = new Worker("WebWorkerCode.js");
        this.worker = this._createWorkerFromString();

        //this is executed when the worker posts a message
        this.worker.onmessage = (msg) => this.resolveFunc(msg.data);
        this.worker.onerror = (msg) => this.rejectFunc(msg); 
        this.resolveFunc = undefined;
        this.rejectFunc = undefined;
    }

   

    run(fn, ...args){
        if (this.alreadyCalled){
            throw "already used once";
        }
        this.alreadyCalled = true;

        let pr = new Promise((resolve, reject) => {
            this.resolveFunc = resolve;
            this.rejectFunc = reject;
        });

        this.worker.postMessage([fn.toString(), args]);
        return pr;

    }

   _createWorkerFromString(){
        let workerOnmessageHandler = function(e){
            let fnSt = e.data[0];
            let args = e.data[1];
            
            //we need the () trick for eval to return the function
            let fn = eval("(" + fnSt + ")");
            let workerResult = fn(...args);
            console.log('Posting result back to main script: ' + workerResult);
            postMessage(workerResult);
        
        };

        let str = "onmessage = " + workerOnmessageHandler.toString() + ";";
        let blob = new Blob([str], {type: 'application/javascript'});
        return new Worker(URL.createObjectURL(blob));

    }
}

The "_createWorkerFromString" private method is a nice addition. Rather than having the worker code in a separate file, we can have it here, create a Blob, create a URL for that in memory object and pass it to the Worker constructor. I learned this trick here

We can run it as easily like this:

function longFormatting(txt, formatCharacter){
    console.log("starting longFormatting");
    let res = formatCharacter + txt + formatCharacter;
    start = Date.now();
    while(Date.now() - start < 1000){}
    console.log("finishing longFormatting");
    return res;
}

function main(){
    document.getElementById("launchCalculationBt").addEventListener("click", async () => {
        console.log("Main.js, inside button handler");

        let txt = "hello";
        let formatCharacter = "---";

        let promise = new PromiseWorkerHelper().run(longFormatting, txt, formatCharacter);
        
        let res = await promise;

        console.log("Main.js, result: " + res);

    });
}

window.addEventListener("load", main, false);

I've put the code in a gist, and you can run it from here (check the debug console for the output).

Notice that we are passing to the run method the function and the parameters to that function, while Net Task.Run receives just the function. In .net if our original function expects parameters we have to create a closure to trap those parameters and invoke the original function with them. In JavaScript, as in the end we have to pass the function as a string to the Worker, the closure is not an option.

Wednesday 1 August 2018

Well Done Denmark

It seems like there's still some hope for those resisting islamisation. Today, August 1st, a law that forbids wearing the burqa or niqab in public spaces has come into force in Denmark. The Scandinavian country joins France, Belgium, Austria, Latvia, Bulgaria... (you can read a listing here) in the fight against intolerance and communitarism.

There are many reasons for banning those disgusting face veils from the public space (security, women's rights, religious neutrality...) but the fundamental reason for me is that the burqa and niquab represent a declaration of war against our Western freedoms and lifestyle. A man forcing a woman to wear the full face veil, or a woman that decides to do so on her own accord, are following a fundamentalist vision of Islam where those who are not Muslims, the infidels, are their enemies, that must be converted, avoided or murdered. Such an interpretation of Islam is not compatible with our Western values, and as such, can not be allowed here. Furthermore, as such a symbol of hatred, they must not just be forbidden from being worn, their sale must be forbidden also. Wearing a burqa or niqab is just the same as sporting a swastika, it must be banned and punished.

For those radical Muslims that consider that not being allowed to hide their faces is discriminatory and "Islamophobic", I have a simple solution, EMIGRATE to a Fundamentalist Muslim country, unfortunately there's a broad list of destinations for your choice... Of course, you can also take with you all those "left-wing feminists" that support you right to wear the full veil, sure they will appreciate the freedom that as infidel women they will enjoy in such countries...

Thursday 26 July 2018

View Independent Animations

For some simple animations (squares moving through a scenario for example) one could hesitate between drawing these squares to a canvas or using DOM divs. The animation logic should be independent of the Canvas/Divs, which would be just 2 different views. I've adapted the TweenJS sample that I posted some days ago so that now it can either draw on a Canvas or move divs around. The new sample is here. The top animation is using the Canvas, and the one at the bottom is using Divs.

The idea is simple. I keep the animation logic in an AnimationSystem class that holds a list of the items to animate. requestAnimationFrame will ask AnimationSystem to get updated, which means that it will call to the differen AnimationItems to update its position and draw to the screen. I have an AnimationItem base class and a derived TweenJSAnimationItem that contain all the animation logic, they correspond to the "Model-Controller". They delegate the drawing logic to a View object, so we have a Canvas View and a DOM View. As these View objects have a single function, drawing, I've opted for directly using functions for them, rather than classes. As these functions need state (the canvas context or the DIV being animated) I'm wrapping them in closures. Let's see their code:

//callable interface
interface DrawItemFunc{
    (currentPosition:Vector, size:Number, color:string, alpha:number):void
}


class ViewFunctions{
    //Factory function returning a closure that traps the context, height and width
    static SystemCanvasViewFactory(height:number, width:number, ctx:CanvasRenderingContext2D):()=>void{
        return function SystemCanvasView(){
            ctx.clearRect(0,0, width, height);
        };
    }

    static SystemDOMView(){
        //nothing to do here, only at the ItemView level
    }

    //------------------------------------------

    //Factory function returning a closure trapping the canvas context
    static ItemCanvasViewFactory(ctx:CanvasRenderingContext2D):DrawItemFunc{
        return function ItemCanvasView(currentPosition:Vector, size:Number, color:string, alpha:number){
            ctx.beginPath();
            ctx.rect(currentPosition.x, currentPosition.y, size, size);
            ctx.closePath();
            ctx.fillStyle = color;
            ctx.globalAlpha = alpha;
            ctx.fill();
        };
    }

    //Factory function returning a closure trapping the DOM item
    static ItemDOMViewFactory(domDiv):DrawItemFunc{
        return function ItemDOMView(currentPosition:Vector, size:Number, color:string, alpha:number){
            Object.assign(domDiv.style,{
                //position: "absolute",
                //border: "0.1px solid red",
                backgroundColor: color,
                opacity: alpha,
                left: currentPosition.x + "px",
                top: currentPosition.y + "px",
                width: size + "px",
                height: size + "px"
            });
        };
    }
}

Notice that for the transparency, in the Canvas world we talk about context.globalAlpha, while for DOM items we use the style.opacity property.

For the canvas case, before drawing each AnimationItem via the ItemCanvasView closure, I need to clear up the canvas, this is done by the view associated to the AnimationSystem itself. For the DOM case, as we move items rather than redrawing them, there's nothing to do at the AnimationSystem level.

The AnimationItem and TweenJSAnimationItem contain the animation logic and end up invoking the View closures (pointed by the drawingFunc field).

abstract class AnimationItem{
 currentPosition:Vector;
 size:number;
 color:string;
 alpha:number;
    
 moving:boolean;
 drawingFunc:DrawItemFunc;
 resolveCurrentAnimationFunc:any;

 public abstract update():void;
 
 public draw():void{
  this.drawingFunc(this.currentPosition, this.size, this.color, this.alpha); 
 }
 
 public animate():Promise{
  this.moving = true;
        return new Promise((res, rej) => {
            this.resolveCurrentAnimationFunc = res;
        });
    }
}

class TweenJSAnimationItem extends AnimationItem{
    tweenGroup: any;
    movementTween: TWEEN.Tween;
    tweenStep:number;

    constructor(currentPosition:Vector, size:number=5, color:string="red", 
        alpha:number=1, drawingFunc:DrawItemFunc, logger)
        {
        
        super();
        this.drawingFunc = drawingFunc;
        this.currentPosition = currentPosition;
        this.size = size;
        this.color = color;
        this.alpha = alpha;
        this.moving = false;
        this.tweenStep = 0;
        this.logger = logger;
    }

    public animateDiagonal(endPosition:Vector):Promise{
        this.tweenStep = 0;
        this.tweenGroup = new TWEEN.Group();
        this.movementTween = new TWEEN.Tween(this.currentPosition, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ x: endPosition.x, y: endPosition.y }, 40) // Move to (300, 200) in 1 second.
            .easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => {
                console.log("movementTween completed");
                this.moving = false;
                //cleaning up
                this.tweenGroup = null;
                this.movementTween = null;
                //I think this is not necessary, the engine itself takes care of it once the Tween is finished
                //TWEEN.remove(this.movementTween);
                this.resolveCurrentAnimationFunc();
            });
        
        let growTween = new TWEEN.Tween(this, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ size: this.size * 3, alpha: 0.4}, 20)
            //.easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => console.log("growTween completed, " + this.size)); 

        let shrinkTween = new TWEEN.Tween(this, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ size: this.size, alpha: 1}, 20)
            //.easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => console.log("shrinkTween completed, " + this.size)); 

        growTween.chain(shrinkTween);

        this.movementTween.start(0); // Start the tween immediately.
        growTween.start(0)
        
        return this.animate();
    }

    public animateFall(endY:number):Promise{
        this.tweenStep = 0;
        this.tweenGroup = new TWEEN.Group();
        this.movementTween = new TWEEN.Tween(this.currentPosition, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ x: this.currentPosition.x, y: endY }, 40) // Move to (300, 200) in 1 second.
            .easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => {
                console.log("movementTween completed");
                this.moving = false;
                this.resolveCurrentAnimationFunc();
            });
        
        

        this.movementTween.start(0); // Start the tween immediately.

        return this.animate();
    }

    public update():void{
        if(!this.moving){
            return;
        }

        this.tweenGroup.update(this.tweenStep++);
    }

    //implemente in the base class
 // public draw():void{
    // }

   
}

Notice also that for drawing on the canvas we'll invoke ItemCanvasViewFactory just once, as the same instance of the view closure (trapping the canvas context) will be used by all the AnimationItem's. On the contrary, for the divs animation, each AnimationItem will use a different view closure that traps a different div, so we'll invoke ItemDOMViewFactory once for each AnimationItem in the system.

Sunday 22 July 2018

Energy Dependence

Even the most stupid person in the world can on occasion say something that is correct. That's what happened last week when the Trump shitbrain said that it was ridiculous that Germany was increasing even more its dependence on Russian Gas. For sure that's a very correct statement, though one could wonder why a Putin lover and Europe hater like the Trump asshole would care about such undesirable dependence. For the biggest enemy of Europe (along with Russia and the Islamists) the weaker Europe is the better... Well, Trump is just a psychopathic megalomaniac piece of shit that can say one thing and its contrary with just the seconds difference needed to tweet his brain farts...

This increased German dependence (that unfortunately applies to other Western European countries) on Russian gas is related to the construction of the Nord Stream 2 gas pipeline that will go under the Baltic Sea directly from Russia to Germany. There's already a Nord Stream gas pipeline doing the same, so this will further increase the already worrying European reliance on Russian gas. Depending on Russia is as castastrophic as depending on Islamist countries, indeed, it's even worse. Golf countries are invading Europe by educating and funding Islamists that live or will live here, but this is a relatively slow invasion that we still could easily fight if we had the bollocks to do it (massive deportation of binational Islamists, for life incarceration for the others, and capital punishment for those with links to terrorism). On the other side, if Russia decides to military invade the Baltic or Nordic countries, fighting back would be quite more complicated. Russia is our enemy both in a geopolitical sense and in a cultural sense (while Western Europe is supposed to represent freedom, equality and opennes, Russia stands for ultra-nationalism, conservadurism, racism, homophobia...) and being fully aware of this is essential for the survival of Europe as we know it.

This article gives a pretty good insight of how dangerous this new pipeline is:

If it is built, the EU would become extremely dependent on a single gas supplier - Gazprom, an entity under the full control of Russian leader Vladimir Putin.

Europe already imports 39 percent of its gas from Russia. After NS2, 80 percent of Russian gas imports would be concentrated in one route. In Germany itself, the share of Russian gas would increase from 40 percent to 60 percent.

Beyond Germany, 12 EU member states depend on Russia for 75 percent or more of their gas. After NS2, the level of their dependence would also go up.

Natural gas is supposed to be a bit cleaner than other fossil fuels, but does its slightly smaller environmental effect justify to keep us as slaves of Fascist or Islamo-Fascist states like Russia or Qatar???
The answer is a big NO for me, so:

For sure Europe needs to continue to invest on renovable energies (which clearly involves the somehow despised and forgotten HydroElectric power) but until the illusory day when they can fullfill all our needs, we'll have to continue to burn Polish cheap coal and leverage nuclear power.

By the way, you can watch this documentary about the damned new pipeline

Wednesday 18 July 2018

Equipe de France

If 20 years ago someone had told me how obsessed with race our world would be in 2018 I would have rejected to believe it, but sadly, part of this world is as obsessed with race and ancestry now as it was in the worst times of history. One could think that it's just the fault of the White far-right (Russia, Eastern Europe, Trump, and their satellites in Western Europe), but "Blacks", "Latinos" and the far-left have contributed to this mess in equal doses.

The kind of comments that have been stir up by the victory of the French football team in the World Cup are sickening. It's not just the Far-Right who considers the French team an "African team", but also African and Afro-American "personalities", or the Nicolas Maduro idiot. So some of the African people that complain about racism are as obsessed with race and ancestry as any of the very white "official racists". So for these people a Human being is not free to decide to what society he wants to belong, it's just his skin color or the birth place of his ancestors who determines that, that's all, the individual has no rights, it's only the "race", who has rights... This is revolting.

For the most part I don't give a shit about football, and I have little idea of the feelings of identity of the players of African descent in the French team. Maybe some of them love France with all their heart, maybe others are anarchists and don't care about nations, and yes, unfortunately it could happen that some of them is an "anticolonial racaille" that identifies himself with the country of his ancestors (from which they fled due to poverty) rather than with the country that has provided him with food and education... I honestly don't know, and hence I apply my general rule, if you are born and/or have lived most of your life in one country, and you give no signs of disrespecting that country, you are a citizen of that country, regardless of your physical traits or those of your ancestors. That's quite simple.

Additionally, these "African nationalists" that want to appropriate the victory of the French team based on race and ancestry are missing a huge point. Would these guys have become good players if they had lived in Africa, rather than in France, with the Western welfare state and being trained by French (of whatever color) trainers?

Hopefully, all this crap has brought up some excellent reactions. Benjamin Mendy, from the French football team, came across a stupid tweet from some sport magazine that associated to different players the flag of their alleged "country of origin", he fixed it by assigning the French flag to all of them.


The (born and raised) French Basketball player (born to a Cameroonian father) Nicolas Batum went even further (sorry for my bad translation).

Sorry for my language, but those that say "Bravo Africa for your victory", go fuck yourself!. I proudly wear the blue t-shirt with "France" written on it, I've won several trophies and medals with the French team since I was 15, I sing La Marseillaise, when I am in the USA I cry high and strong that I am French. Then, yes, I have a Cameroonian father and a Cameroonian name, but we all have fought and played for France because we have been born here, we have grown here, we have learnt our sport here, we are proud of having the French nationality. We have won for France, for the French youth that looks at us and aspire to do the same and bear high the French colors. Let's be proud of that. Vive la république et vive la France!

When one sees this growing and deviated obsession with race, the move from the French National Assembly to remove the word race from the French constitution seems particularly appropriate.

Sunday 15 July 2018

TweenJS and Canvas Basic Sample

I've been playing around a bit more with animations on the HTML5 Canvas. While in this previous sample I was doing the basic movement logic myself, for this new experiment I wanted to use some library that would allow me to use easing equations. After some basic investigation I've opted for tweenJS. I'm not animating DOM elements, but shapes that I draw on the canvas, so I needed a library that would accept any object and update its values on request based on the selected movement/evolution logic, and then I would take care of drawing it. TweenJS fits perfectly into this mindset.

As in the previous sample, I'm leveraging the power of async/await to make it simple to launch my animations in sequence. There is not much to explain, just launch your debugger to see the typescript code.

while (true){
        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateDiagonal(new Vector(canvas.width - ((x + 1) * size), size * y )); //endPosition:Vector,);
            }
        }

        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateFall(canvas.height - (size * (y + 1)));
            }
        }

        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateDiagonal(new Vector((x * size), size * y )); //endPosition:Vector,);
            }
        }
    
        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateFall(canvas.height - (size * (y + 1)));
            }
        }
    }

Monday 25 June 2018

Taiwan

Some months ago I read a short text (in a nice book about geopolitics) about the China/Taiwan relations that quite surprised me. I knew that Taiwan as a country was created after the Chinese Civil War, when the losing side, the nationalists, retraited to the island. As part of the Cold War, USA decided to protect the island from an invasion from the mainland, communist China. Ever since China has reclaimed that Taiwan is part of China and there's always been the potential for an invasion. Well, there's quite a bit more to the story.

I used to think of Taiwan as a normal free, wealthy country, with a powerful hi-tech economy and a good standard of living. Their big problem, the fear of a Chinese invasion, would be similar (thought more intense and justified) to the fear that Baltic republics have for a Russian invasion. Well, I was a bit confused. One could say that Taiwan is not a a normal country, because it lacks a seat in the United Nations and basically no other nation (save for a handful of small ones) consider it a country and maintain official diplomatic relations with it (the rest of the world keeps informal relations). This lack of formal recognition is also the case for USA, even if they more or less protect the island from a mainlad Chinese invasion.

There are some key points to better understand this odd situation. What we commonly know as Taiwan officially calls itself Republic of China (ROC), while what we commonly call China officially calls itself People's Republic of China (PRC). So, yes, it seems like there are 2 Chinas... Well, not really... The One Chine Policy basically says that there is a single country of China, but with two governments, the ROC and the PRC. For example the ROC government tends to consider itself as the legitimate government of both Taiwan and Mainland China.

One could think that Taiwanese population would massively support independence save for the fear of being invaded by mainland China, but indeed this is not the case, as many people consider that both Chinas form a cultural unity and they should join together, but of course under a democratic government, not under the pseudo-Communist regime. As this is not feasible, many people support the current situation.

Bearing in mind that Taiwan's flagship companies like Acer and Asus have factories in mainland China, one should think that the relations between both countries are not so bad as they could seem.

Saturday 23 June 2018

The Salafists and the Balkans

I've recently watched 2 very interesting and disturbing French documentaries about the expansion of salafism in the Balkans. La Bosnie-Herzégovine, fief du salafisme européen is not so suprising to me. It explains how the moderate (with many Sufist influences) Islam that was common for Bosniaks (Muslim Bosnian population) was first exposed to the radicalisation disease when Jihadists from Arab countries and Pakistan, Afghanistan and other shitholes (indeed many of them had just finished their "work" in the Afghan war) ran into the Balkans to support their Muslim "brothers" during the collapse of Yugoslavia. After the war, some of these scum bags decided to settle in Bosnia and began to spread their poisonous ideas. Some of them would settle in rural areas and create "salafist villages".

These yihadists played a role, but for sure the main actors in bringing and spreading fundamentalism in Bosnia have been the Golf countries and Turkey, that have built new mosques managed by imported or reeducated radical Imams and have funded "cultural associations" aiming to push Bosniaks into fundamentalist Islam. This is clearly seen in the documentary, with the "hispter salafists" leafletting on the streets and the caritative associations helping the poor to buy their acceptance.

This documentary was like the appetiser, the main dish is served by this other documentary, Bosnie, Serbie, Kosovo, les nouveaux territoires de l'islam radical. This is an excellent report. It starts with Bosnia, and shows an even more worrying portrait. The drift towards a much more strict interpretation of Islam can be clearly felt on the streets. It's not just a matter of the increasing presence of women with niqabs and men with the salafist dress code. Now many bars have stopped serving alcohol, the Halal market (not only for the soaked in suffering meat) has just exploded, and the socialization habits are changing. The part that surprised me a lot is that part of these changes are also due to the country having become a tourist destination for the middle classes of the Golf countries. Huge touristic villages (well, they are planning a city for 100.000 people) made up of secondary residences for Arab families are springing up like mushrooms. It makes sense, if you are a devote Arab family and want to enjoy a green, mountanious landscape (even ski sports) in a place where your strict moral views won't be disturbed, a place desperate for investment like Bosnia seems ideal (adjusting their secular Islam to a more rigorist one is just a compromise). It's particularly sad to see in this documentary how the huge radical mosques funded by Saudi Arabia are full of "believers", while a Sufi mosque preaching a tolerant and moderate version of Islam is almost empty...

Seeing how Arab investment is shaping (destroying) the present and future of Kosovo was not surprise to me either, but what shocked me is the influence of radical Islam in Serbia and Montenegro. Come on, Serbia!? a country that represents slav "culture" at its most (Orthodox Christianity, nationalism, conservadurism...), that during the wars against Bosniaks and Kosovars made of ethnicity and religion a huge factor... Well, to my surprise, there's a region stretching over the borders of Bosnia, Montenegro and Serbia, Sandjak, where there's a huge percentage of Muslim population, that is also being exposed to fundamentalist views. Odd that the Serbian authorities allow salafists to proselytize on the streets of its main city, Novi Pazar.

Sunday 17 June 2018

Climate Engineering

I've recently watched a pretty good documentary about Climate Engineering (the deliberate and large-scale intervention in the Earth’s climate system). I came across with the Spanish version, "Un Clima Mecanico" (not sure about the English title), but there seems to be quite a few other documentaries on this topic.

I thought the idea of voluntarily changing the climate or the weather for someone's benefit lied mainly in the realm of fiction (let's exclude Global Warming, that could benefit a few people at the expense of the rest of us), but indeed it was already done by the USA during the Vietnam War, in the Operation Popeye. Furthermore, it seems like the Soviet Union used to artificially clean up the skies of Moscow for the May 1st parades, amazing.

Modifiying the local weather for one or several days seems scary (causing huge storms that can damage crops, flood cities...) but modifying the climate would have a global effect, and that's terrifying. If you modify the climate to do your country more rainy others will become drier, and the same goes for the temperatures. Conflicting entities would end up in a traditional war... The documentary shows how the Soviets had a crazy plan for melting the Artic to benefit of its resources, it's sad to see that they just had to wait a few decades to let Global Warming do the job for them.

For the moment, Climate Engineering remains such a dangerous and conflictive topic that apparently governments are not supposed to promote research on it... but well, who knows what is really under the surface...

Agriculture 2.0

This documentary about Vertical Agriculture is just amazing. I used to think of "Urban Agriculture" mainly as a nice hobby with a social component. If you live in a flat in a city you need to be a bit lucky to enjoy that hobby. The options are:

  • You have a balcony (relatively common in France, totally uncommon in Asturies) and you can grow there a few tomatoes, strawberries and even have a small orange tree in a pot.
  • The building where your flat is placed has some sort of private garden (rather common in France, very uncommon in Asturies) and the neighbours have agreed in setting a growing area. This could also happen in your building's roof.
  • Some neighbours association has agreed with the city council to set up some growing area in some park or unused space (this happens sometimes in France, is unknown to me in Asturies).

Well, all the above is cool, but has nothing to do with the documentary. This documentary is about how to set up agricultural facilities in towns that would really help to feed the town regularly (with veggies that in many cases do not grow in the city's climate), not just a neighbours lunch. City space is rare and expensive, so the idea is taking the conventional greenhouse to its version 5.0! You can start by hanging up if possible different layers of growing veggies in one container and then move to setting multistories plantations. You can also skip using soil and move into Hydroponics. The concept envisioned by one Swedish entrepreneur where a building would be used for office space and agricultural space is beautiful.

What amazed me the most is how by fully controlling the weather in your container: temperature, light, humidity... you can grow anything maximising its nutrients and taste. If you know that certain harvest a certain year in a certain place was particularly tasty, and you have access to the weather patterns in that place that year, you can be close to replicating it. Agriculture is becoming the new IT freaks realm!

When in October 2016 I was travelling by train from Amsterdam Airport to Rotterdam I felt totally amazed by the huge extension of modern greenhouses. These had nothing to do with the ones covered in plastic that are so important in Southern Spain, these were glasshouses, like the ones in a botanical garden, but on a massive scale. This shows up in the documentary and happens to be called Westland.

Tuesday 22 May 2018

Async/await with Animations

Years ago I had fun coding an animation matrix (the sample has been moved here). Most cases involved a sequence of animations, each one starting after the previous one had finished. It was one more case where I had to simulate an asynchronous loop, where at the end of each "iteration" I would callback into an "orchestrator function" that would launch the next iteration. I realized that now that we have async/await, this could be done in a much more straight forward way, so I've prepared some sample code.

For the kind of animation that I'm doing it would have been more simple to just animate divs rather than drawing squares on a canvas, but lately I've been playing around with particle systems on a canvas, and I've preferred to continue with the canvas route.

Whatever item we are animating, the thing is that starting the animation should return a Promise that will get resolved when the animation completes. For this sample I'm animating a square that falls from the top to the bottom of the canvas and bounces a couple of times until it stops. You can see it here. The code (yep, I've jumped into the TypeScript trend) looks like this:


abstract class AnimationItem{
 currentPosition:Vector;
    endPosition:Vector;
    moving:boolean;
 resolveCurrentAnimationFunc:any;

 public abstract update():void;
 public abstract draw():void;
 
 public animate():Promise<void>{
  this.moving = true;
        return new Promise<void>((res, rej) => {
            this.resolveCurrentAnimationFunc = res;
        });
    }
}


//in our child, concrete class:
    public update():void{
        if(!this.moving){
            return;
        }

        this.ySpeed += this.gravity;
        //this.logger.log("speed: " + this.ySpeed + ", pos:" + this.currentPosition.y + ", " + this.acceleration);
        this.currentPosition.y += this.ySpeed;
        if(this.currentPosition.y >= this.endPosition.y){
            //let's place it just in the limit
            this.currentPosition.y = this.endPosition.y;
            if(this.bounces > 0){
                this.bounces--;
                this.ySpeed = -1 * this.ySpeed/2;
                this.logger.log("bouncing: pos:" + this.currentPosition.y + ", speed: " + this.ySpeed + ", " + this.acceleration);
            }
            else{
                //stop it
                this.moving = false;
                this.resolveCurrentAnimationFunc();
            }
        }
    }

So we have an animate method that returns a newly created Promise and stores in our class a reference to the resolve handle of this Promise. The update method takes care of updating the position of the object and resolving the Promise once the final position is reached.

I'm animating several of these items (rows and columns), one after another. With the power of async/await our code is so simple as just writing normal loops like this:

for (let y=0; y<2; y++){
        for (let x=0; x<3; x++){
            let item:AnimationItem = new FallingSquare(ctx, 
                new Vector(x * size, 0), //currentPosition:Vector, 
                new Vector(x * size, canvas.height - (size * (y + 1))), //endPosition:Vector,
                0, //speed:number, 
                size,
                "red",
                logger);
            
            animationSystem.addItem(item);   
            await item.animate();
        }
    }

I've uploaded along with the transpiled and bundled javascript file the original typescript source code and the source map, so to see the full code just launch the debugger!