Sunday, 25 January 2015

A War to be Won

Well, I want to write a long post about the tragedy of January 7, but I've not managed to take the time for it, so for the moment I'll just mention here some interesting material concerning the war against madness that our society is waging on, this war between civilization and Wahhabism/Islamofascism or whatever you want to call that scum.

Continuing with my obsession with the fight of the Kurdish Socialists against ISIS, this short Documentary about Syria's Stalingrad depressed me, enraged me and inspired me in equal parts.

This documentary about the threat of ISIS to Lebanon is scary and depressive. That fucking scum seems willing to destroy any place in the Middle East where different religions have managed to coexist for centuries. Why don't they invade Quatar, Saudi Arabia or any other of those Medieval Kingdoms? Ah, yes, because that scum has been funding them with their petrodollars for years... The position of Hezbollah is quite interesting, they don't want to act against ISIS in areas populated mainly by Sunnis in order to prevent those actions from igniting internal tensions. Such a demonized "terrorist group" is now the main defender of Christians and Coexistence in the Region...

While in Montpellier this weekend I came across this nice poster:

Finally this ducumentary about al-Qaeda in the Islamic Maghreb is a real must (unfortunately it's in Spanish) for anyone interested in the history of madness. It tells the story of Islamofascism in Algeria, that I think is a topic that is quite unknown. In my case it was not so unknown, I already knew about the atrocities conducted by the Islamic Salvation Front and related groups, and along with Jomeini's dictatorship they helped to make me develop a deep fear and hate for fundamentalist Islam many years ago. Well before September 11 these beasts were planning to crash a plane against the Eiffel Tower and were committing attacks in French soil, and well before ISIS they were massacring villages, slaughtering pregnant women and kidnapping young ones.

Sunday, 11 January 2015

AsQueryable

The discussions as to whether Repositories should return IEnumerable or IQueryable has been hot and present for a long while. There are pros and cons, and I don't think I can add anything particularly useful on what path to follow. However, if you decide to go the IQueryable path, I've found something of some interest related to it.

One problem with returning IQueryable could seem to be, "and what do I do with my Mocks?" The typical case is having some mock repositories returning List<Entity>, so what can you do to comply with that contract that expects IQueryable<Entity>? Well, the BCL itself provides all you need, so no effort required, all you have to do is invoke AsQueryable in your collections and your normal IEnumerable will be turned into an IQueryable!

Seems interesting to take a fast look at how this thing works, but first let's do quick recap of how the different Linq flavours work.

  • Linq to Objects is implemented as just a set of extension methods in the System.Linq.Enumerable class.
  • As discussed in this previous post, the Extension Methods for Parallel Linq are located in the System.Linq.ParallelEnumerable class.
  • The Extension Methods for IQueryable are located in the System.Linq.Queryable class (that along with the other classes is located in the System.Core assembly)
  • As explained in this old post (time flies...) an IQueryable Linq Provider is based on implementing Sytem.Linq.IQueryProviderT> and having in your Sytem.Linq.IQueryable classes a Provider property pointing to it and an Expression property referencing to an Expression Tree that represents the Query (this means that when you chain Linq calls on an IQueryable, this Expression property will be the composition of those queries).
  • The IQueryable<T> interface implements IEnumerable<T>. If you have a class implementing IQueryable but want to use the Enumerable methods on it you can just call the Enumerable.AsEnumerable extension method (or just do a casting, that is just what that method does, as we know Extension Methods resolution is purely done at compile time). When you do this with your DataBase related IQueryable collection you'll be losing all the Sql construction magic that you LinqProvider probably implements under the covers, and you'll end up with a "select all" query and the filtering will be done in that huge in memory collection. Sometimes you need this cause you have a complex query and can't write a Expression Tree for it or your Provider can't convert it into SQL statements.

So, what happens when you invoke AsQueryable (that is an Extension Method in the System.Linq.Queryable class expecting an IEnumerable parameter)?

Well, it can not be too complex. The IQueryProvider provided by the new IQueryable object will receive an expression Tree representing the query, so it occurs to me that if it keeps a reference to the IEnumerable object, it can compile the Expression Tree into a normal delegate and use it with any of the System.Linq.Enumerable extension methods.

Let's go a bit through the Framework code (out of habit I still feel more comfortable going through the decompiled classes shown by ILSpy that using the Reference Source code...) to see how it is implemented. AsQueryable returns a System.Linq.EnumerableQuery object. Same as some objects implement both IEnumerable and IEnumerator (they know how to iterate themselves), this class implements both IQueryable and IQueryProvider (it knows how to query itself). As MSDN says:

Represents an IEnumerable collection as an IQueryable data source.

This EnumerableQuery object contains a reference (the Enumerable property) to the original IEnumerable object. When we invoke "Linq queries" on it (the System.Linq.Queryable extension methods), they'll retrieve the provider (that in this case we've seen that is the EnumerableQuery object itself) and will invoke the CreateQuery method on it (source.Provider.CreateQuery), that in turn returns another EnumerableQuery object. As we do so, the Expression tree for the current Query is composed to the Expression Tree representing previous queries, this way (extract from System.Linq.Enumerable.Where):
return source.Provider.CreateQuery(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[]
	{
		typeof(TSource)
	}), new Expression[]
	{
		source.Expression,
		Expression.Quote(predicate)
	}));

