Monday, 16 December 2013

Misfits, an underappreciated show

Series poster with the original crew I've just finished the eighth episode of the fifth season of Misfits, the last in the series, as the show finally reached its end. I am convinced that most of the people reading this post don't really know what Misfits is and I mean to rectify that. Be warned, this is not the epitome of television and the last seasons were rather disappointing compared with the first few, but those few were pretty refreshing for a TV show.

Misfits is a British TV show about superheroes. Unlike American heroes, who are all beautiful and good and perfect, the first batch of Misfits superheroes is a bunch of losers on community service that get caught in a freak storm that gives them "powers". They use those powers in the most outrageous ways, completely out of control and with a tendency to think only of themselves and accidentally kill probation workers. Unfortunately it is the most consistent trend through the series, as actors change from season to season and the mood and quality of the show oscillates wildly.

My point, though, is that the show has a very nice premise and its worst problem was that instead of focusing on character development, they tried to ramp it up, adding more people with powers and gradually increasing the danger and weirdness of the situations in which they were involved until it just became ridiculous.

I don't know (or care) about ratings, but for me a nice show would have pitted these few guys against the real world, not a weird (and ultimately meaningless) version of itself where a lot of people have superpowers, but nobody notices. I repeat myself, but the idea of normal blokes and girls having superpowers and acting like normal people while they have them was a great one and the show creators should have followed it through. Too bad they didn't.

To wrap this out, I highly recommend to sci-fi fans watching the first two seasons of Misfits. Its... britishness... brings a refreshing perspective to an already overloaded and tired genre of the superhero and not getting exposed, even a little, to Misfits makes you miss out on a nice and unfortunately shortlived slice of the mythos.

I really wanted to give you a compilation of the best moment in Misfits, but apparently YouTube is infested by "Best funny moments of Nathan" which is the rude Irish pretty boy from the first season. Instead I leave you with the trailer for the series:

Tuesday, 10 December 2013

The Witcher - Nice game, but the story gets drown in silly sidequests

Geralt and his White Wolf medalion You have to appreciate The Witcher for at least two major reasons: one is that it is based on a series of books by a Polish author and second is that it is made almost exclusively by Polish programmers and software managers. It is basically Polish software, and for that the quality is really great. Not that I disconsider software coming from the country, but I imagine they have a lot less resources than major American game studios, for example.

The story is that of a witcher, a monster slayer. He has tremendous physical strength and can use magic thanks to magical and genetic changes that have transformed him into a sterile mutant. He is basically the Caucazian version of Blade, if you want. I have not read the stories, but from what I've heard they are rather morally ambiguous, featuring the witcher drinking and whoring like a madman in between monster slaying bouts. The game attempts to do the same thing, of course with the sex and foul language removed, as it would have been too gruesome among all the blood, gore and violence. (I was sarcastic there, in case you didn't see it, people in charge with the moral development of our society!)

In fact the concept of the game is marvelous: have a character that can make choices that affect the overall story in a fantasy game of feudal monsters and courtly intrigue. However, in order to do so, you must go on endless quests gathering this and that, running around like a marathoner on steroids (which I guess you are, with all the genetic alterations and potions). The poor guy runs so much that one gets tired just watching him move. That was the major issue I had with the game, over 70% of it is running around (and 10% animations).

The fighting style was intriguing, but ultimately annoying. You had to click on the monster you wanted to kill, then wait for a specific moment when the cursor changed in order to click again and perform a combo. Up to six clicks can build a combo, which gives the player a lot of opportunity to click on somebody else, click next to the monster or move the camera in a way in which it is temporarily impossible to fight. Also Gerald does not have automatic fighting, so unless you tell him to attack, he just sits there and takes it. The damn clicks make you feel you are doing something, though, which I guess is a plus.

You get to meet a lot of damsels in distress which you have the option of helping. Once you do that they are remarkably willing to discard their clothes for you. In that situation you get to see... a nicely drawn card of a partially naked woman representing the sexual act. Then you return to where you were... at the same hour... dressed... which makes one think of a problem with the witcher's endurance, so to speak.

The changes in storyline are interesting, and some of them don't seem to happen until they have had time to propagate. This means you cannot just save, make a choice, see what happens and load, as there is a long time between choice and effect. This also means you will have to play the game a lot just to see only one story line. You will probably have to Google for all the outcomes. I, as always, was a perfect gentleman. No matter how ugly that Adda chick was, I still slept next to her... twice... and of course we remained best friends. No, really, there is something seriously wrong with me.

Overall it is a pretty entertaining and captivating game. The end chapter (the fifth, if you are wondering) is fraught with animations and it seems you have nothing else to do but move a bit, see a movie, move a little bit, kill some guy, another movie and so on. The fight with Javed was the most difficult, I think, with the rest a complete breeze once I had upgraded the Igni spell to the maximum power.

