Archive for March, 2008

Using Spare Laptop LCD as a VGA Monitor

Monday, March 31st, 2008

We have bunch of old broken laptops lying around at work. Most of them are unusable, but I don’t like to throw them out because they are a great resource of spare parts. Sometimes I’m able to dig in that pile and use stuff like display hinges, bezels, arm rests, touch pads and etc to quickly fix some of the older machines that are still floating around. Naturally all these machines have been stripped out of memory, hard drives and CPU’s long time ago. One thing that doesn’t get replaced that often are LCD’s. There is probably 6 or 7 displays like the one below in that pile.

Spare Laptop LCD

They are just sitting there and not doing anything constructive, so I started thinking about putting them to a good use. There is another problem I often face - lack of spare monitors. Every time someone brings in a desktop for service we have to go an pull a monitor from one of the currently unused machines available in the office. Which is not the end of the world, since I usually have some flat surface available to set it all up.

Sometimes however a friend or relative brings their machine to my house asking for help. This is where the fun begins. I do have a spare CRT up in the attic that I keep for just hat occasion. What I don’t have is space. When I’m fixing someone’s computer you will usually see a scene of pure mayhem on the floor of my room:

Family Tech Support

I’m usually forced to squeeze the old CRT, the desktop, the keyboard and mouse in the tiny little amount of free space between the bed and the TV, and essentially sit with my back wedged against my desk, occasionally turning around to Google something on my desktop in the back. I could buy a LCD screen, but even a tiny 15″ cheepo sells for almost $200 at neweg - which seems a bit high for something that I would use twice a year, and then stash in the attic or at the bottom of some closet.

This is where the two needs begin to merge: my need to do something useful with the spare laptop LCD’s and my need for ultra-small portable LCD screen. I figured that if I could find an Laptop LCD to VGA adapter I would be all set. Or not…

It turns out that I’m not the only person who had this brilliant idea. Unfortunately, it turns out that it is not as easy as one might think. The laptop LCD has a digital output that is designed to pin into a controller circuit which in turn talks to the video card. These things are mostly proprietary, not standardized and not widely available. The difficult part is figuring out exactly what kind of controller circuit do you need, then locating and ordering one. It’s definitely possible though.

For example, I have found this blog describing the process. Unfortunately it is very light on technical details to the point of being relatively useless. It’s more or less photographic proof that it is possible, but not much more:

dyilcd.jpg

