Sunday 29 April 2012

Hooked on Deutscher Rap

I knew almost nothing about German rap until a few days ago (my knowledge was just limited to having heard that there are some rather good GermanTurkish MCs). The thing is that almost by chance (you know, you're watching some other stuff on youtube and end up clicking on one of the related videos on the right...) I've came across a good bunch of pretty interesting German rap acts. Let me advise you that unfortunately I don't speak German, so I can't understand the lyrics and I base my assumptions about their lyrics on the visuals and some other articles I've found (most of them also in German, so read through google translate...)
There are some excellent Left wing artists, like Boycott, Holger Burner and Albino (Animal rights lyrics)
Then I came across this Serbian-German MC, Toni der Assi (the associal). Even now, 20 years after the Yugoslav armageddon started, the general opinion seems biased by the media propaganda of those (and present) times. Western Media depicted Serbs as the only ones to blame for the disaster in the Balkans... I believed that partial view for many years, but I no longer buy it. Reality is much more complex than the 5 minutes analysis portraited by those few mass media that we even dare to consider objective, all sides in the Balkans got their hands deep in blood, there were monsters on every side, and above all, the ultimate responsible for the disaster were outside the Yugoslav borders (NWO...). Well, I'm digressing again, don't plan to do a history post here...

The thing is that I find very inspiring the attempts of this Balkan guy to try to get over the hatred and distrust between these communities, probably using their shared suffering and trying to focus on the victims and not the guilties (there were both of these in all the ethnic groups)
It's also interesting, cause I'd never really thought before about the conflicts that immigrants from the old Yugoslavia could have among them in their new countries. I remember having seen in Viena a pub called Sarajevo and another one called Beograd, but at the moment didn't think what would happen if the customers of both pubs met in the street, what sort of feelings they would feel for "the others", those that in a matter of a few months had gone from being their comrades to being their sword enemies...

On the flip side, I find terribly disgusting these videos by Albanian gangs:

Well, as I can't understand their lyrics, maybe I'm confused and they talk about profound phylosophical matters, reconciliation and integration... but I would bet that's not the case... I think this "maphia and proud" attitude makes them little favor, but well, there are groups that base their lives and identity in the alleged discrimination and hatred from the others, so if they need to prompt that hatred, so be it...

On a similar note, it's sad to see that in the last years there's been an emergence of Nazi Rap (NS Rap) projects. They share the same "us against you", "us against the differents", "we're victims turned into tough guys" attitude as the above... It sounds hilarious to see these "aryan guys" playin "niggers music", but in this time where our whole civilization seems to crumble... nothing should surprise us anymore...
I'm not going to put links to that crap here, so if you're feeling curious, search it yourself.

Wednesday 25 April 2012

Reflecting on Private Members

The other day one colleague was talking about a JavaScript heavy application on which he was working, and he mentioned that for private members they were using just conventions (the typical "_" or "__" stuff). I much agree with that approach, it's the one I tend to follow and I think it's enough. Anyway, it made me think of those many articles and techniques for simulating private members in JavaScript. All of them boil down to using closures in one way or another, and all of them seem to have some sort of caveat, either you have to add your methods at the instance level instead of at the prototype level or you end up with no way (I think) to declare private instance data fields, that's what happens with my favorite solution, that is this one I found here:

function Restaurant() {
}

Restaurant.prototype = (function() {
    var private_stuff = function() {
        // Private code here
    };

    return {

        constructor:Restaurant,

        use_restroom:function() {
            private_stuff();
        }

    };
})();

The funny thing here is that with this approach we obtain private members rather "more private" than in other languages featuring private members out of the box. Both in C# and Java you can use reflection to invoke, get or set private members. For example, to invoke a private method in C# you would just do something like this:

//first get the method info
MethodInfo method = typeof(Person).GetMethod("BeingCalledBy", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

//know you can invoke this way (in this case if you check the StackTrace from the invoked method, you'll see it invoked by _InvokeMethodFast
method.Invoke(p, null);

//or create a matching delegate and invoke it through it (in this case if you check the StackTrace from the invoked method, you'll see it as invoked by the calling method)
Action action = (Action)(Delegate.CreateDelegate(typeof(Action), p, method));
action();

With JavaScript, I can't think of anyway to access the members of a closure from outside, unless that the closure itself is giving you that access as I explained here

I remember having read years ago a rather stupid story claiming that this was a security vulnerability. Obviously it's not, as Private members are not a security feature, they're just a way to discourage clients of a class from using them because they could change in the future breaking your code. It's the same for example as you should use only Win32 functions, and not the Windows Native API

Pondering about all this, I stumpled upon this question where someone asks whether it's possible to prevent the invocation of a private method via Reflection. Well, thought I don't think one should care about this (as I've said I don't consider it a security feature, so if someone wants to risk to use code that was not intended to be used from outside the class, at your own risk...) I considered an interesting thought exercise. I've figured a rather basic way to do this, fighting Reflection with Reflection!

Simply put, you can know in one method who's invoking it by using new StackTrace().GetFrame, you can also know the list of methods in your class (that are the only places from which that private method should be legally invoked...) so with these 2 things, it's just a matter to do the match

public class MethodBaseComparer : IEqualityComparer {
    private string GetMethodIdentifier(MethodBase mb)
 {
  return mb.Name + ":" + String.Join(";", mb.GetParameters().Select(paramInfo=>paramInfo.Name).ToArray());
 }
 public bool Equals(MethodBase m1, MethodBase m2) {
        //we need something more here, comparing just by name is not enough, need to take parameters into account
  return this.GetMethodIdentifier(m1) == this.GetMethodIdentifier(m2);
    }

    public int GetHashCode(MethodBase mb) {
        return this.GetMethodIdentifier(mb).GetHashCode();
    }
}

class PrivacyHelper
{
 static Dictionary cache = new Dictionary();
 public static bool IsInvocationAllowed()
 {
  Type curType = typeof(T);
  if (!cache.ContainsKey(curType))
  {
   cache[curType] = curType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToArray();
  }
  //StackTrace.GetFrame returns a MethodBase, not a MethodInfo, that's why we're falling back to MethodBody
  MethodBase invoker = new StackTrace().GetFrame(2).GetMethod();
  return cache[curType].Contains(invoker, new MethodBaseComparer());
 }
}

//now, in whatever method that you want to protect you would add something like this:
private string SayInternalSecure()
 {
  if (!PrivacyHelper.IsInvocationAllowed())
   throw new Exception("you can't invoke this private method");

//run normal code here

}  

 }

One of the many problems that I can think of for this (sort of) solution, is that if for some odd reason I wanted to invoke via Reflection (MethodInfo.Invoke) a private method from any other of my other methods, I would also get it prevented, cause invoking through MethodInfo.Invoke, the caller I would obtain would be _InvokeMethodFast, instead of the method that is using the Reflection hack.

You can get the code here

Wednesday 18 April 2012

Street Art in Milan

I spent the weekend in Milan this Eastern, and I was pleasantly surprised. I used to think that Milan was just the Duomo (really impressive indeed) and the Galleria Vittorio Emmanuelle, but there's much more to it. Sforza Castle, Sant'Ambrogio, the beautiful Brera neighbourhood...

There's a good bunch of skyscrappers: the popular Pirelli tower, the lovely Torre Velasca(my uncle, as many other people I guess, hates it, but I find it really interesting, though based on the Lombard tradition, it reminds me of some works by USSR constructivists, like this one or even the Slovak Radio building) and many more (CityLife project) on their way (who said crisis?, judging by all those new glass and steel structures one would think the Italian economy is boosting...)

On one side the buildings and the trams give the city an Austrian touch, on the other side the wide avenue lined by office buildings that goes from the Central Train Station to downtown and the many slim high rise buildings (15 to 20 stories, no glass and steel ones) reminded me of Brussels. Even (though it actualy bears little resemblance) the Park behind Castello Sforza with that nice Arc at the end brought me back memories of the Parc du Cinquantenaire also in Brussels.

I would say that Milan is not by far a Street Art hot spot (at least the city centre is rather lacking in it), but I found a few rather interesting pieces that I'd like to share:

  • Not too aesthetically appealing to me, but it pays tribute to an Antifascist murdered by NeoNazi scum 9 years ago, so it deserves my small homage by adding it here:
  • A typical sentence, but this time with a very original visual representation:
  • Art Nouveau females:
  • And well, being Italy (or Southern Europe for that matter)... the Christian reference could not be missing:

Saturday 14 April 2012

Asturian politics, the largest brothel you've ever heard of

There's an Asturian (and Galician, and Spanish...) expression that says: "X ye una casa putes" (X is a brothel) meaning (sort of) that X is a fucking senseless messy chaos full of corruption (sorry if the expression exists in English and this introduction is unnecessary).

Asturian politics have been a big brothel for decades, with two hyper corrupt political parties (psoe and pp) (managed by illiterate thugs pissing on the idiotic masses that rose them to power) allegedly alternating in power (though in fact they had a covert pact to share power an bounty) and bringing about the total decline of our economy, identity and collective moral. In the last year things got even worse, cause when a new party (apparently rather more respectful and more concerned about the problems or our land) entered the game and overthrew them from power, both parties joined ranks to preclude the new party from governing and force him to call early elections. These elections have been a complete catastrophe, probably the last nail in Asturies coffin, resulting in a far right political party (upyd) being the new key for misgoverning our land... the day after elections I felt deeply ashamed of being Asturian... along with a feeling of frustation and anger that I think not only won't fade with time, but will get deeper and deeper as these ultranationalist far right thieves plunder the country, deny our history and humiliate our culture and collective memory

This said, I thought I should share this hilarious image, if you can't fight something, at least try to laugh out loud at it. In the picture below, we've got a billboard for these last elections (unfortunately it's for one of the few parties for which I hold some respect, but in fact this makes the whole thing even more absurd and surrealistic) surrounded (the green and pink ones) by two adverts for 2 of the most popular brothels in Asturies. Funny and disgusting, isn't it? :-D

Thursday 5 April 2012

CLR vs JVM: Unhandled exception in Thread

There's something interesting that expands a bit this previous post. Since .Net 2.0, when we get an unhandled exception in any of our threads, the whole application is shutdown. This is something that changed from the .Net 1.0 times, and that I was not fully aware of. I think it makes sense, if an exception is unhandled the application should be shutdown, irrespective of whether it runs in the main thread or a separate one. If you want to avoid this, you have to wrap the code in a try catch, but watch out, the try-catch has to be inside the code that will be run in the separate thread, not surrounding the code that launches the thread. That's common sense, exceptions bubble up the stack until they are caught or they get to the top. Each thread has its own stack, so the try-catch needs to be inside the thread, not around it

What this means is that this exception won't be caught and your program will shutdown
class Searcher
{
 public void Search()
 {
  Console.WriteLine("Searching");
  Thread.Sleep(2000);
  throw new Exception("Search exception");
 }
}
class App
{
 public static void Main()
 {
  try{
   new Thread(new Searcher().Search).Start();
  }
  catch(Exception ex){
   Console.WriteLine("Exception: " + ex.Message + " caught by program");
  }
  
  Console.WriteLine("Press 'q' to quit");
  string st = null;
  do{
   st = Console.ReadLine();
  }while (st != "q");
 }
}
On the contrary, your exception here will be caught and your program won't shutdown.
class Searcher
{
 public void Search()
 {
  try{
   Console.WriteLine("Searching");
   Thread.Sleep(2000);
   throw new Exception("Search exception");
  }
  catch(Exception ex){
   Console.WriteLine("Exception: " + ex.Message + " caught by program");
  }
 }
}


class App
{
 public static void Main()
 {
  Console.WriteLine("Main Thread");
  
  new Thread(new Searcher().Search).Start();
  
  
  Console.WriteLine("Press 'q' to quit");
  string st = null;
  do{
   st = Console.ReadLine();
  }while (st != "q");
 }
}

We can easily write a helper method to wrap this in case the method we're going to launch in its own thread lacks the try-catch routine

class ThreadHelper
{
 public static void RunThreadWrappedInExceptionHandling(ThreadStart code, Action catchRoutine)
 {
  new Thread(() => {
   try{
    code();
   }
   catch(Exception ex){
    catchRoutine(ex);
   }
  }).Start();
 }
}

class Searcher
{
 public void Search()
 {
  Console.WriteLine("Searching");
  Thread.Sleep(2000);
  throw new Exception("Search exception");
 }
}

class App
{
 public static void Main()
 {
  Console.WriteLine("Main Thread");
  
  ThreadHelper.RunThreadWrappedInExceptionHandling(new Searcher().Search, 
   (ex) => Console.WriteLine("Exception while searching: " + ex.Message + ", try again")
  );

You can get the code here

There's a fundamental gotcha here. Imagine we're using third party code that in turn is creating its own threads, if they have not adopted measures like ours, there's nothing we can do to prevent an exception in their threads to shutdown our program... Well, I think this is pretty serious stuff, imagine you have and Asp.NEt application that is using some component that creates its own threads. Imagine that you have that application running in an Application Pool along with some other applications (well, at least in principle I always assign a different AppPool to each Application), one failure in that component would be crashing all those applications. Don't think so? check this article

It's very important to note here that the JVM behaves quite differently. As you can read here, an unhandled exception will end the thread were it was thrown, but not the whole program.

This short article explaining how the JVM handles exceptions makes a good read. And the same goes for this article for the CLR. In both cases an Exception Table is used to describe protected blocks and locate the catch-finally code to run if an exception happens (in the JVM there seems to be one table per method, in the CLR one table for the whole executable). It's very important to understand that exceptions do not affect performance unless they occur, I mean, wrapping your code in as many try-catch blocks as you judge necessary won't have any effects performancewise (the only cost it incurs is the addition of entries to that table) until those exceptions begin to happen. It's explained in several StackOverflow questions... This means that you should not be concerned about placing a try-catch inside a loop, the entry to the exception table is added once, not n times

According to msdn:Performance Tips and Tricks you can use try and catch without any performance problem until the real throw occurs.

Wednesday 4 April 2012

Run your compiled Groovy code

I've lost some time today figuring out this, so I thought I would share it in case it can be helpful to someone.
Usually you run your Groovy code just by invoking groovy.exe on it. It takes care of loading your .groovy files and compile them on the fly. If you check the class loader for a Groovy class loaded this way [myInstance.class.classLoader] you'll see it's the groovy.lang.GroovyClassLoader.InnerLoader. This class has a doParse (private Class doParseClass(GroovyCodeSource codeSource) method that seems to compile your groovy class to in memory java bytecodes. If you want to check these bytecodes generated by groovy (it's really important if you want to get some insight on how Groovy does all its magic) you'll need a .class file that you can open with this nice Java Decompiler for instance. You can use groovyc to obtain those .class files.

Let's say we have this CheckClassLoader groovy code

class Person{
 def name;
}

println  "Checking ClassLoader";
p1 = new Person();
println p1.class.classLoader

running groovyc CheckClassLoader.groovy we'll get 2 .class files: Person.class and CheckClassLoader.class, one for each class generated by groovy.

I understand most people use these .class files not for decompiling them, but to launch them faster (you compile ahead of time just once and save all the time groovy spends doing the runtime compilation to bytecodes each time it loads one class...), so, how do you run your .class file generated by Groovyc?

Obviously you just invoke java.exe on it, as you would do with any .class generated by javac. The problem is that you need to add to your classpath the Groovy runtime library (the groovy.exe, groovyc.exe and groovysh.exe already take care of referencing them when launched, so that's why probably you should have never cared about this before...). Well, after some efforts, I finally found this document explaining where to find it, in my case: C:\Program Files\Groovy\Groovy-1.8.6\embeddable\

I'm not much experienced with Java, but I think the modern best practice is not to add things to the CLASSPATH environment variable and pass whatever you need to the compiler or the launcher with the -classpath switch, so I ended up with this:

java -classpath ".;C:\Program Files\Groovy\Groovy-1.8.6\embeddable\*" CheckClassLoader

notice that we have to add the current folder to the classpath, as when using the -classpath all the default classpath values (that includes the current folder) are overriden

When run this way, the class loader for your groovy class is not the GroovyClassLoader anymore, but the normal sun.misc.Launcher.AppClassLoader

Tuesday 3 April 2012

P183, the Russian Blek Banksy

In the last years I've developed a growing interest and appreciation for Street Art (mainly murals, stencil and sticker art). I love some of the aesthetics (thought I rather dislike most of the fat letter graffiti thing) but I mainly love the social message present in many artists (well, be aware that in the last years the new far right has also got involved in the street art world, so part of the street art in Eastern Europe has a message far to be endorsed...).

Also, after reading the "Wall and Piece" masterpiece by Banksy (yes, I don't mind how cool it sounds to say now that Banksy is an overrated copy of Blek le Rat, that he's a no longer cool and so on... for me he's an absolute genius) I pretty much share his philosophy of confronting the consumer "street crap" continuously fed into us through billboards and all sort of media, and his opposition to the "Art from a few" society, where just an elite decides what is beautiful, innovative or worth and should be exhibited in our so democratic museums and art galleries.

I'm not sure whether part of my interest for street art has been sparked off for my devotion for Berlin, or if on the other side it's the omnipresent street art in Berlin what has prompted my fascination for that city. The thing is that I feel more immersed in art when wandering around Kreuzberg or Friedrichshain than when in any conventional Modern Art gallery (yes, even my beloved Tate Modern). I absolutely recommend this excellent book to anyone that wants to learn something about Berlin's street art scene.

The thing is that the other day I knew for the first time about P183, an excellent Russian street artist. Coming from such a conservative country like Russia, where the far right has managed to instill xenophobia and racism into an alarming percentage of youngsters, I'd really like to know more about his political stance (is he just one more anti-Putin guy or he's on the left side?). You can check some of his works here and here.