Finally, when the data represented by this query is really needed, the GetEnumerator method in EnumerableQuery will get invoked:

private IEnumerator GetEnumerator()
{
	if (this.enumerable == null)
	{
		EnumerableRewriter enumerableRewriter = new EnumerableRewriter();
		Expression body = enumerableRewriter.Visit(this.expression);
		Expression>> expression = Expression.Lambda>>(body, null);
		this.enumerable = expression.Compile()();
	}
	return this.enumerable.GetEnumerator();
}

which will finally compile and execute that Expression that has been composed all over the chain of queries.

Tuesday, 30 December 2014

As Above, So Below

In my first trip to Paris, back in January 2009, I spent a few hours visiting the Catacombs. It was OK, but probably was the only thing in that trip that didn't meet my expectations (while for all the rest, I'd never imagined that Paris would be such a fascinating place for me). I'm not saying the Catacombs are not worth a visit, but I would put it way after many, many other things in a Parisian "to see" list.

However, they have worked as the backdrop for 2 pretty good horror films, Catacombs, and As above, so below. It's the latter why I'm writing this post (I watched the former some years ago and have not much to say at this time).

"As above, so below" is one of the best horror/thriller films I've watched in a long while. This is one of those found-footage, hand-held (well, head-held for good part of the film) kind of films, which at first put me a bit off (I loved The Blair Witch Project, but usually I prefer a more classic filming approach), but in the end seemed quite appropriate for this work.

I've called it a Horror film, but indeed it spans over some other genres, like (archaeological) adventures and thriller. The plot is quite original and straight forward (don't expect some complex twist or different possible interpretations) and the pace is quite frantic, making a really effective production. At first I was expecting that the causes of the horror would be "natural" ones (getting lost in that maze, maybe some crazy folks...) but after a while it will move into the terrain of the supernatural, which at first disappointed me a bit, but turned out pretty well. I find this film pretty fresh, having nothing to do with the "haunted house", "possessed person" or "evil child" kind of horror that so repetitive and ineffective has turned in the last years.

To sum up, if you want something fresh and powerful that will keep you glued to the screen from the first to the last minute, just go for it.

Sunday, 28 December 2014

Metaprogramming, Reflection and MOP's

Metaprogramming, Reflection and MOP's (Metaobject Protocols) are some of the most interesting topics in Computer Science that I can think of. The idea of a program inspecting itself and modifying itself is for sure beautiful. The specific meaning of each of these terms can be a bit confusing though, and the borders and relations among them rather blurry. My understanding has changed a bit over the years and I think it's good to write here my current view on it.

When reading this excellent and very in depth article about Metaprogramming in ES6 with Proxies, I felt a bit confused by the notion of Reflective Metaprogramming exposed there and its different subparts. It was a bit different from how I used to think of Reflection and Metaprogramming and their different classifications, so I've been doing some reading to clarify this nomenclature and taxonomy.