I have, however, the certainty that with a simple hack to allow a person to click on the map and get there at warp speed (maybe stop if there is a monster on the road or something) this game would have been three times shorter and a lot more fun. I started with a lot of expectations about it, though, and maybe that is why I felt a little disappointed, especially with the "boss" fights which seemed to involve a lot of talking and hiding behind minions until I got to them and very easily kicked their ass.

Time to play The Witcher II, I guess! I leave you with a video review of the game.



Also, for more information about the Witcher, like the choices you can make and the consequences or the quests you never got around to finishing, go to the Witcher Wiki

Wednesday, 4 December 2013

Launch code for US nukes was 00000000 for 20 years

This is how an US general looks like I tried to find a title with more impact than the title of the original article to express my combination of amusement and disdain; I couldn't. It says almost everything. Apparently, the reason why the nuke codes were reset was that US Strategic Command generals almost immediately had the PAL codes all reset to 00000000 to ensure that the missiles were ready for use regardless of whether the president was available to give authorization.. How insane is that? On the other hand, there is a positive side to all this: it goes to show that you are just as intelligent as an US general when you leave your phone PIN to the default 0000.

Monday, 2 December 2013

Accelerando, by Charles Stross

Book cover Oh, what a wonderful book this was. A cross between a William Gibson and a Peter F. Hamilton book, Accelerando was like a cyberpunk's wet dream. Not only it describes the deep transformations of our culture caused by the increasing power and speed of computation, but it goes further, years, decades, centuries and millennia more. You know the feeling you get when you get close to the end of a book and you sigh "Oh, I wish it would continue to tell the story"? It happens at the end of every chapter. It's like Stross could have ended the book at any point, but he chose to continue the story until its satisfyingly circular end. What is it with writers and the return to origins, anyway? There is an explanation for the structure of the book, as the author originally published each chapter as a separate story.

What is even nicer is that the story doesn't skim the details, showing only superficial bits that further the story, but it goes into everything: cybernetics, economy, ethics, law, the nature of consciousness. It gets frightening at some points when you realize that in the situations depicted in the book reality would be even more carnivorous and that your own individuality (held coherent in the book for the benefit of the reader) is just an illusion we cling to, ready to dispel when we muster the courage (or the insanity) to let it go.

I also liked how, while it was human-centric, the book did not limit itself to one species, nor did it go the way of accelerating (pardon the pun) until the whole story becomes meaningless in some encounter with a God like alien or by complete transcendence. I have to say I appreciate Stross immensely for not doing so, which is the normal and easiest way for a geek to end such a story: by generalizing the hell out of the situation until no particulars make sense. In that, the writer showed real restraint and mature wisdom. It makes me want to read all of his books.

If you want to know what the plot is, you will have to read the book, as I can't really do it justice here. I can tell you that it made me believe in an explosive evolution of the human race in my lifetime more than any Kurzweil discourse and it did it easily, by simple measuring MIPS/gram on the scale of the entire Solar System. If we will run Moore's Law for a few more decades, it will make enormous sense that "dumb matter" is done for. It is a fantastic vision of computation as a devourer of mass, a frightening equation akin to Einstein's matter to energy conversion. Did I mention that it also - convincingly - explains Fermi's paradox, much more so than "we get to build androids for sex", which was the most believable for me so far?

Needless to say it, but I will anyway: go read it, read it now! It is an amazing book. It is a little too pretentious in some parts, when it bombards your brain with technobabble just so it gets you "future-shocked" enough to understand the characters, but what cyberpunk fan doesn't eat that up, anyway? Also the familial connections in the book are a bit too overdone, but then again, they provide the generational point of view necessary to describe centuries of human evolution. There is a page - surprisingly Web 0.9 for such a plot :) - for the book, with an extract from the first chapter, but I don't think it is representative for the entire work.

You can actually read the book online for free, from the author's site: Accelerando

Monday, 25 November 2013

Joining the rows of a table to the best row of another table in T-SQL

This is something I have been hitting my head on from the beginning of my programming career: just find the best match in a table for each row in another table through a single query.

There are solutions, but they are all very inefficient. To demonstrate the issue I will start with a simple structure: tables A and B, having the same columns id, x and y. I want to get, for each point in table A defined by the (x,y) coordinates, the closest point in table B. I only need one and it doesn't need to be exclusive (other points in A might be closest to the same point). It doesn't even have to be one row in B for each row in A, in case there are two points at the exact same distance to a point in A. The creation of the structure is done here:
CREATE TABLE A(id INT PRIMARY KEY IDENTITY(1,1), x FLOAT, y FLOAT)
INSERT INTO A (x,y) VALUES(10,20),(20,30),(20,10),(30,20),(30,20),(10,30)

