Tuesday 29 June 2010

Jeniger

Finding this post today has made me extremely happy.

After having been fairly disconnected from the Crust (Classic Crust, NeoCrust, Dark Hardcore...) music scene for several years, my visit to Berlin last year (where unlike other times I found a lot of posters of Crust concerts by new German bands like Unquiet...) restored my interest in Crust.

Back at home I did some myspace research and learnt about the new German (Neo)Crust scene, formed by bands like Unquiet, Alpinist, Finisterre... and then some great memories came to my mind about one the best German Crust records I had never listened, a record that sounded in my now defunct turntable innumerable times in 2002, Jeniger's self titled Lp. I got the Lp from one shelf (where it had remained untouched since I moved away from HardCore, Crust... years ago) I tasted again the magical-awful design, that so well matches the depressive, anguished lyrics...
I tried to find the record to download, but, believe it or not, it was nowhere...
I discovered on the way some great Crust-Hardcore download blogs with some very hard to find records, I found all sort of Jeniger 7 inches (some of them I was absolutely unaware of, other ones were part of my collection, like their first, raw, primitive, delicious, "Disrupt's first rehearsals like" "Drink your tea") but this fucking Lp seemed to have been banished from the digital world.

Today, for some reason, I decided to try again, and YES!!! google (well, the nice guys of Ruin Nation, one of the labels that released the record back in 2002) made my day.

I've been listening to it as I read those incredible lyrics, and it's so great, it brings me great (not so) distant memories that I can combine in my head with things I've learnt since then, and that makes me realize of how we evolve, how past and present embrace each other so that we can dream of the future...

This record is as good as I renembered it. Dark Crust, influenced by His Hero is Gone and the likes, but not too much, it sounds more punk than those bands. Vocals are some of the best I can think of, spitting those dramatic lyrics just in the right place with the right strength. Lyrics are really important for me in this record, they transmit a feeling of desolation, loneliness and despair like few other bands have managed to convey. They absolutely match the music (or viceversa), creating such a gloomy, depressive atmosphere...

FOR THIS TIME
the same old thoughts come to my head when I'm standing at the cliff
always the same question: commit suicide or live
for what it's worth to live in a state of compromise
not doing the things you really want to do
not being able to show your real thoughts and feelings
hold back by your own fears and your surrounding
castrating your personality day by day
wasting time by living in the past and dreaming of tomorrow
the same old thoughts come to my head when I'm standing at the cliff
always the same question: commit suicide or live
suicide or live
the sun is going down
the stars begin to shine
the sea is rolling on
and so do I for this time
but I really don't know why


That song is striking, a punch direct to your face from someone so fucked up to undress his soul so deeply on a paper and then with strength enough to carry on with his life, with his band...

