Thursday 30 November 2006

Green software

This is a brilliant piece of software designed to make your computer use less power. Download it and run it people - it's your duty!

http://www.localcooling.com/

Come together

It always appeared that totally changing one's life was going to be one of the hardest things to do. There would be the enormous doubt, the fear of the unknown, the constant questioning of the choice, the nerves about the imminent financial state, the worry of the excessive chafing of the leotard to the nether regions in the new job, etc. However it's been amazingly simple. It helps enormously to have supportive friends and family to allay those doubts, and to each and every one who has helped - thankyou. However not many of these negative values have really surfaced, probably due to the real morale boosting and positive mindset of these influencial people.

For anyone who's thinking about chucking it all in and going to fulfil a lifelong dream - don't delay - get stuck into changing your life. It's the most euphoric feeling. Every emotion runs through your body sending pins and needles of pleasure and happiness through every finger and toe in your body. Every muscle and memory seems to gear towards solidifying the past encouraging you to settle any personal differences - the feeling that this may be the last time to be able to say protracted goodbyes to those who have helped shape your life, the ability to see through any past indiscretions to come together and truly accept who you are. It's the most incredible therapeutic, cathartic feeling. Of course you want all of the goodbyes to seal in the story of the journey so far, but they must be fully sealed without leaving any gaps to lose anything through.

Life's a totally personal experience, no one can ever tell you how you feel or force you to think in a certain way, but everyone has influence over others in their close circle of friends. To be able to clean the dust away from the relationships with your friends and admire them for who they are is wonderful. To be able to hold someone with the greatest respect after knowing them for many years having seen the decisions they have made and the way they have handled themselves when the going got tough - that's a personal quality that I will always admire in those around me, and constantly aspire to.



So take a look at your friends - repeat in your mind why you like to talk to them, why you enjoy spending time with them, why they make you laugh, why they make you think, what you'd miss if they went from your life, but most of all why you respect them. Then sit down and tell them one thing that you thought of. Everyone needs a morale boost sometimes, and if that boost comes from a close friend they might just buy you a drink and argue about whether Roadrunner was better than Tom and Jerry.

Monday 27 November 2006

A cage for the monkey

Spoke to the lovely Steph at Planet Subzero about getting somewhere sorted to live in Chamonix. Lo and behold, am all set up! Perfect.

Everything's coming together nicely and picking up pace at a good rate with more ideas for work coming into the pipeline and being discussed. Will book flight this week and start dusting off my thermal thong and the rest of the boarding gear.

For those who aren't sure where Chamonix is, here's a link to the French Google maps listing.

The Changingman

Written Friday 24th November

Decided to head home to the country to see my folks and take part in the Lytham Yacht Club annual dinner. It's a pretty traditional affair - dinner jackets, speeches, port and the like. It's pretty crusty too. Junior members are those under 30 and the president of the club is in his 90's. As I said - traditional! The funny thing is not one of the (all-male) members actually owns a boat/yacht/ship - it's purely social.

Another reason for coming up to the dinner is to take a break from the big smoke. I've been in London for a several years now, working for a capital management company and then for a financial betting company. A radical change in life is due. So yesterday the formal resignation went in and it became time to start shaping the future of the boy Narg.

Today I find myself on a Virgin train piling through central England heading from Euston to Preston listening to Nina Simone's greatest hits flowing through the headphones from my iPod with the same subtle, blended, sinuous feel of looking out of the window watching the scenery roll past. It truly does feel like the beginning of an adventure - one that potentially could shape life for many years to come.

I've decided to move out to Chamonix - the town that sits in the valley at the bottom of Mont Blanc in France. It's a mecca for skiiers and snowboarders due to the high, steep peaks, as well as being one of the best places in Europe to go climbing for the same reason. Timings look like to move out there mid-January after spending a month in New Zealand over christmas and new year. The more cynical out there will think this is purely a ruse to go out and play in the snow for a few months, but in fact it's going to provide the oppertunity to finish writing a piece of software that's been rolling around my mind for some time now. Also there's a particularly talented friend out there who runs the Chamonix valley website - chamonix-valley.com - and we've talked a bit working on a few bits on that together in a trade for using his offices to work from.