CREATE TABLE B(id INT PRIMARY KEY IDENTITY(1,1), x FLOAT, y FLOAT)
INSERT INTO B (x,y) VALUES(11,20),(20,31),(21,10),(31,21),(30,20),(11,30)

To find the distance from A to the closest point in B is trivial:
SELECT a.id, 
a.x,
a.y,
Min(( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y )) AS
dist
FROM a
CROSS JOIN b
GROUP BY a.id,
a.x,
a.y
To get the id of the closest B point, not so easy.

The first naive solution would be to just find the row in B that corresponds to each row in A using nested selects, like this:
SELECT * 
FROM a
JOIN b
ON b.id = (SELECT TOP 1 b.id
FROM b
ORDER BY ( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y ) ASC)

Looking at the execution plan we see what is going on: 86% of the query is spent on "Top N Sort".
Let's get some other solutions so we can compare them in the end in the same execution plan.

Another solution is to just use the result of the query that computes the distance and just join again on the distance. That means we would compare each row in A with each row in B twice, once for the computation of the MIN function and the other for the join:
SELECT j.*, 
b2.*
FROM (SELECT
a.id,
a.x,
a.y,
Min(( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y )) AS m
FROM a
CROSS JOIN b
GROUP BY a.id,
a.x,
a.y) j
INNER JOIN b b2
ON j.m = ( j.x - b2.x ) * ( j.x - b2.x ) + ( j.y - b2.y ) * ( j.y - b2.y )

Something that does the same thing, essentially, but looks a little better is joining the table A with B and then again with B on having the point from B2 be closer to the one in B1, but then adding a condition that there is no B2 (in other words, B1 is closest):
SELECT a.*, 
b1.*
FROM a
CROSS JOIN b b1
LEFT JOIN b b2
ON ( a.x - b1.x ) * ( a.x - b1.x ) + ( a.y - b1.y ) *
( a.y - b1.y ) >
( a.x - b2.x ) * ( a.x - b2.x ) + ( a.y - b2.y ) *
( a.y - b2.y )
WHERE b2.id IS NULL

None of these solutions scan B only once for each row in A. Their relative complexity is this: 75%, 11% and 14%, respectively. In other words, finding the minimum distance and then joining with the B table again on the points that are in exactly that distance is the best solution. However, given some assumptions and a weird structure, we can get to something that runs in half that time:
SELECT id      AS Aid, 
x,
y,
m % 100 AS bId
FROM (SELECT a.id,
a.x,
a.y,
Min(Cast( ( ( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y ) ) AS BIGINT) * 100 + b.id) AS m
FROM a
CROSS JOIN b
GROUP BY a.id,
a.x,
a.y) j

These are the assumptions that must be true in order for this to work:
  • The function value can be converted to a BIGINT without problems. (if the distance between points would have been subunitary, this would have lost precision)
  • The maximum ID in table B is under a certain value (in this case 100)
  • The converted function multiplied by this maximum number doesn't cause an overflow
Basically I am mathematically creating a container for the value of the function and the id of the point in B, computing the minimum, then extracting the id back from the value. Neat.

Another solution, one that makes most apparent sense, is using a feature that was introduced in SQL Server 2005: RANK. We rank the points in B to each point in A, based on our function, then we only get the first by selecting on the rank being 1. Unfortunately, this doesn't work as expected. First of all, you cannot use RANK in the WHERE clause, so you must select the rank first, then select from that selection to add the condition. This might mean horrid temporary data tables if tables A and B are huge. Also, after running the query, it appears it is slower than the one that joins on the minimum distance. Here it is:
SELECT aid, 
bid
FROM (SELECT a.id AS aId,
a.x,
a.y,
b.id AS bId,
Rank()
OVER(
partition BY a.id
ORDER BY (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y) ASC) AS rnk
FROM a
CROSS JOIN b) x
WHERE rnk = 1

Comparing all the solutions so far, without the first naive one, with the nested selects, we get these values:
  1. Mathematical container of function value and id: 14%
  2. Selection of the minimum distance to each point and then joining with table B for the second time to look for the point that is at that distance: 21%
  3. Joining twice on the same table with the condition that one is better than the other and that the better one doesn't actually exist: 29%
  4. Using RANK: 36%, most surprisingly the worst solution

The final solution, adding some more computation in order to get rid of constants and some assumptions thus becomes:
DECLARE @MaxId BIGINT 

SELECT @MaxId = Isnull(Max(id) + 1, 1)
FROM B;

WITH q AS (SELECT A.id,
A.x,
A.y,
Min(Cast(Power(A.x-B.x, 2) + Power(A.y-B.y, 2) AS BIGINT) * @MaxId + B.id) AS m
FROM A
CROSS JOIN B
GROUP BY A.id,
A.x,
A.y)
SELECT id AS aId,
x,
y,
m % @MaxId AS bId
FROM q;