Living an unhappy life in a city you hate, in a society that rejects you as much as you despise her... Feelings of a wasted life from which you try to escape but that seems to walk towards asylum or suicide...
Yes, these topics are fucked, and make me feel bad as they remind me of some of my own miseries, but at the same time are terribly vital, cause if a bunch of angry people that seem so disenchanted with everything are able to create such a piece of pure beauty like this record, then things are much better than we think, and some hope still exists...
Something that had called my attention at the time and has done it again is that they have a lyric that sort of deals with a broken relationship (well, maybe there's some extra metaphor here), that is rather new to me in a crust band:

FOR NO-ONE
where we've lost each other we will never meet again
just starring at each other with bounded hands
sweet melody of death in my ears again
just echos of the past whose sources faded away
I will send you kisses from a foreign land
I will send you kisses with a black rose in my hand


I'm missing an Apfelschorle now.

I've added below a pic with the complete lyrics:

Wednesday 23 June 2010

Singletonize

Since I wrote this post I had in mind if it would be possible to transform a normal "class" in a singleton "class" (I'm thinking in JavaScript here, that's why I'm quoting "class"). Well, maybe it does not look much useful, but it sounds freak enough to be appealing to me.

In principle it didn't seem too complex, but when I started to write it, I found some problems.

Updated on 2011/06/23
Most of what you can read after this paragraph is misleading and based on some misconptions that I had at the time... just jump to this new article.
Anyway, I leave this old article here for historical reasons (and for my own shame :-)



The idea is storing the initial "constructor" somewhere, and return a new "constructor" function that checks whether the singleton instance has been created or not, if not, it calls the initial "constructor".
That's the main problem, invoking a function as a constructor (that is, with new before) is not that easy as invoking a normal function with Function.prototype.apply(...) or Function.prototype.call(...)

I mean, when we invoke:

initialFunc.apply("this", "arguments");

that "this" should be the new object that in a normal invocation (new intialFunction(...);) the new statement would have just created...

I searched the net for some help and in principle it seems like there's not a clear way to do it, except using the almighty eval().

I already knew that eval() runs in the context of the calling function, but hadn't realized of how incredibly important that can be (otherwise it would be rather complex to make the arguments passing work)...

so the main part for this to work is:


var strings = [];

for(var i=0; i<arguments.length; i++)

     strings.push("arguments[" + i + "]");

            

/* as eval runs in the context of the calling function, we can use arguments with no problem */

var code = "new initialFunc(" + strings.join(",") + ")";

initialFunc._singletonInstance = eval(code);



Researching a bit more I found a trick to do this using apply, in fact, it was damn obvious, I just can create the "this" object (that in a normal invocation would be created by the new statement just before the constructor) in a previous sentence, and then pass it to the apply function as its "this".
I mean:


var obj = new Object();
initialFunc.apply(obj, arguments);
obj.constructor = initialFunc;


problem with this is that for some reason the prototype chain does not seem to work Of course it doesn't work, at the time of this article I was terribly confused about how prototype chains are implemented, the functions are not looked up in obj.constructor.prototype or something like that, but in the [[prototype]] that got assigned to obj at creation time, just after new runs and before it gets passed as this to the "constructor" function, so method invocations on the new object created this way fail...

You can find the complete source here

Thursday 17 June 2010

Moscow Death Brigade

I've got a really negative perception of nowadays Russia. Unfortunately (among other things their architecture makes Moscow and Leningrad two incredibly interesting cities to me) I've never had the chance to be there, but I've read enough from different sources to believe my views are sadly realistic...

Sure it's easy to think about their totalitarian government, a political maphia with a total control on media. A gang of cold war educated mercenaries that do not hesitate to cut the gas supply to other countries in the middle of winter, to imprison or murder disidents, to attack Georgia, to attack Estonia, to threaten Ukrainia, to perpetrate ethnic cleansing in Chechnya, to recruit war lords, to starve their own people...

But more than that, it's the "street feeling" what really outrages me... It's a society where xenophobia and racism seem almost genetic, a place where NeoNazis rule the streets with the aid of state forces. A place where having dark skin, slanted eyes... or any other "sign of ethnic impurity" can get you stabbed in the metro by a pack of blood thirsty Nazi Skinheads... a place where going to a Punk concert or collaborating with Food Not Bombs means risking your life. A place where standing against the oppresors can be rewarded with some shoots in your doorway...
There are tons of information on this, but it still seems rather unknown to most Westerns...
I renember how horrorized I felt the first time I read this:

As of 2007, St. Petersburg and Russia in general can be regarded as a seriously dangerous destination for tourists of darker complexions. Travelling in groups is highly advised

in wikitravel, and how much hate and solidarity I've felt each time I've read news like these

But, even when these motherfuckers are now the rulers, opposition exists and resits, a true opposition (with true I mean not an aesthetic trend making you feel rebelious but keeping you empty... but a committed attitude confronting unequalities and unjustice that can bring you real trouble).
Hopefully there's a good bunch of samples, like:

Anna Politkovskaja, Natalia Estemirova, Memorial, Novaya Gazeta...

but what has prompted me to write this post is this great band that I've recently found in the net. Uncompromising antifascist Hip Hop from Moscow. Their music is great, and this extract from their MySpace makes their stance clear:

MDB tells stories straight from their own reality – the reality of modern Russia with its raging poverty, corruption, extreme police brutality, child drug-addiction and bloody race and ethnic conflicts. A reality where the Neo-Nazi hordes murder people in the broad day light and still got the support from the government. A reality where a hardcore or hip-hop gig may end up in a brutal attack of the police or their fascist puppets. A reality where it's hard to survive and even harder to remain true to yourself.
...
MDB gigs on the territory of the former USSR are usually accompanied by the visits of riot cops, bomb threats from Nazis and other fun stuff.


It very much impressed me to see the pictures of their performance in the street, with them and the audience with their faces covered, not doing that way can mean the the Nazi scum tracking you and beating you to death...

Another thing that amazed me was seeing that they had taken part in a benefit show to raise funds for an orphanage for children with disabilities. Shit, I'm used to concerts for raising funds for political actions, squats, autonomous social centers... because usually we take for granted that it's the state (well, all of us) who puts the money for orphanages, but it seems like in the Russia of the oligarchy and the maphia state does not take care of that...

Thumbs up to these artivists, and above all, much RESPECT!!!


Monday 14 June 2010

Closure in a Loop


Closures are one of those things that when you get used to them it seems absurd that a modern language does not implement them (hey java, wake up, it's time for you too...)
They're really important in JavaScript for the Asynchronous Ajax calls and callbacks or the binding of "this" to an event handler.
I've also done good use of them in C#, saving me from having to write "intermediate classes" just to hold parameters to be passed to a method when inside a parameterless delegate... yes, it sounds confusing, this sample with ThreadStart delegate makes it clear, though:



//we have this method that expects two parameters:

public static void Format(string title, string txt)

{

Console.WriteLine( "<h1>" + title + "</h1>"

+ "<p>" + txt + "</p>");

}

 

//and we want to run it in its own thread, but ThreadStart delegate does not accept any parameters, so what? just create a parameterless closure that captures the needed values and passes them on to our method:

 

string s1 = "title";

string s2 = "description";

Thread th1 = new Thread( new ThreadStart(() => HtmlFormatter.Format(s1, s2)));

th1.Start();



How a language implements closures is interesting and bizarre at the same time. Scope chains in JavaScript, auxiliar classes generated by the C# compiler...

Well, I've come across several times with a case that does not work the same in JavaScript and C# and that makes you think about how language semantics and internal implementation shaped this case. It's when you create a closure in a loop.

Let's say we have loop like this in C#:


for(int i=0; i<5; i++)

    actions.Add(()=>print("value = " + i));



or in javascript:


for(var i=0; i<5; i++)

    actions.push(function(){print("value = " + i);});



if now we invoke the functions in the actions array, it's not 0, 1, 2, 3, 4 what we're going (and that in principle would be desired behavior) to obtain, but 5, 5, 5, 5, 5.

This makes good sense in both cases if we think in terms of scope.
In the JavaScript case, the scope for i is the whole function, in the C# case, the whole loop, so in both cases, all actions are capturing the same i variable and all of them see any change done to the variable.
Thinking in implementation terms, if we know how closures are implemented in each language, this makes perfect sense with JavaScript, when each function is declared it captures the execution context object of the function where it's declared, so all these new functions point to the same execution context that contains that i variable.
However, in C# this behavior caught me by surprise. In principle, the compiler generates a class where the method for the delegate and the free vars are stored, so there should be one instance of that class per method and then a different i variable (data field) in each case. I was wrong, in this case an only instance of the class is used, so i is shared.

To obtain the intended behavior, we would have to go this way in C#:


for (int i = 0; i<5; i++)

{

int k = i;

actions.Add(() => print("value = " + k));

}



in this case we're using a new variable k, that is scoped only for each loop iteration, so each closure captures a different k variable.

however, if we do the same in JavaScript:


for (var i = 0; i<5; i++)

 {

  var j = i;

  actions.push(function(){ print("value = " + j);});

 }



we still get the initial results: 5, 5, 5, 5, 5.
This is the right thing according both to semantics and implementation. In spite of being declared inside the loop, the scope for the j variable is the whole function... so this it the same as for the first case. Likewise, from the implementation standpoint, we have an only variable in the execution context of the main function... so that's fine.

So for JavaScript in order to achieve the intended behavior, we need to add an extra function with it's extra scope, execution context:


for (var i = 0; i<5; i++)

  actions.push(function first(it){return function second(){print("value = " + it);}}(i));



when the "second" function is declared, it captures the it parameter passed to the "first" function where it's declared. We have 5 "instances" of the "first" function, each one with its own "it" parameter, that will be captured by the "second" function.

The equivalent c# code would be something like this:


for (int i = 0; i<5; i++)

{

 Func<int, Action> intermediate = it => (() => Console.WriteLine(it));

 actions.Add(intermediate(i));

}



You can check the source code:


Hey, I've got an update to this

Friday 11 June 2010

Some JavaScript Magic

It's not a secret that I consider JavaScript one terribly interesting language. I quite like its Prototype based object orientation and how its enormous flexibility allows us to simulate class orientation. I've got a certain amount of experience with JavaScript and I'm sort of a Language freak (I don't know a word about compilers-interpreters programming, but I'm very much interested in the different features and idioms provided by different languages), but anyway JavaScript continues to wonder me with new pieces of wisdom.
So, I'm going to talk of some of the last ones I've found (or rediscovered) lately:

  • JavaScript closures are one of its more important features. It's very interesting to learn how the [[scope]], execution context, scope chain... work together. Yesterday I found a use of closures that I'd never seen before and really amazed me, using closures for anonymous recursive functions:

    var count = function countToTen(i) {
    if (i <= 10) {
    console.log(i);
    count(i+1); // Call count with the power of closures
    }
    }
    when countToTen is declared, it's [[scope]] property traps the count variable, so when countToTen is executed, it can find count in its execution context.
    as the article says, you no longer need arguments.callee nor named functions (thought anyway, for debugging purposes I think all functions should be de-anonymized)

  • Functions with return values being used as constructors. This is rather interesting. In most languages I know constructors do not return any value. In JavaScript, the concept of constructor not rigid at all, in fact, I think we can say that we don't have constructors, we just have functions, and when a function is called following a new statement it works as a constructor.

    var p1 = new person();

    I think it works this way: new creates a new object, the object gets its constructor [[Prototype]] property pointed to person() and then is passed to person() as this. person does whatever it wants with this and if it does not have a return statement, the new object-this is assigned to p1. Nothing unusual so far. But, what happens if person has a return statement? in that case it's the object returned by the function what gets assigned to p1. This, apart from being a rather freak feature, could not seem way too useful, but for example it could be useful for implementing a singleton pattern this way.
    What I like of that implementation is that the singleton no longer looks like a singleton to the outside world when referencing it. What I mean with this is that instead of the classic singleton.instance... we can call new as many times as we want, and we'll be receiving the same object...
    It's as if the class was no longer expressing in its contract that it's a singleton, is this really a good idea?
    Also, this thing reminds me of __new__ in Python, that is sometimes (ab)used to implement sort of a factory.

  • I really like when something makes you scratch your head, even if it's not especially useful. First time I saw somewhere a JavaScript line like this:
    this();
    it really caught me by surprise.
    Well, it's not that strange (taking into account that functions are objects and as such can be "expanded"), if "this" can be invoked it means "this" points to a function, so if we think how the "this" gets assigned, an example would be just something like this:

    var f1= function(){print("I'm f1");};
    f1.hi = function(){this();};
    f1.hi();

    Thinking around this a bit more it came to my mind how we could write a rather confusing line. Let's say we have a person "class" and we're going to add some "static" methods to it:

    function person()
    { this.name=....};
    //instance methods
    person.prototype.dump = function(){...};
    //static methods
    person.static1 = function(){...};
    //this looks rather confusing, cause having a "this" in a "static" does not seem too natural
    person.static2 = function(){this.static1();}
    //this one looks much more natural way to call a static method
    person.static3 = function(){person.static1();}

  • While checking some more JavaScript code in the web I came across this lazy function definition pattern. It's both simple and interesting. A problem with this is that we're just changing where the reference points to. If we had more than 1 reference to the function object, it would only work for one of them. It would be beautiful if we could replace the code inside the function itself, something like:
    arguments.callee.code = function(){...}.code;
    it would just involve that functions had a code property containing their code itself.

Saturday 5 June 2010

Ordered enumeration

The other day while writing some WSH code (yes, this old, but really powerful, technology is still alive and well, and I guess it will take a very long time until it gets fully replaced by .Net and PowerShell), I came up with something that could be good to share.

I have different scripts each one using a different logInfo "data object" that is passed to a generic logToCSVFile method. It's no wonder that the method enumerates the data fields in the logInfo object and writes a line to the csv file.
So, I need to enumerate these data fields always in the same order (and also get the data fields name, so that each time I create a new log file I write those names as column headers).
I had a problem here:
Traversing a JavaScript object (in the end a dictionary) with for in does not guarantee the order in which items will be returned. Well, in practice it seems it does, but we can say it's an implementation detail, not an interface contract. So, in principle, I can't count on fields being returned in the same order as I added them. Also, it could happen that I would not always add them in the same order... so I definitely need something more...

In C# (and Python) setting the enumeration order would be that simple and elegant as using an iterator block (a generator in Python) letting the compiler generate the Enumerator object for us. (for obtaining the Fields order I had to do some extra code, see the source)



public class LogInfo:IEnumerable<String>

{

    public IEnumerator<String> GetEnumerator()

    {

        yield return this.User;

        yield return this.Computer;

        yield return this.Result;

    }

 

    IEnumerator IEnumerable.GetEnumerator()

    {

        return this.GetEnumerator();

    }

}



but in JavaScript I had to write some more code (well, JavaScript 1.8, implemented in last Firefox versions, provides generators, but that's rather unknown to the %systemroot%\System32\jscript.dll engine used by WSH...) In the end I came up with an object that can be iterated with 2 slightly different for-in constructions:



var orderedEnumerator = function(orderAr, source)

{

    this.order = orderAr;

    this.enumerable = source;

    this.curPos = -1;

};

orderedEnumerator.prototype.get = function(i)

{

    return this.enumerable[this.order[i]];

};

orderedEnumerator.prototype.count = function()

{

    return this.order.length;

};

orderedEnumerator.prototype.current = function()

{

    return this.enumerable[this.order[this.curPos]];

};

orderedEnumerator.prototype.moveNext = function()

{

    if (this.curPos < this.order.length-1)

    {

        this.curPos++;

        return true;

    }

    return false;

};



You can get the code here:

  • javascript (you can easily test it with cscript, rhino or firebug)

  • c# (I've added some stuff to get the "columns order" thing)

Wednesday 2 June 2010

Platform evolution and inconsistencies

It's not easy to evolve a platform, avoid breaking code and being consistent.

So far, one of the main changes undergone by the .Net Framework was the inclusion of generics both at the CLR level and the language level.

With this, we saw the arrival of a common creational idiom:


T Create<T>(){/*implementation here*/}
T myObject = Factory.Create<T>();


so, we can write code like this:


MyType instance = Factory.Create<MyType>();


instead of this


(MyType) instance = Factory.Create(typeof(MyType));
//note the need of a casting due to a method signature like this:
Object Create(Type t){/*implementation here*/}


We have a sample of both styles in Activator.CreateInstance, which among other overloads has:

  • public static Object CreateInstance(Type type) //old style, available since framework 1

  • public static T CreateInstance<T>() //new style, available since framework 2.0


Note that version 1 is not marked as deprecated. That makes some sense due to its dynamic nature. Doing a CreateInstance(otherInstance.GetType) means that we don't need to know at compile time (as happens with the generic version) the type of the object to create. Anyway, we would be returning an Object, and as we could not cast it (cause we don't know what to cast to) it would not be much usable (only through Introspection). In .Net 4, the dynamic keyword would make it more convenient to use.

Today, when checking more in depth the list of new features in .Net I came across something that looked a bit inconsistent to me. We have a new Enum.TryParse that is rather welcome and uses the second style, but when compared with "classic" Enum.Parse that uses the first style, the whole picture looks a bit inconsistent:

Parse(Type, String)
Parse(Type, String, Boolean)

TryParse<TEnum>(String, TEnum)
TryParse<TEnum>(String, Boolean, TEnum)

in this case, given that I don't think that there's any dynamic scenario that needs of a Parse(myInstance.GetType(),...), I believe the best would have been marking the current Parse implementations as deprecated and add 2 new ones:

Parse<TEnum>(String)
Parse<TEnum>(String, Boolean)