Metaprogramming is a wide topic, and from the Wikipedia entry we can read:

Metaprogramming is the writing of computer programs with the ability to treat programs as their data. It means that a program could be designed to read, generate, analyse and/or transform other programs, and even modify itself while running

so Reflective Metaprogramming deals with the itself (analysing, transforming and even modifying itself while running)

Reflective Metaprogramming is indeed what I'd always called just Reflection. However, the way I used to subdivide it is a bit different, while Axel Rauschmayer talks about:

  • Introspection: you have read-only access to the structure of a program.
  • Self-modification: you can change that structure.
  • Intercession: you can redefine the semantics of some language operations.

I used to think in these terms (obviously is not something invented by me, I had read it years ago in some book, copy-pasted it in my personal notes and stick to it):

  • Introspection: same as in the above classification, the ability to ask for the type of an object, the methods of a type, its parameters...
  • Structural Reflection: the ability to access properties or invoke methods based on runtime decisions, and even creating new classes (runtime metaprogramming). To a greater or lesser extent most languages possess this feature. In .Net for example it has evolved from the initial Reflection API to the current Roslyn superstar, going through LCG and the DLR.
  • Computational Reflection. This would be a way more complex beast. It would include things like modifying the semantics of a language, from how method resolution and invokation is done or how property or indexed access is performed, to adding new constructs to the language at runtime (yes, crazy stuff like adding new types of loops...). I used to see this related to the existence of a MOP.

The terms Structural Reflection and Computational Reflection don't seem to be particularly popular (you'll find some references along with Behavioral Reflection), so I'll try to change my mindset and use the ones given by Axel Rauschmayer in the future.

The another big and confusing topic is the MOP. Everyone seems to have a different idea of what a MOP is, so I'll give first some definitions that I've found over time:

From StackOverflow

The MOP exposes some or all internal structure of the interpreter to the programmer. The MOP may manifest as a set of classes and methods that allow a program to inspect the state of the supporting system and alter its behaviour. MOPs are implemented as object-oriented programs where all objects are metaobjects.

From Wikipedia

A metaobject protocol (MOP) provides the vocabulary to access and manipulate the structure and behavior of objects. Typical functions of a metaobject protocol include:

Creating and deleting new classes
Creating new methods and properties
Changing the class structure so that classes inherit from different classes
Generating or modifying the code that defines the methods for the class

The metaobject protocol is contrary to the "closed" aspect of Bertrand Meyer's open/closed principle. It reveals and allows a system to modify the internal structure of the objects. For this reason it is usually used sparingly and for special circumstances such as software that transforms other software, for example for reverse engineering.

From Moose Documentation

A meta object protocol is an API to an object system.

To be more specific, it abstracts the components of an object system (classes, object, methods, object attributes, etc.). These abstractions can then be used to inspect and manipulate the object system which they describe.

It can be said that there are two MOPs for any object system; the implicit MOP and the explicit MOP. The implicit MOP handles things like method dispatch or inheritance, which happen automatically as part of how the object system works. The explicit MOP typically handles the introspection/reflection features of the object system.