There's a heightened sense of freedom and happiness now that's not been felt for far too long. It's too easy to get bogged down in monotony and the negative aspect of life and that's debilitating. There's too much oppertunity to make your life wholely fulfilling and happy out there. The big adventure of life is an exciting miracle of a challenge and I've always felt that if you feel like life is passing by and you aren't living to the apex of the fun, happiness, joy and peace you can have then it's time for a change. Life is beautiful - even the chapters that are difficult or you don't like provide the lows for the highs to be high. Once again, it's been easy to wake up in the morning and jump up and down on the bed with excitement about what the day will bring, the utter joy of knowing that this one day is unique and there will never be the chance to live it again. That for me is the most special feeling, to share that with someone else - especially your partner and children - has to be the great gift of life.

There is an element of sadness leaving work - there is a plethora of amazing, incredible people there. Especially one guy who stuck up for me when times were hard and I just hope one day that he'll see the loyalty and honesty he showed me was reciprocated at every oppertunity that arose - he deserved it and much more. For that and his ability to teach and share knowledge selflessly, I thank him. I wish him and the other guys all the very best. Before leaving it also feels fully right to make peace with the very few people who there was any sort of friction with. It just feels correct in order to look back at this chapter in life with a whole heart full of happiness at having those people around as influential characters.

So the main plan of action now is to move to Chamonix and:

1) Write an exciting, challenging, clever, sellable piece of software (then sell it!).

2) Settle into doing two things that I love unconditionally - programming and snowboarding.

3) Fall in love again. OK now this isn't quite so urgent, but it's definately part of the main life plan thingy so it's included here.

Related links:
Chamonix valley website

Listingslab blog

Thursday 23 November 2006

Number fun

Numbers are pretty interesting things, as well as the obvious mathematical use people also attribute emotional, psychological, mythological and religious reactions to certain numbers. Everyone has numbers they like and don't like, history and superstition show that westerners perceive the number 7 as not only lucky but also there are associations with cognitive psychology whereas the chinese see the number 8 as especially fortuitous. Funky stuff. In fact numerology explores this relationship between numbers and other systems (religious, physical, living, etc). My study into this is fairly limited, but it's always been interesting playing around with numbers and I've a stack of JavaScript number object extensions that I carry around in an html file wherever I go to work.

So here they are. I can't take full credit for all of these, I've based some of them on other snippets of code I've found around the place. Notably from codingforums.com so thanks to all who have contributed. I should point out that there's not much explaning that will be done as to why they work - they've been chopped right down to the bare minimum of overhead in most cases and work beautifully, but often look complex. I may well post up another time how they work in more detail.

1) First up is a classic. Rounding a number to a specified number of decimal places. It takes an optional argument n for the number of decimal places to round to. If no argument is supplied, the number will be rounded to 2 decimal places.

Number.prototype.toDecimals = function(n) {
  var n = (isNaN(n)) ? 2 : n;
  var nT = Math.pow(10, n);
  function pad(s) {
    s = s || '.';
    return (s.length > n) ? s : pad(s + '0');
  }
  return (isNaN(this)) ? this : (new String(Math.round(this*nT) / nT)).replace(/(\.\d*)?$/, pad);
}


Usage:
var intNumber = 9.23423;
var intRounded = intNumber.toDecimals(); // output: 9.23
var intRoundedToFourPlaces = intNumber.toDecimals(4); // output: 9.2342

2) Make an ordinal string (eg 1st, 2nd, 3rd) from a number. I use this a lot in date formatting. The argument n is just a locally declared variable, this function does not need any arguments passed to it.


Number.prototype.toOrdinal = function(n) {
  return ( this + ["th","st","nd","rd"][(!(((n = this % 10) > 3) || (Math.floor(this % 100/10) == 1))) * n] );
}


Usage:
var intNumber = 13;
var intOrdinal = intNumber.toOrdinal(); // output: "13th"