The last entry is particularly discouraging - apparently the merchant who was supplying the circuits used in the example no longer produces them, and is currently out of stock. (

A slightly more informative but less complete post can be found on the mp3car forum. They actually post a link to a vendor who seems to have quite a few different models for sale. There are two caveats though - the vendor seems to be located in Europe, and they only sell in bulk (100 units of more) which makes them useless as a resource. I found few others but none of them was really selling anything online.

Then I remembered a piece of old internet wisdom - if it exist, someone is probably selling it on ebay. Believe it or not, I found some interesting looking kits for sale. Here is a closeup pic of one of them:

tft_lcd_panel__back_light_1.JPG

It is a TFT LCD controller with a back light inverter, which seems to be exactly what I would need. It also looks astonishingly simillar to what the dude in the first blog I linked to was using. Good news is they seem to be selling for $35 + shipping and handling (which will probably be another $30 or more knowing these types of ebay stores). So I’m tempted. It could work, provided that my LCD is one of the models supported by this device and that there are no funky drivers required to actually run this thing.

Anyone ever did something like that? Should I do it? It could make for a nice, space saving, ultra portable monitor, provided that I could find a semi-decent frame to mount the circuit and LCD…

Taking Weekends Off

Saturday, March 29th, 2008

Just wanted to drop a quick note here - I won’t be doing Saturday posts anymore. I already gave up on Sunday posting back in January and I mentioned I might go down to a much healthier 5 day schedule. So this is what I’m doing right now.

This doesn’t really mean anything negative. Rather, I noticed that over time I’ve been putting more and more thought, research and time into every post here. More often than not I’m actually trying to write something that’s either meaningful, interesting or worth discussing rather than just posting 3 paragraph rants apropos the newest hot issue found via digg or slashdot. More often than not I’m trying to post original material here rather than reiterating stuff that you can easily find elsewhere. I don’t know if this is gradual improvement in quality, but it does tend to be more time consuming. So the drop in posting frequency is good for my sanity, and will hopefully let me queue up posts, and perhaps even proofread all of them before they go live. P

I don’t think I will drop below 5 days, but perhaps that will turn out to be necessary in the future. For now though, you can expect to see posts appearing here Mon-Fri usually between 11am and noon (although Google reader doesn’t pick it up until few hours later).

Only Trolls wear Martian Headsets

Friday, March 28th, 2008

I wasn’t going to comment on Joel Spolsky’s Martian Headsets ramble for two reasons: it was an obvious troll-bait, and people much smarter than me already pounded it into the ground. But alas, the Spolsky FUD seems to have infected one of the less known blogs that I really enjoy. I don’t blame Shamus though - he is a good man. It’s just that well written FUD is contagious like brain rot. And Spolsky went all out - he even has pretty pictures all over that article. So I kinda feel that I must counter measure this until it spreads any further.

Joel is essentially trying to tell us that W3C standards are bad because there is no 100% compliant implementation in existence. Therefore he advocates completely ignoring them, and and claims that the efforts make IE8 default to standards mode are ill conceived.

Only he is missing the forest of the trees here. If there is no standards, how can we even strive for interoperability between browsers? Joel doesn’t care because he only uses IE and he is convinced that 98% of the universe does the same (which is gross exaggeration). In the real world however, the standards give us an ideal towards which we can strive for. Different platforms will implement things in different ways, and by comparing implementations we can slowly improve and creep toward that ideal. Sooner or later everyone will be roughly on the same page, and the differences in implementations will be small enough to be negligible. Stefano Mazzocchi does a much better job of describing this process, so take a look on his post on the topic.

In a way this has already happened. Most of the major browsers out there including Firefox, Opera and Safari are perfectly happy displaying the same pages in very similar ways. The standards problem only becomes apparent when IE enters the equation - it has always been a problem. If we bring IE8 into the manifold, then this inter operation and compability issue will slowly phase itself out of existence. I think Sam Ruby hit he nail on the head when he said:

Web pages like Google Maps work on other browsers. Not because of a mythical, platonic “standard” in scare quotes. But because of standards that are actually implemented compatibly. And because in standards mode, these other browsers don’t implement the non-standard IE only Javascript objects that Google Maps checks for.

After reading Joel’s long winded rant, one might come to the conclusion that these “standards” are some truly arcane mysterious texts. But they are not. Granted, they are not simple and straightforward, but it’s not like there is no existing body of knowledge, and interpretations out there. Volumes of text have been written on the nuances of these standards, and there are groups and communities out there completely devoted to pouring over these documents and interpreting them. There are people who specialize in this stuff and will actually hire them to consult you on any and all standards related questions and concerns. But Joel conveniently ignores this fact. He goes on to say:

The precise problem here is that you’re pretending that there’s one standard, but since nobody has a way to test against the standard, it’s not a real standard.

Mark Pilgrim, whose post on this topic is hilarious, eloquently sums with one short sentence:

I have never heard of test suites.

There are test suites, applications and comparison tables you can use. And if anything else fails, you can go straight to the source and hit up the W3C mailing lists. But Joel is not done, he goes on this weird tangent - just bear with me while I quote it in it’s entirety:

If you’ve ever visited the ultra-orthodox Jewish communities of Jerusalem, all of whom agree in complete and utter adherence to every iota of Jewish law, you will discover that despite general agreement on what constitutes kosher food, that you will not find a rabbi from one ultra-orthodox community who is willing to eat at the home of a rabbi from a different ultra-orthodox community. And the web designers are discovering what the Jews of Mea Shearim have known for decades: just because you all agree to follow one book doesn’t ensure compatibility, because the laws are so complex and complicated and convoluted that it’s almost impossible to understand them all well enough to avoid traps and landmines, and you’re safer just asking for the fruit plate.

WTF in hell? I actually laughed as I was reading this. I hope you find this funny too, because this whole big paragraph shows exactly where Joel is coming from, and how far he is of the mark. They are nothing like religious orthodoxy. The interpretation of religious scriptures accepted by the Mea Shearim Jews is pretty much set in stone. In 50 years they will probably be using the same interpretation - perhaps slightly adjusted to account for advances in technology and changing lifestyles. Implementations of web standards are not meant to be religious orthodoxies. If MS doesn’t make IE default to standards mode now, then they will be in the exact same situation in a year or two when they are ready to release IE9. If we keep defaulting to quirks mode, and continue rendering web pages in the same half assed IE6-7 mode, then why even bother implementing the standards? Why even make any changes to the rendering engine? Let’s freeze the code at IE7 stage and only improve the browser by adding UI features from now on. That seems to be what Joel is implicitly suggesting.

Gordon Weakilem makes a very good point when he says:

I mean, really, after Joel harping on about “smart, gets things done”, would Joel accept “Those documents are super confusing” as an excuse in an interview, or for why a developer doesn’t understand something like operator precedence? Really, is there an excuse for ignorant or lazy?

Indeed my friends. Joel’s whole rant is about how difficult, confusing and impossible to implement the standards are. I guess we ought to give up then, right? A mark of a good software developer is that he simply abandons a project at the first sign of trouble. P

But the best part is that even Joels summary near the end of his lengthy triad contains a hidden contradiction:

98% of the world will install IE8 and say, “It has bugs and I can’t see my sites.” They don’t give a flicking flick about your stupid religious enthusiasm for making web browsers which conform to some mythical, platonic “standard” that is not actually implemented anywhere. They don’t want to hear your stories about messy hacks. They want web browsers that work with actual web sites.

Let’s for a minute assume that 98% of the world does use Windows, and that they will all install IE. If my website doesn’t work in IE8 on the release date, guess who is going to get publicly flogged and then castrated by the upper management? If you guessed it was me, you are right. My boss is not going to give a flying fuck that the IE changed the way it is rendering pages. The people who will notice this change the most will be web developers who will have to fix hundreds of web pages, not the customers. No major company will allow their page to remain broken once IE8 release is imminent.

Here is what I secretly think will happen - IE8 will get released, and end users will blog at length about all the new features in the browser. Most of them won’t even notice the standards thing. Few legacy applications, and poorly maintained pages will break, but Google, Yahoo, Myspace, Facebook and all the other big and popular sites will work like they always did, or better.

Sure, few people here and there will blame IE8. Are they going to install Firefox? Yeah, right. The people who know about Firefox either don’t like it, or are already using it. IE8 breaking won’t push people towards alternative browsers. And surely it won’t make them abandon windows altogether. That would be the day! Worst that will happen is that they will downgrade back to IE7 - if they can figure out how to do it. Most of the clueless users from Joel’s example will simply shrug it off and learn to live with it.

You don’t even want to know hoe many times I heard my users complain about “the new Microsoft” (IE7 in luser speak) that got installed on their computers. When I offered to downgrade them back to IE6 almost all responded with a surprised “you can actually do that?”. Users will survive - they are already used to Microsoft breaking their shit.

So there. This is my Spolsky headsets rant. Regrettably, that’s another link to Joels page, and probably few dozen page views (considering my click through rates) and few extra dollars in his adsense account. Maybe I should take cue from Mr. Spolski and post some horribly inflamatory, nonsense every once in a while and then just sit back and rake in the cash. Unfortunately, while I’m shameless and blunt at times I have that thing… I think they call it integrity or something like that. Oh well… Now that it’s over with, let’s get back to usual craziness.

The Sudoku Infection

Thursday, March 27th, 2008

My family has been decimated by the Sudoku bug. I’m actually physically tired of making the “Hey, the year 2005 called and they want their game back” jokes all the time. I’m not sure why is this happening now, but nevertheless everyone keeps solving the damn things. For added humor, my dad keeps forgetting the name of the game and keeps referring to it as seppuku. Whether I want it or not that damn puzzle has entered my household and is not going away anytime soon. Because of this I started looking at he puzzle more closely as an interesting problem to be cracked.

A while ago I mentioned an effective Sudoku solving algorithm - one that you can use with your pen and paper puzzle. For the sake of completeness, let me recount it here:

  1. Start by writing numbers 1-9 in each empty cell of the puzzle (or get the nifty template with pre-filled numbers)
  2. Pick one of the given (seed) numbers and eliminate it from the row, column and quadrant it is in (ie. cross it out from the 1-9 lists in these cells)
  3. If you are lucky, few cells may end up having only one number on the list that was not crossed out - that’s the number that belongs in that cell. Take that number and eliminate it in a row, column and quadrant as above
  4. If you can’t find a singleton number scan each crow, column and quadrant for a unique non repeating number (ie. one that appears only in a single cell in that row, column or quadrant. If you find one, that’s your number - put it in the cell where it appears and eliminate it from the row, column and quadrant

I believe that you can solve most of the easy, medium and hard sudokus this way. However, now that I actually did some digging, there seems to be a subset configurations in the “evil” range which actually requires trial and error strategies and can’t be solved by simply sticking to the algorithm above. Which of course doesn’t mean the puzzle is not solvable.

In fact, if you look at sudoku really hard it really boils down to the good old graph coloring problem. A standard 9×9 Sudoku grid translates to a graph with 81 vertices. Each vertex has exactly 20 edges connecting it to 20 neighboring vertices (8 more in the row, 8 more in the column and 4 more in the quadrant) and the chromatic number is 9. The bad news is that graph coloring is NP-hard. The good news is that sudoku’s don’t really scale upwards that much. So you can use an algorithm that performs acceptably with sudoku sized graphs (9 colors, 81 vertices, 1620 edges between them) and stick with it.

The fact that sudoku is a book case graph problem not surprising. A lion share of real life problems can be solved using nothing more but graph theory. So here is a word of advice for you younger whipper-snappers out there. Do use the Algorithms class to sleep off your drunken debaucheries - especially not on the day when they are covering Graphs. But don’t take just my word for it, listen to Steve Yegge’s recent rant:

Graphs are, like, really really important. More than you think. Even if you already think they’re important, it’s probably more than you think.

(…)

Whenever someone gives you a problem, think graphs. They are the most fundamental and flexible way of representing any kind of a relationship, so it’s about a 50-50 shot that any interesting design problem has a graph involved in it. Make absolutely sure you can’t think of a way to solve it using graphs before moving on to other solution types. This tip is important!

Big question: how many real world graph problems have I encountered at my at my job since I got my degree? I’ll give you three guesses.

The sad truth is that I haven’t touched these things since my algorithms class. Part of it is the nature of my work - which involves a lot of sysadmin stuff, in addition to hacking my PHP+MySQL monster into submission. The problems I face on the daily basis can mostly be solved in polynomial time and usually revolve around storing and fetching data from a database.

This state of things is regrettable but not unusual - a lot of people are in the same boat. Nevertheless, we are getting rusty and these graph problems are important, if for nothing else than for impressing interviewers when looking for another job.

Which tells me I need to dig out my Algorithms book and knock out a Sudoku solver. But which language should I use? I’m thinking Ruby just to get more feel for this language. )

Hellstroms Hive

Wednesday, March 26th, 2008

As you may or may not know, I’m a big fan of Frank Herbert’s work. I own all six books in the Dune saga, and I more or less consider them an epic Science Fiction masterpiece. Dune is my yard stick by which I use to measure greatness of other SF novels.

You may say what you want about Herbert, but his books pack more thought provoking ideas about philosophy, religion and life per page than any other work in the SF genre. They are incredibly smart, eloquent and while the plot usually moves at a glacial pace, each paragraph is loaded with mind blowing revelations, or interesting ideas. Dune had so many incredibly potent ideas condensed into it created a similar effect that Tolkien’s Trilogy did for Fantasy - almost all science fiction written after Dune echoes or copies it’s themes and ideas.

Even Herbert himself didn’t seem to be able to escape from being overshadowed by his own success. I recently picked up one of his non Dune related novels titled Hellstrom’s Hive and it does seem like a faint echo of Dune. When I first started reading the book I actually thought that this was one of his earlier novels, and that the familiar themes (ecology, eugenics, social conditioning) were simply indicative of authors primary interests which were later expanded and fully fleshed out in Dune. This is however not the case. Prior to writing this review I checked the publishing dates, and it turns out that Hellstroms Hive (I will abbreviate it as HH if you don’t mind) was first released in 1973 which is 3 years after Dune Messiah hit the book shelves and 3 years before the Children of Dune.

Hellstroms Hive

Messiah is widely considered to be the weakest book of the Dune saga, so it puts HH right at the lowest point of this great authors form and it shows. Still, Herbert at is worst is still a hell lot better than most writers at the pinnacle of their creative performance. The book is still smart, eloquent and very well written. The concept behind it, and the general setting however are simply not as gripping or fascinating as those of Dune.

The action takes place in the present - or rather Frank Herbert’s present, which is the the earl 70’s. A ultra secretive governmental agency intercepts schematics for some incredibly potent weapons system, and links them to a known insect specialist and film maker Nils Hellstrom. Agents are immediately sent to covertly investigate his remote and secluded farm compound where most of his nature films are being produced. What they find there goes beyond their wildest dreams - they uncover a bizarre social experiment: a human hive. Inhabitants of the compound built a vast network of tunnels and caverns beneath the ground, and their society is modeled after that of social insects like ants of bees.

In a way the Hive is simillar to Huxley’s Brave New World Society with humans being breed and chemically altered for their jobs. There are mute drone workers chemically stripped out of free will, grotesque and sterile science specialists with withered bodies but superhuman intellect, inbred dim witted and docile hulks used for heavy lifting and etc. The Hive is essentially an alien world with it’s own philosophy, goals, and agenda.

Herbert skillfully switches between the two factions and tells the story both from the perspective of the members of the agency and the hive inhabitants. So we get a unique look on what really drives Hellstrom and his people, and how they view the outside world. But while the description of inner workings of the hive, and the psychological portrait of it’s people are compelling there are no where near as complex and layered as for example the Fremen culture Herbert portrayed in Dune.

While the Dune books usually are overflowing with really catchy, memorable ideas and themes that we keep imitating to this day (the spice, the space guild, the Bene Gesserit, Kwisatz Haderach, the Golden Path, Sand worms, personal shields, the Sardukar etc..), HH is essentially a one trick pony. The hive is the central idea - it is the science fiction element and that’s it. The same painstaking level of detail, and slow methodical progress of the plot that actually worked well in Dune is actually painful at times. While it was fascinating to read about court intrigue, or observe Bene Gesserit political maneuvers, the lengthy passages dealing with the Agency going through the motions, and dealing with bureaucratic hurdles are actually a bit dull. They lack that deep insight, religious reflection, philosophical contemplation, and the Zen of Dune.

I think that the core plot and ideas could easily be compressed into 20-30 pages and would make for an excellent short story. As it is, it is merely a mediocre novel which plays around with 3 of the themes known from dune: ecology, eugenics (selective breeding for special purposes) and social conditioning. All of them were already pretty well covered in the two Dune books that preceded HH and the author really had given them a much better treatment in the 4 Dune books which followed it. In my mind this book seems to be a light warm up or perhaps a much needed combo breaker that helped Herbert to get into the mood for Children of Dune.

If you are a big Frank Herbert fan like me, pick it up. It is well written, and uses that distinct 3rd person, objective, omnipotent narration style that you know and love from the Dune books. Just don’t expect any conceptual fireworks. Just sit back, and enjoy the ride. If you fell asleep reading Dune, and then fell asleep again watching one of it’s movie adaptations stay clear of this title. You have to appreciate Herbert’s specific, slow, deliberate and detailed style to fully enjoy this book.

How to Teach Programming?

Tuesday, March 25th, 2008

I might be wrong about this, but I’m partial to the gauntlet method of teaching introductory programming courses. You make the class as challenging and difficult on purpose and make the students sweat. Hit them hard and as early as possible so that the slackers get the idea and withdraw from the course. Every lecture should raise the bar, and anyone who can’t keep up or is struggling should be encouraged to drop the course and change their major. It is harsh, but I do believe that a large percentage of people in every programming class will just never get it. No matter what you do, they will always struggle and will demand your help and attention which would be better spent supporting the students who actually get this stuff and are progressing at a fast pace.

I can probably tell you which people will do well, and which will struggle and just waste your time. You can see when you assign a really difficult problem they haven’t encountered before. The students that get energized, and excited by the challenge - who ask meaningful questions, furiously jot down notes, or start coding before you even finish explaining it - they are your star players. They should get all your attention and you should make sure they are sufficiently challenged, and that they have adequate support to meet the challenge head on.

Then there are those other students who raise their hand and say “I don’t understand this” or “I don’t know how do I do this” - they are most likely a dead weight. And yet, you will end up spending inordinate amounts of time basically holding their hand, and pretty much debugging their code for them. You end up purposefully dumbing down the course, and choosing idiot-friendly tools for their sake and in the end your star pupils get bored, and frustrated with the glacial progress of the course. In the end everyone loses.

The talented students make little progress, and end up ill prepared for the next programming course in the curriculum. The non-programmers barely pass with a C or a D (or if you made enough concession for their sake even a B) and leave your class without actually learning one damn thing. Or rather, the only thing they learned in your class was that they can slip through the cracks and pass a programming class without actually learning how to code or solve problems.

I think that the use of tools like BlueJ in the classroom is an outgrowth of this “cuddle the hopeless students while ignoring the talented ones” approach. Personally I think we do not need tools like that - not at the college level. But this seems to be a minority opinion, and many people disagree with it. Same could be said for the gauntlet approach.

The thing about the gauntlet thing is that it is actually very difficult to implement. It requires tons of experience, and absolute confidence in your teaching ability and methodology. When I notice that large number of my students is lost, I usually blame myself and try to review and re-iterate the difficult parts over and over again. More than once however I found that the people who were most vocal about the difficult material, and who got the most help from me actually got it wrong on the test, while the silent majority actually understood it. So I essentially wasted my time, spinning my wheels in place instead of going forward or covering other areas in more depth. It’s easy to spot these pitfalls in retrospect but not when you are lecturing. When I have 4 or 5 students who seem to be completely baffled by something that I just said, and loudly voice their confusion it is sometimes hard to realize they are actually not speaking for the whole class. The remaining 30 students who are quietly taking notes might not be confused at all.

Experience helps here - and so do a time tested lesson plans and delivery methods. Identifying and subsequently ignoring the dead weight also helps. But it is very hard to do because it means you are essentially giving up on some students and allow them to fall behind. And that is a horrible thing to do. Most teachers won’t willingly do something like that. Personally I refuse to do it and I really try to help people out when I see they are struggling. But often that means I’m essentially the one doing all the work - I’m literally pushing, and dragging them that’s passing grade. Would they make it if I didn’t actually force them to do work? Would they pass if I didn’t extend their deadlines ad infinitum? Probably not, and by helping them so much I actually allow them to slip through the cracks without actually working for the grade or even trying very hard. This is why gauntlet is a good idea, but I’m the wrong person to run it. I couldn’t do it. But there are people who can and do run their classes this way.

It takes the right instructor - someone who is approachable, supportive, but at the same time tough and demanding. And most importantly someone who knows what he/she is doing.

But IMHO there should be no cuddling, and no tolerance for ignorance or technological incompetence. But above all, there should be a zero tolerance policy for students who say one of the following lines:

  1. I hate computers
  2. I hate programming
  3. I hate [language you are teaching]

The only response to any of these statements should be: You should not be here! You will not do well! Drop this class! Drop this class! Drop this class immediately!

If you are confused by technology, programming bores you, and you dread every single coding assignment why are you subjecting yourself to this whole ordeal? I do not understand why people do this, but they do. When I was in college, I stayed the hell away from the Business School building because economics and finance classes bored me to death. I did not enjoy them so I didn’t take them. The Computer Science program at my school offered us a choice when picking required auxiliary courses - you could either do the science route (2 science classes - chem or physics) or the business route (3 business classes - micro/macro economics and some other stuff). I immediately signed up for science because it sounded much more interesting, and much more challenging. Most of my friends picked economics because it was easier.

Computer Science should never be the easy or fun course. It should be the class that evokes the sentiment in the majority of student body: “You are taking Computer Science? Are you insane?”. Only the students who are crazy enough, motivated enough or just love the subject should be taking the class.

Unfortunately, if you don’t get 20-30 warm bodies to register for your course at my university, the Dean will shut it down. And this is a problem at a school where we only offer 2-3 introductory programming sections per semester due to low student frequency.

3 Value Checkbox with JQuery

Monday, March 24th, 2008

Few days ago I did that whole 3-value checkbox thing basing it on some script I found online. I went back and I re-implemented it using some JQuery magic. I’m not going to reiterate the whole setup here. I recommend that you check the linked post for details. You can find the JQuery-fied code below:

$(document).ready(function() 
{
   checked = '/path/to/checked.jpg';
   unchecked = '/path/to/unchecked.jpg';
   na = '/path/to/na.jpg';
   i = 0;
 
   // replace the checkboxes with images    
   $("form.funky_form > fieldset.funky_set :checkbox.funky_box").hide().each(function() {
 
      img = document.createElement('img');
      img.className = "funky_image";
 
      switch($(this).val())
      {
         case "0":
            img.src = unchecked;
            $(this).attr("checked", "false");
            break;
         case "1":
            img.src = checked;
            $(this).attr("checked", "true");
            break;
         case "2":
            img.src = na;
            $(this).attr("checked", "true");
      }
 
      // these will let us identify which image was clicked
      // and which checkbox does it belong to
      $(this).attr("id", "input" + i + "image" + i);
      $(img).attr("id", "" + i + "image" + i);
 
      i++;
 
      $(this).before(img);
   });
 
   // add onClick functionality to the new images
   $(".funky_image").click(function() {
 
      // select the checkbox corresponding to the clicked img
      t = $("#input" + $(this).attr("id"));
 
      switch(t.val())
      {
         case "0":
            $(this).attr("src", na);
            t.val(2).attr("checked", "true");
            break;
         case "1":
            $(this).attr("src", unchecked);
            t.val(0).removeAttr("checked");
            break;
         case "2":
            $(this).attr("src", checked);
            t.val(1).removeAttr("chekced");
      }             
   });
});

The major difference from the other version is that I’m much more discerning in which checkboxes get converted. The code will select only a box that is of the class funky_box and is inside a fieldset with a class of funky_set and inside a form with a class of funky_form. I’m mostly doing that to show power of JQuery - this is all specified in that very first select statement. I was trying to do something similar in the old code, but I was getting hung up on the silly DOM gotchas. JQuery makes this easy.

Also note the chaining functions. The first line after I declere i both hides all the selected check-boxes and begins the each block. Similarly, check out the second switch statement. In several places I set the value of t and change the checked attribute on the same time. It’s very expressive, and lends itself toward very compact and concise code.

Here is the HTML for the form to go with the code above (note the inclusion of the fieldset tag):

<form name="funky_form" method="POST">
      <fieldset class='funky_set'>
         <label for="c1">
            <input type="checkbox" name="c1" value="1" class="funky_box" checked>
            Some Important Task
         </label><br>
 
         <label for="c2">
            <input type="checkbox" name="c2" value="1" class="funky_box" checked>
            Some Important Task #2
         </label>
      </fieldset>
 
      <label for="c3">
         <input type="checkbox" name="c3" value="1" class="funky_box" checked>
         This is a checkbox with the funky_box class outside the funky_set
      </label><br><br>
 
   <input type="submit" value="Submit">
</form>

How readable is this version? To me it is actually better because it’s smaller, and more compact. To someone who never worked with JQuery it might be a bit confusing at first but I think you get used to the weirdness pretty quickly. I find the selection statements much more elegant than nested loops for example, even if they might The more code I can see on my screen the better. I’m not golfing though - all the methods and most variables have meaningful names (well, except stuff like t and i but you know how it goes).

Which version do you like better?

KOTOR 2: Broken Jedi

Saturday, March 22nd, 2008

KOTOR 2 uses an interesting plot device to explain why your battle scarred, world weary Jedi character has such meager stats and force powers at the beginning of the game. In the original there was no such excuse because you simply started as a oridinary, human being and only gained force powers after going through the training on Dantoine.

KOTOR 2 on the other hand insists that you were a Jedi once, and that you are actually one of the last of the living Jedi knights in the galaxy. So why the poor starting characteristics? It turns out that you were exiled from the order, and the Jedi Council somehow severed your connection to the force. Ha! Clever stuff. Unfortunately while it does make some sense on the surface, and does make for a good story (why did they do it and how?) I don’t totally buy this explanation. It’s not very consistent with what we know about the Star Wars universe. If the Jedi Council had this power all along and could elect to neuter a Jedi knight at a whim by severing him from the force why was it done to your character (a virtual nobody), and not to the big bad Sith Lords that threatened the galaxy in the past? Someone is probably going to say they were to powerful to be dealt with that way or that the Sith training includes techniques that help one protect himself from such an attack, and I guess it is an explanation of sorts. Still it has not been addressed in the game yet. I will suspend my judgment on this until I finish the game but I’m not entirely happy with the forceful force removal idea.

On the other hand, I kinda like the idea of a failed, broken Jedi character. If I remember correctly the D6 Star Wars rulebook we used way back when (long log ago, in a galaxy far far away) actually included something similar as a playable character archetype. I think it was dubbed as the “Fallen Jedi”. The fallen bit was not referring to falling to the Dark Side though. In fact it was about failing more about falling. A fallen Jedi was simply a washed out failure and a nobody. The rulebook had this great sketch of a unshaved, unkempt inebriated drunkard slouching on a bar stool, with a drink in one hand, gambling cards in the other, the lightsaber hilt sticking out of some odd pocket of his jacket.

k2_00007.jpg

The idea was simple - you were taught to be a Jedi but you were either never really good at it, or your personal opinions clashed with the Jedi code - or perhaps you somehow dishonored yourself. Either way, you have no affiliation with the Jedi Council anymore and your life went down the drain. Now you spend most of your time getting drunk trying to drown out the past. And if you are not drinking you hire yourself out to do odd jobs here and there in order to afford the booze. Even if you were semi competent at using force in the past, these days you are rarely sober enough to actually actually be able to concentrate.

Not so long ago, Shamus had an interesting discussion about the difficulties of running a Star Wars campaign when someone in the party insist on playing a Jedi. I think the washed out Jedi is the ideal archetype to stick into a more traditional party of smugglers and bounty hunters. He would have similar motivations and aspirations as the rest of his company - money, booze and loot. His social and political influence would be diminished since most of NPC’s would be able to tell he has no backing of the Council and essentially is no more than some hired gun with a toy lightsaber. Additional bonus is that this character could actually have a good excuse to dabble in the dark side powers.

k2_00009.jpg

But let me get back to KOTOR. The game did take a turn for the better after leaving the initial area, and the Telos Orbital Station section was actually fun and interesting. I liked how the game allowed you to either work for the corrupt Czherka Corporation, or against it by help out the Ichtorian planet restoration efforts. There were some interesting missions there, and I liked how they were all clustered in the relatively small area of the base. Since the same locales were reused, or previously blocked areas became available it made the base seem more dynamic and alive. It was much better than running in the endless corridors of the mining station fighting hordes nameless droids at the begining.

That said, the story I still makes me cringe at times. For example, nearly every time you board some kind of a ship or shuttle you either get shot down or locked out and end up trapped in the new area. When you start the game your ship is sealed off in a differed section of the station, and you need to run around for hours before you can unlock it. Then you reach the Telos Orbital Station, and your ship gets confiscated, and then stolen. So you board a shuttle to the planet surface, which gets shot down and you end up trapped on the semi-hospitable planet. Somehow you manage to find another shuttle on the surface, only to get shot down again, and ending up trapped in the polar region of the planet. WTF?

k2_00018.jpg

It seems repetitive, to the point that I’m now actually expecting it to happen every time I travel from one area to another. Furthermore the game seems to alternate between seemingly open ended game play mode and interludes of very linear progress and story exposition. Which I guess is ok. I’m once again at a point in the game where I can once again choose my own quests. I also did so many good deeds that my character’s portrait is actually glowing now. P

The dialogs seem to be a bit glitchy in this game. Sometimes the game will randomly skip a spoken line and you notice it because they usually change the camera angle after a full stop. When a line is skipped you can still see the change in scenery, and it just quickly cuts away to the next scene/line. It doesn’t happen very often, but it is noticeable. Also, the timing is sometimes off when you talk with aliens that speak in their own language. It’s almost like that subtitle gag in which you hear a character speak in a foreign language for a full minute, only to see this lengthy tirade translated to a single word in the subtitles. This actually sometimes happen here - the subtitle says something like “I will think about this…” but the spoken part in the alien language seems to be going on and on and on. It’s a little bit silly.

k2_00014.jpg

As I progress through the game, combat starts to become more strategic and the behaviors/stances you set for the party members you are not currently controlling actually do matter. For example, on the surface of Telos there are big open areas with enemies scattered all over the place. I left all my characters in the aggressive stance only to watch them scatter in all directions and aggro just about every single enemy on the map. After that fiasco I tend to keep the old lady as a force support character, and whoever else I have in the party as ranged. This usually keeps them following my main character who is in aggressive stance and prevents them from doing to much aggro all around. When needed I can switch to these characters and give them direct commands. I just wish I could have more than 3 people traveling with me at a time - if for nothing else just to exploit all the different stances at the same time.

As characters go, there are few new faces at this point in the game. There is a Zabrak mechanic and an Echani fighter. While I don’t care either way for the former, the later seems interesting. While she was trained to shield her mind against the force, she seems to be genuinely interested in it. She also has interesting concepts on combat as a form of expression. If you ask her to train you she will insist that you both strip down to your underoos. Yes, this is a character that I can grow to like. mrgreen

k2_00022.jpg

Despite all the complaining above, I’m actually enjoying this game. The story is slowly unfolding and the missions are interesting and not very repetitive, even if all but the most important NPC’s look the same using the 20-30 same models colorized in different ways. So far I haven’t been tempted to put it down which is a good sign. P

JQuery Quirks

Friday, March 21st, 2008

Here are two interesting quirks in the way JQuery works. Let’s say you want to check all the check-boxes on the page - how do you do it? It’s trivial:

$(":checkbox").attr("checked", "true");

Now quickly, how do you un-check all the check boxes on the page? If you said:

$(":checkbox").attr("checked", "false");

You are wrong. Despite the fact that if you use a more standard notation and say for example:

document.myform.mycheckbox.checked = false;

it will give you the desired result. The JQuery call however does not work. In fact, it does the exact opposite - it will set all the check-boxes on the page to their checked state. Apparently for the few funky attributes like “checked” and “selected” the second argument of the attr() method call can be any non-empty string. It makes sense because you actually don’t have to give these attributes an explicit value in your HTML code for them to work. So how do you un-check a box in JQuery? There are two ways. First one, and the more sure-fire one is to remove the checked attribute altogether:

$(":checkbox").removeAttr("checked");

Second one which has worked for me for some reason was to set the attribute to the empty string:

$(":checkbox").attr("checked", "");

Same goes for select attributes in combo boxes and list boxes. You need to remove them or set them to an empty string, or they won’t go away.

Quirk number two: axjax weirdness. Look at the code below:

$("a").hover(function() {// do something});
$("#sometrigger").click(function() { 
   $("#container").load("/some/page.html #links"); });

What am I doing here? I’m adding some hover functionality to all the links on the page. Then I add an on-click even to #sometrigger element. When it is clicked I want to load the contents of #links from /some/page.html into #container asynchronously. Where is the quirk? The hover functionality will not apply to the dynamically loaded links. It’s weird, but that’s just how it works. So if you want this functionality on all your links you will need to reapply them:

$("a").hover(function() {// do something});
$("#sometrigger").click(function() { 
   $("#container").load("/some/page.html #links", 
      $("#container > a").hover(function() {// do something});
         });
   );

It’s a little bit silly, but it kinda makes sense. You may not always want to apply the same events and formating to newly loaded html. But if you don’t expect it, it may throw you off. One you know about it however you learn to compensate for it. I’m being told that folks coming from the Prototype community are hitting this little quirk like a brick wall because their framework behaves in the opposite way (ie. the effects and behaviors are applied to the ajax loaded html).

Apostrophe in the Email Address?

Thursday, March 20th, 2008

Here is a question for my IT/Sysadmin readers out there. When you get a user who has an apostrophe, or an unusual character in their last name, how do you go about setting up his or her email address? Do you:

  1. Drop the apostrophe and special characters and/or replace them with the closest ASCII equivalent to keep it easy
  2. Keep the special characters and force everyone in the world to struggle as they try to email that user

Apparently IT people at a certain bank that I will not name (but let me just say it’s initials are HSBC) think that option #2 is a good idea. Why? Let’s think about a hypothetical scenario in which, for example and apostrophe in the email could be a problem. Again, this is just a make believe situation that has never actually happened yesterday at my company.

So, hypothetically speaking a made up user JC calls me up yesterday and tells me that she can’t send email to one Frogurt D’mangello who works at the said bank. Why can’t she do it? Because Mr. Frogurt’s email looks like this:

frogurt.d’mangello@we.like.subdomains.in.our.emails.hsbc.com

On the surface this is ok - after all apostrophes are allowed to be part of the email address according to the RFC, right? I know this, you know this but apparently whoever hacked together SquirrelMail didn’t. So when you try to send an email to Mr. Frogurt via this popular and widely used webmail application his address becomes:

frogurt.d\’mangello@we.like.subdomains.in.our.emails.hsbc.com

Yes, someone is running mysql_escape_string method on all input fields, even those which legally are allowed to contain MySQL unfriendly characters. I should be mad at SquirrelMail but you know what - they are doing the right thing. I sanitize all my input fields too when I work on a web application. Better be safe than sorry. Naturally, they could use strip_slashes just before actually sending the email but what are you going to do. It’s a bug (which might have been already patched in then newest release), but I can’t fix it because I do not maintain the SquirelMails server. (

But the situation is now a conundrum because JC is behind some draconian firewall which blocks all outgoing ports save for port 80 meaning she can’t use Outlook to send emails. She also can’t use SquirrelMail due to this peculiar bug. So how do they communicate?

This could have been easily avoided if certain IT department simply had a policy which said “only dots and alphanumeric ASCII characters in usernames”. And not just because certain email packages may not support all the different addressing formats as specified in the RFC. It’s also because everyone thinks they know how to validate emails but they don’t. Half the validation scripts out there is just plain wrong. You actually need a 6.4K regular expression to cover all the different addressing schemes covered by the RFC. So if Mr. Frogurt wants to subscribe to some mailing list, or sign into some popular web application he might at one point be told his email is not valid. Remove the apostrophe, and even the most broken email validator will let it through.

Not to mention the hassle of emphasizing the apostrophe every time he tries to dictate his email address to someone over the phone. So really, other than blindly following the RFC, what other benefits are there of putting that non alphanumeric character in his email? Would Mr. Frogurt really mind if his email started with frogurt.dmangello? Would it really make his life a living hell, or would it actually spare him some potential hassles, misunderstandings and unnecessary tech support calls?

I too have a non-standar letter in my name. If I wanted, I could set up my email as: Łukasz@example.com. It would be legal under RFC but I would probably spend the rest of my days explaining to people what that “weird L” is and how to get it in Outlook. Oh, and no iPhone user would probably ever email me because these poor schmucks can’t copy and paste yet. ;P

I say stick to alphanumeric ASCII and dots. Anything more is just asking for trouble.


Bad Behavior has blocked access attempts in the last 7 days.