All object systems have implicit MOPs. Without one, they would not work. Explicit MOPs are much less common, and depending on the language can vary from restrictive (Reflection in Java or C#) to wide open (CLOS is a perfect example).

The distinction done above between implicit and explicit MOP is unclear to me. The way Java or C# handle inheritance is hardcoded and there's not an API to modify it (excluding dynamic C#). There's not API for intercepting method calls or property access (other than creating proxy objects), there's no methodmissing/aoutoload/nosuchmethod, no way to modify inheritance chains or inheritance behavior... All in all nothing to do with the power found in Groovy

Groovy's MOP system includes some extension/hooks points that you can use to change how a class or an object behaves, mainly being:
getProperty/setProperty: control property access
invokeMethod: controls method invocation, you can use it to tweak parameters of existing methods or intercept not-yet existing ones
methodMissing: the preferred way to intercept non-existing methods
propertyMissing: also the preferred way to intercept non-existing properties

And finally from the article by Rauschmayer

The ECMAScript specification describes how to execute JavaScript code. It includes a protocol for handling objects. This protocol operates at a meta level and is sometimes called the meta object protocol (MOP). The JavaScript MOP consists of own internal methods that all objects have. “Internal” means that they exist only in the specification (JavaScript engines may or may not have them) and are not accessible from JavaScript. The names of internal methods are written in double square brackets.

Notice how in ES6 if you want to alter the way property access or method invokation works you can not directly alter the [[GET]] internal method of an object, but to create a proxy and set a get trap. While the article praises this separation between the base level and meta level, I see some disadvantages on it. In Groovy, you can directly alter "the protocol" of an existing object by just adding or redefining its invokeMethod method, so all your references to that instance will get the new behaviour, in JavaScript you would have to update all your references to point to the proxy instance rather than the proxied one. For me this means losing transparency.

So you can see different perspectives on what a MOP is.Iinspired by the article when it says "The term protocol is highly overloaded in computer science" I guess we can say right the same for MOP, it's highly overloaded. I'll give now my own practical definition of what a MOP is:

For me a practical definition of a MOP would be any support (in the form of some sort of API) given by a language in order to modify how property access, method invokation or inheritance work.
Less advanced topics like the way to add new methods or properties (expand) to an existing class or instance, or modify the inheritance (or prototype) chain would be part of that MOP.
More advanced features like modifying/expanding the syntax of the language, changing how exceptions propagate, how loops behave (think for example of a calling a method that would turn all or certain loops into parallel loops), changing methods from sync to async, making those methods memoize results, throttle... would also be part of a MOP.

Thursday, 25 December 2014

Paris Street Art, December 2014

In this previous entry after a weekend breakaway in Paris I said I had not come across much Street Art there if compared to Berlin, but it was probably cause I had not been in the right area. This weekend I was lucky to do another short escape to Paris right before Christmas, and had my hostel in an area that I had read somewhere that could be considered like the Parisian Kreuzberg. I'm talking about Menilmontant-Belleville, an area in the juncture of districts (arrondissements) XIX and XX. Well, it's not Kreuzberg/Fridrieschain cause France is not Germany, and in spite of globalisation (the good parts and the bad parts) cities with such a character and history still manage to keep a big degree of uniqueness. Anyway, there were some moments where I really had a sort of "I'm in Berlin" feeling (lots of left-wing political posters, stickers and slogans on the walls). Something that really helps to it is coming across with pieces done by Artists which works I'm used to find in Berlin.

I found this piece by Alias in Rue Belleville:

this work by Alice in Montmartre

and 2 impressive "small" murals by a genious (with socio-political motivations in most of his works) called Alaniz. This beautiful Arab woman face:

and this "young artist" one:

His style seemed familiar to me, so searching on the net it made quite sense to find that he's based on Berlin, and that some impressive works that remain in my mind from strolling around Berlin, are indeed his creations.

Notice that on the top right of the Arab woman you'll see one of those omnipresent "it's time to dance" paste-ups, that though particularly everywhere in Berlin, are indeed the product of French artist, SOBER.

If you're into Urban landscapes, the point where Canal St Martin and the elevated M2 tracks cross will quite delight your eyes. The similarity with places like KottbusserTor in Kreuzberg is quite clear. I found there a really good work denouncing the drama of child soldiers.

I love the elevated Metro stations around there. The design is almost a clone of those in Berlin; I don't know when these stations were built, but I assume it was well before the EU dream started (however incomplete it is and wrong things have been done, 70 years of peace between European countries is like a dream), so at a time when the French-German relations were pretty bad (as always throughout history save for the last 50 years)... so it's interesting to see how elements of both cities were developed following the same patterns.

I quite liked this "Urban Angel" paste-up:

And obviously pretty enjoyed this Antifa mural

One form of Street Art that is "very French" is painted vans and trucks (I've seen quite a few in Toulouse, but they're everywhere in Paris). In too many occasions it's just ugly Street Crap, but you can find beautiful pieces like these:



I could continue to add pictures here for a good while, but I think it's time to end the post, so will just add this cute tree:

Kurdish Obsession, December 2014

I can't really understand the lack of any real support to the war against ISIS. On the government side, the air strikes are just a bad joke, just a strategy of deception to keep calm that small part of the population that are really horrorized by the drama being lived in Irak and Syria. Without troops on the ground (and that means many troops) there's nothing to do. The negative of Western powers to put troops on the ground there really makes me sick, politicians do not want to go through the trouble of seeing some of those troops coming back in coffins, it won't play nice for the next elections. Sure the idea of sending Westerns to die there is painful, but it's much more painful to see how women and children are enslaved by ISIS terrorist (on a different topic, I can't understand why the media continue to call these beasts "militants", they are real TERRORISTS, and not the PKK fighters), men get their heads chopped off, and the most interesting experiment in social transformation in the last 50 years, Rojava, is kept under attack. As for the "drama" of sending our "guys" to die in a foreign war... well, this is not a foreign war, this is a war against Humanity, and if someone enlists in the army it should be clear to him than dying in combat is one of the chances he faces, it's part of the job.

As for the normal population, this lack of support is deeply revolting. While in 2003 there were massive movilizations against the war in Irak, now we've hardly seen anyone on the streets urging the Government to fight this monstrosity. Well, in the end it makes sense, most people is unable to go beyond the dichotomic views they were instilled with. So basically violence and war are bad, regardless of whether they'll be use to colonize and oppress other people or to try to save other people from oppression and brutality, so a politically correct person can not demonstrate in favor of a military intervention, cause military interventions are always bad... Society of idiots.

It can be quite shocking that I could agree with anything said by Marine Le Pen... but the other they she reminded us in an interview in Euronews (I'm not linking it, I don't want to give any further publicity to the FN) how absurd is to be in a coalition against ISIS with the states that have been funding radical Islam for decades (yes, all those IslamoFascist medieval kingdoms: Saudi Arabia, Quatar... you name it)

Hopefully, as already shown in previous posts, there's a small portion of our society that is aware of this drama and are trying to raise awareness. These are my last street findings in France/

Financial support for Kobane in Toulouse:

And different stickers and posters in Paris, in an area quite full with Antifascist "propaganda":





Parc des Buttes-Chaumont

Paris has such an incredible architecture that at this point, after having enjoyed on several occasions of the main jewels that make up the European Treasure (Prague, Vienna, Budapest, Lyon...) I would dare to say that it's the most beautiful city on earth (sorry for this act of treason, my beloved Prague and Vienna :-D Visiting right before Christmas is maybe one of the best occasions to enjoy its beauty in all its magnificence. Walking along the river banks on a cloudy day, from Notre Dame to the Eiffel Tower, with a Seine flowing dark because of the last rains, a cold but bearable temperature (6 degrees, below that it means pain for me)... buff; those are memories that get intermixed with dreams. Sure France is renowned worldwide for its taste for fashion and perfumes (not that I'm any interested on that...), but in this year living here I've also realised that their taste for many other things like gardens or chocolate is supreme. So being here in Christmas you'll also learn that their taste for Christmas lightning is astonishing (it's pretty nice in Toulouse, but in Paris is just outstanding, those "trees on fire" in Champ Elysees are impressive).

There are so many things to see and that compete to take the first positions on any tourist guide that probably the place I'm recommending in this post does not rank particularly high, but is a must do (at least for your second visit to Paris). The Parc des Buttes-Chaumontis one of the most beautiful urban parks that I can think of. I like it even more than Primrose Hill in London, that for years has been my favourite. This park has several artificial hills, one of them being an island in the middle of a cute artificial lake. This island is crowned by the Temple de la Sibylle, a beautiful and "melancholic" viewpoint. There are also some cascades (they are off now due to restoration works that intend to do the ecological footprint of the park much lower) and 2 bridge giving access to the island, one of them a suspension bridge that will slightly move under your feet when walking along it (designed by the very Gustave Eiffel)

Right in front of the main entrance to the Park you'll see the building of the Mairie du Quartier (the Hall town of the district), typical French Architecture that you find here in every corner, but that in my hometown would be top of the top.