I am still looking and there is now a question on StackOverflow that attempts to get the answer from the community, so far with limited results.

Friday, 22 November 2013

Prevent a Windows computer from going idle even when the Group Policy prevents you from installing any software

I work in this silly place where everything must be done according to some plan or procedure. They aren't even very good at it, but they are very proud of this bureaucracy. For example I don't have Outlook installed on my work machine, but on a virtual one which is in a different network and can be accessed only by remote desktop protocol. Some admin with a God complex thought it was a good idea to make the computer lock itself after a few minutes of idleness and even close the entire virtual machine when no one accesses it for a while. This might have some sick sense in the admin's head, but I need to know when an email arrives and so I would like to have this virtual machine open on the second monitor without having to enter the password every 5 minutes. To add hurt to offence, I cannot install any software on the virtual machine or using Powershell to prevent the computer going idle or anything useful like that. Good, a challenge! I need to find a way to keep the remote desktop session alive.

Enter Windows Script Hosting. I've created a small Javascript file that gets executed by the machine and occasionally moves the mouse and simulates pressing Shift. No more idleness and no need to access Group Policy or install anything. Just create a text file and paste the following code and then save it with a .js extension, then run it. It will keep the computer from going idle.
var WshShell = WScript.CreateObject("WScript.Shell");
for (var i=0; i<60; i++) // 60 minutes
{
WshShell.SendKeys('+');
WScript.Sleep (60000);
}

Step by step instructions for non technical people:
  1. Press the Windows key and E to start the Windows Explorer
  2. In the Explorer, navigate to Desktop
  3. Remove the setting for "Hide extensions for known file types" - this is done differently from Windows version to Windows version, so google it
  4. Create a new text file on the desktop by right clicking in it and choosing "New Text Document"
  5. Paste the code above in it
  6. Save the file (if you successfully removed the setting at point 3, you should not only see the name, but also the .txt extension for the file)
  7. Rename the file to busybee.js (or any name, as long as it ends with .js
  8. Double click it

The script will run 60 times at every minute (so for an hour) and keep the machine on which it runs on from going idle. Enjoy!

Displaying a message from a T-SQL query in real time

The preferred method to display anything in Transact-SQL is PRINT. You can print a string, a variable, an expression. However, as anyone soon finds out, the message get all cached in a buffer and displayed after the entire query ends. So if you have several long running queries in a single batch and you want to get real time messages from them, PRINT doesn't work. A quick search directs you to another MS SQL directive: RAISERROR (note the creative spelling that makes one think more of hearing Katy Perry RROR rather than a proper error raising directive). Also note that Microsoft recommends using a new construct called THROW, introduced in SQL2012. However, it only looks like a lamer version of RAISERROR. They both send a message to the client instantly, but the problem they have is that they do not, as PRINT does, accept an expression. So if you want to print something like 'The computed key from the query is: '+@Key you are out of luck as you need to declare a new nvarchar variable, fill it with the message value then use it in RAISERROR.

But there is a better solution. RAISERROR not only throws something at the client, it also flushes the message cache. So something like this works: PRINT 'The computed key from the query is: '+@Key; RAISERROR('',0,1) WITH NOWAIT;.

Of course, being the dev that I am, I wanted to encapsulate this into something that would be reusable and also get rid of the need do use plus signs and conversion to NVARCHAR, so I created this procedure that almost works like PRINT should have:
CREATE PROCEDURE Write (@P1  NVARCHAR(max)=NULL, 
@P2 NVARCHAR(max)=NULL,
@P3 NVARCHAR(max)=NULL,
@P4 NVARCHAR(max)=NULL,
@P5 NVARCHAR(max)=NULL,
@P6 NVARCHAR(max)=NULL,
@P7 NVARCHAR(max)=NULL,
@P8 NVARCHAR(max)=NULL,
@P9 NVARCHAR(max)=NULL,
@P10 NVARCHAR(max)=NULL)
AS
PRINT Isnull(@P1, '') + Isnull(@P2, '')
+ Isnull(@P3, '') + Isnull(@P4, '')
+ Isnull(@P5, '') + Isnull(@P6, '')
+ Isnull(@P7, '') + Isnull(@P8, '')
+ Isnull(@P9, '') + Isnull(@P10, '')

RAISERROR('',0,1)

And you use it as DECLARE @now DATETIME = GetDate()
Write 'The date today is ',@now
. Nice, huh? Of course what you would have liked to do is Write 'The date today is ',GetDate(), but apparently stored procedures do not accept functions as parameters, and functions do not accept PRINT inside them.