3) Convert a decimal number (also known as base ten or denary number) to hexidecimal (base 16 or hex) string. Hexidecimal is the numeral system that computers use. This is very useful for html colour codes which use 3 pairs of hexidecimal values to dictate the red, green and blue mix of the colour (so #CC130F is actually - CC 13 0F).

Number.prototype.toHexidecimal = function() {
  return this.toString(16).toUpperCase();
}


Usage:
var intNumber = 28;
var intHexidecimal = intNumber.toHexidecimal(); // output: "1C"


4) Convert a decimal number to binary. This is used the least out of the previous 3 number extensions, but it's included because it's elegant!

Number.prototype.toBinary = function() {
  return this.toString(2);
}


Usage:
var intNumber = 13;
var intBinary = intNumber.toBinary(); // output: 1101

You can also use these by putting parentheses (round brackets) around the number and calling the method. For example (13).toBinary(); outputs 1101, (40).toOrdinal(); outputs "40th", etc.

You may well notice that the 3rd and 4th number extensions (toHexidecimal() and toBinary()) use the native JavaScript object toString() method. When used with JavaScript numbers, this toString method allows you to pass an argument called a radix. In pretty much every numeral system we use, a radix refers to the number of unique digits that the chosen numeral system can use (including 0). So in the case of toBinary() we pass a radix of 2 because there are two digits that binary can use 0 and 1. In the case of decimal there are 10 they are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and in the case of toHexidecimal() there are 16 which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. The letters A-F are used in hexidecimal to complete the number of unique digits for that numbering system (the decimal equivelant would be 10-15 but as all those numbers (0, 1, 2, 3, 4, 5) have been used previously, they need to be replaced with unique digits).

So go, have fun with the numbers, be nerdy and spread the word!

Wednesday 22 November 2006

Lies, damn lies & statistics

I was having a chat with the Big Swede today, and he told me about his house getting burgled last year. It got me thinking and one thing led to another and I tried to work out (mathematically) my chance of being burgled whilst living in London. A quick search on google provided a link to the Home Office crime statistics website. As I'm flicking throught the site I come across the sexual offence statistics page.

I'm totally shocked by what it says.

"Seven per cent of women had suffered a serious sexual assault at least once in their lifetime (including rape) since the age of 16."

7 percent. That's staggering. To put it in perspective - educationnews.org says that dyslexia affects around 2-8% of school-age youngsters. I'm always reading about the latest initiative to teach reading and literacy, but rarely do you hear about victim support. There's some sort of dirty aura around rape that cloaks and taints everything that comes into contact with it. As far as I assumed (because I don't really hear about it) that there was support available but it's not that globally expansive - local support groups and such. Happily, I'm wrong. rape counselling pulls down more results than violent porn.

Statistics? That's one out of every 14.2 women. Now I'm looking around at the lads because I have more than 14 male friends, mathematically one of them is guilty.

Tuesday 21 November 2006

More coin flip

Just found out one of my mates got some bad, bad beats last night and lost enough money to buy a house in London.

Woah!

CSS image flickering solved in IE

There has been a problem for many years that most of us have come across developing for Internet Explorer with background images "flickering" when the cursor is hovering over them. (here's an example). This is due to to Internet Explorer checking for a new version of the background image declared in the background-image css attribute when the mouse hovers over the tag. The flicker issue may also be accompanied with the hourglass flicking on or even no image flicker, but the hourglass flickers!

<script type="text/javascript" language="javascript">
/*@cc_on @*/
/*@if (@_jscript_version >= 4)
document.execCommand("BackgroundImageCache", false, true);
/*@end @*/
</script>

Essentially, if you include this script somewhere in your page (best towards the top) then it will resolve this problem. Banzai!

The comments with all the @ symbols are actually JScript (Microsoft's version of JavaScript) conditional commenting. In simple terms, only IE will see and execute this code. In more complex terms it means only the IE compiler will read and compile this code. This means that should you have large forks in your script - one to deal with IE and another to deal with any other browsers - you can often get large performance returns from using conditional compiling. There's a good article on javascriptkit.com about conditional compilation of JScript.

I can't take credit for this solution - MisterPixel came up with the goods looking into DHTML behaviours in IE with regards to another problem (a bit like Fleming discovering penicillin!).

Coin flip

I love poker. I really do, there's something about it that's slightly geeky but quite risky and that appeals greatly to a snowboarding programmer. I've learnt some of the finer points over the past few years by picking up tips and hints from the pros, from reading books, studying odds and statistical methodologies through extended mathematics and watching lots of poker on tv/online. One of the current favourites is High Stakes Poker. Basically a high stakes cash game with a minimum sit-down $100k.

Even the pros get the game wrong though, sometimes impressively to the tune of many hundreds of thousands of dollars...
http://www.youtube.com/watch?v=uyAj0ZygG80


I've got to say Negreanu takes it on the chin, but he gets several bad beats over a session and goes down about 400k. I mean really bad beats - guys all-in for 100k chasing flushes and hitting rivers. I feel sorry for him, but then again I'm not sure I would have called an all-in raise in this hand. Maybe that's why he's a pro dealing in hundreds of thousand and i'm just dealing in just the thousands.

It all made me want to play a bit, so I logged onto my pacificpoker account and had a tinkle last night and did pretty well - won a $20 buy-in tournament. But it got me thinking - if you had £400k and someone said they'd double it by correctly guessing the outcome of a coin flip. Would you take it? Possibly not - I mean £400 is a lot and would make a big difference. But what if it was £4000? Not sure about you guys but well I'd probably say yes. 4k isn't going to make much difference, 8k will enable me to live it up for a ski season. So the happy medium is somewhere between 4k and 400k.

The trouble is that every poker player will tell you, that gamble's not bad odds. You get a 50% chance at a 100% profit. Basically the maths is relatively happy. But as any poker pro will tell you, they'll bet a 51% chance every time because if they do that every time it comes up over the course of their betting lives, they will always end up that 1% up. I always think that this attitude exemplifies betting all over the world (including bookmakers/financial markets/hedge funds/etc) where the amount of money that is willing to be gambled grows exponentially as to push up the monetary value of the 1%. Every now and again obviously, this goes seriously tits up when a stock market crashes and the vast majority of investors lose a ton. But then they all seem to go back for more. Maybe in the same way Negreanu doesn't walk away from the table after such a big hit to his money in order to clear his head - I feel if it was me losing that much, I'd be crying on the floor, sucking my thumb, waiting for the woman in my life to beat the crap out of me when I got home.

How much money would you gamble on the coin flip?
P.S.
Found some amusing famous bets as well today whilst researching this post.

Thursday 16 November 2006

Registry hacking

Note: This is Internet Explorer only as it deals with ActiveX and modifying the system registry.

Recently I've been writing a few scripts to change values in the system registry. In actual fact, you use a few different technologies to achieve something that looks very simple. This script reads then sets the home page for Internet Explorer via the registry. However you can edit any registry value you wish to using this method.

Background
Firstly what is the registry? In simple terms, the registry is a database that stores settings and options for Windows and contains information for all the hardware, software and preferences of the PC (http://en.wikipedia.org/wiki/Regedit). This script uses a combination of JScript and ActiveX in a Windows Script host environment to edit those bits of information in the registry. JScript is Microsoft's Active Scripting implementation of ECMAScript (http://en.wikipedia.org/wiki/Jscript). Basically it's their version of JavaScript, but with lots of add-on features. These "add-ons" also rather nattily work in any Windows Script Host environment - and that's been shipped by default with every version of Windows since Windows 98 or with Internet Explorer 5+. Further information: http://en.wikipedia.org/wiki/Windows_Script_Host. We can use this JScript to create an ActiveX control to pass information from our script into the registry. ActiveX is simply as mechanism for passing information around a Windows computer. All in all, pretty neat eh?

Here's my script:
<script type="text/jscript" language="jscript">
var objShell = new ActiveXObject("WScript.shell");

/* Get the current home page */
var strRegKey = "HKCU\\Software\\Microsoft\\Internet Explorer\\Main\\Start Page";
var strCurrentHomepage = objShell.RegRead(strRegKey);

/* Set a new homepage */
objShell.RegWrite(strRegKey, "http://nargster.blogspot.com/");

</script>

Let's go through it.
The script attributes
<script type="text/jscript" language="jscript">

These are set to jscript because this script is only to work in IE it's not vital, but it's good a good habit to get into.

Create an Windows Script Host (WScript) shell object
var objShell = new ActiveXObject("WScript.shell");

OK, so we're going to ask the script to create a new ActiveX object (as mentioned, this is just an information carrier) to pass information to a particular target - in this case the Windows Script Host (WScript) shell. The shell is simply interface that enables access to the inner workings of the computer - we need to create this shell object in our script to access the registry.

Accessing the registry
var strRegKey = "HKCU\\Software\\Microsoft\\Internet Explorer\\Main\\Start Page";
var strCurrentHomepage = objShell.RegRead(strRegKey);
objShell.RegWrite(strRegKey, "http://nargster.blogspot.com/");


Now we've created a shell object, we can access the properties and methods of that object. Two of its methods are called RegRead and RegWrite - they read and write the registry respectively. The example shows the arguments required for these two methods. In both we pass the registry path of the registry item we wish to edit, making sure that we replace any single backslashes \ with a double backslash \\. This is because the backslash character in JScript is special - it's an escape character. The strRegKey string is the path to the value we want to change, you can find more information about how this string is built by looking through the registry using regedit, explained below. It's easy to see how the string relates to the structure of the registry, it's like a filesystem folder path.

Regedit - the registry editor
So you want to find out what the registry looks like to browse through. I'll not kid you - it's massive. You can use regedit, the registry editor (Start Menu --> Run, then type regedit and hit enter or run regedit.exe or regedt32.exe in your Windows directory) to have a look around and adventure. The registry structure is too detailed to go into here, but Wikipedia do an excellent job of it: http://en.wikipedia.org/wiki/Regedit

A last word just on security
It does seem incredible that Microsoft would create a web browser that could run scripting to read and write the system registry, but that's what they've done. They've tried to correct this problem in IE7 by not allowing the creation of ActiveX controls by default - users must enable this manually (with accompanying nasty messages about potential insecurities). In other supported versions of IE (IE3 - IE6) the default behaviour is that this simply runs with an ActiveX warning message. You can get around these warnings by saving the html file with an hta extension, turning the html file into an HTML application (MSDN). This .hta file only runs locally on a machine and runs without the strict security model the browser uses - no nasty error messages!

Play around with the registry - you could potentially damage something, but stick to the simple stuff and work your way up and it should all be good. Using .hta files is good because it opens all sorts of potential for html/scripting without security restrictions, so you can make cross-domain AJAX calls - something which is not allowed in a webpage) as well as other funky HTML applications to change the settings and tailor your computer.

Windows Script Host programming reference
There's loads of methods and properties of the shell object - you're not limited to reading and writing stuff to the registry - you can set/retrieve/delete user information, network and printer settings, read and write files and much more. You can find details of this at devguru.com in their Windows Script Host reference:
http://www.devguru.com/Technologies/wsh/quickref/wsh_intro.html

Tuesday 14 November 2006

Panda porn

http://news.yahoo.com/s/nm/20061111/sc_nm/life_thailand_panda_dc

Someone's shot a video of pandas mating to get a captive panda "in the mood" to encourage him to breed. Couple of things. Who would shoot this video? If it's David Attenborough then someone should really address the situation. Anyone who spends that much time and effort watching animals have sex should clearly be put on some sort of register. Another thing is what's the film about? Is it like a girl panda in a nurses uniform or something? Are there like 5 boy pandas and one girl panda? Better still are there like 5 lady pandas and one man panda (one extremely happy man panda I might add).
Filth.

Garbage Collection

Thought I'd post up a bit I wrote at work discussing differences in memory handling and garbage collection in different browsers.

Background
Microsoft's implementation of ECMAScript is actually called JScript (not JavaScript), and it's behaviour with regards to garbage collection differs from the original implementation of JavaScript in SpiderMonkey (SpiderMonkey is the name for the first JavaScript engine written by Netscape, Firefox is based on this engine). It's worth noting that the JScript/JavaScript engine does not itself provide a host environment for the DOM - they are two separate structures that exist together, but can logically exist apart.

The main difference
IE uses non-generational mark and sweep garbage collection versus SpiderMonkey's generational mark and sweep garbage collection. The "mark and sweep" bit means that each object (either JScript or JavaScript) has an attribute that is set to 1 if it is to be collected and 0 if it is not. As the generational/non-generational bit of the name implies, what it means is that SpiderMonkey will find older objects first and clean them out (generational), whereas IE will do this fairly indiscrimately and just find JScript objects in memory and check to see whether to garbage collect them (non-generational). Simply put SpiderMonkey will push the objects to be collected to the bottom of the memory heap (http://en.wikipedia.org/wiki/Heap_(programming)) and then knows to grab the bottom of the pile to free memory, whereas JScript will throw objects (relatively) randomly onto the heap and then pick through all of them individually checking to see if that object needs collecting. As you can imagine there's an impressive performance lean towards generational garbage collection.

Implications
Because of the relationship between the DOM and the JScript/JavaScript engine, stacking objects in memory becomes very important. As you can imagine, keeping less objects in memory now has real performace implication in IE - especially circular references between the engine and the DOM such as an array of nodes - an example of this problem would be memory leaking through event handlers in the DOM (http://www.jibbering.com/faq/faq_notes/closures.html#clMem) - in fact this problem surfaces with any sort of large numbers of data types/objects held in memory at one time. It also should promote forced memory handling when resources can become free, rather than simply waiting for automatic garbage collection to be initiated (statements such as "myArray = myString = myNumber = null") to make sure the object has the least memory allocated to it after use and the automatic garbage collection then becomes much quicker.

Links to more info
Garbage collection: Wikipedia Garbage Collection
SpiderMonkey: Wikipedia SpiderMonkey
Garbage collection models: North Eastern University

Monday 13 November 2006

Mood music update

Just saw the itunes counter that checks how many times a song's been listened to. According to the ticker Enya - Caribbean Blue has been listened to 34 times today (35 if you include the fact it's still coming through the headphones). That's bordering on some fairly serious obsessive behaviour.

enya logo

Going to go to the pub for a beer, hopefully won't end up like rain man.

Mood music

I was looking at a clip on youtube earlier about a german guy called The Trainrider who spent the last year of his young life trainsurfing around europe before dying of leukemia. The intro music to the clip is a piece by Enya called Caribbean Blue and it's a fairly recognisable tune. The celtic calmness got my juices going so being of focused mind immediately downloaded the whole track from alltunes.com. I love pieces of music that get you thinking, sometimes the words or the feeling they give you, but ultimately it's the mood they put you in. Spark yourself up in the morning listening to the Grease soundtrack, chill out later listening to Massive Attack, free your mind with Led Zeppelin. It's like a personal psychology experiment.

I like to think that this song by Enya is fairly sad, soulful and relaxing. In fact it almost brings a tear to my eye when I listen to it, but there's an overall sense of contemplative happiness that I get which is an interesting contrast. Everyone has a song like this they know, one that makes you sad but you don't know why - or maybe you know why it makes you sad but can't let it go.

Working the way techies do means you're surrounded by music in various formats, and there's such a range of music to listen to that you rarely just stick your entire collection on random and hit play. You pretty much stick to choosing album/artist/playlist according to your current mood. I'd love to write a program that stores the music I listen to during the day so at 6pm I can look back and see if the music I listened to affected my day greatly in any way. Or even over the week - see which days were good, which were bad and what music you listened to. I reckon there would be some interesting results.