Monday, 26 December 2011

Hot water

I am staying with my parents for Christmas, which has been, as always, fantastic. They live in the country with many of the home quirks that come with being out of the city. So, for example, you can only get reception if you leave your phone on the back of the sofa in the lounge or on the window ledge in my room. There is also quite low pressure in the water pipes in the bathroom.

The water pressure requires you to run a bath on full hot for 25 mins - the hot water comes out just below boiling, so there's no putting your hand in to test the temperature. The cold water comes out super cooled at a temperature of about 4 K, so you have to micropipette 0.25ml into the bath. If your hand slips you are left with a bath that will kill you after 30 seconds of submersion.

Despite 2 years of chemistry practicals at uni I have yet to have a warm bath this Christmas. It's particularly gutting when I watch my parents wander off, leaving their bath running with careless abandon, come back, adjust the taps with the precision of micro-biologist and jump in a perfect temperature bath.

How? How do they do it?

Wednesday, 26 October 2011

Memory Booths

Being on holiday is cool, I'm currently catching up on my reading and another of Derek Parfit's awesome thought experiments has me thinking.

The idea is that I could go on holiday and on my return home, go to a memory booth and have the memories stored on a disc. I could pass this disc on to friends who could visit the same store and have my holiday memories uploaded to their brain. Giving them the memory of my holiday. They would then have a memory of somewhere they hadn't been.

Possibility

The technical possibility of this process was never the question. It is merely a postulate to open a discussion on what constitutes a real memory. Can you have a memory of something that didn't happen? What is "the self" are we a "stream of conciousness"? What would happen to that stream if the memories that are the link backwards in time to "me" 5 years ago, 10 days ago are false?

My interest

While the above questions are interesting, what really caught my attention were the sensory questions raised by having someone else's memories. When I remember certain events, I do not just remember the details of an event, I remember the emotional context of the event. For example, if I remember an argument with someone close, I also remember the feelings of anger or hurt.

What would it be like to experience someone else's feelings? I love that first wave of heat when I get off a plane in a hot country. Other friends have told me they feel the same, would this friend? How stressed would the friend get trying to find a taxi and a hotel in a foreign country? How much better would I understand them after walking a mile in their shoes?

Imagine the first meal at the restaurant, it sticks in your friend's memory vividly due to the excellent prawns. However, you hate seafood... would you enjoy them in this memory? Or would there be some sort of conflict?

Imagine your holidaying friend does a bungee jump... What would their feeling of exhilaration be like? Do they experience excitement in the same way you do? Or is it a totally alien feeling? Imagine you are afraid of heights, could there be such a conflict that your mind rejects the memory? In the same way that the body recognises donated organs as foreign?

Social uses

Could the victim of a crime give their memory of the incident to their aggressor? Could this be a more effective form of rehabilitation?

I have had quite a nice day today - tomorrow I might even leave the house...

Sunday, 18 September 2011

Breakfast of Champions

Why were so many Americans treated by their government as though their lives were as disposable as paper tissues? Because that was the way authors customarily treated bit-part players in their made-up tales.

And so on.

Once I understood what was making America such a dangerous unhappy nation of people who had nothing to do with real life, I resolved to shun storytelling. I would write about life. Every person would be exactly as important as any other. All facts would be given equal weightiness. Nothing would be left out. Let others bring order to chaos. I would bring chaos to order, instead, which I believe I have done.

If all writers would do that, then perhaps citizens not in the literary trades will understand that there is no order in the world around us, that we must adapt ourselves to the requirements of chaos instead.

It is hard to adapt to chaos, but it can be done.

Breakfast of Champions, Kurt Vonnegut

Friday, 6 May 2011

So, AV or FPTP

Obviously, AV seems a much fairer system when you look at the maths of it, this blog post describes things rather well. However, the concept of AV being "better" is only a good thing if the underlying system that it improves is worth while. For example, using cup to get drinking water from the toilet bowl rather than sticking your face in there is a better method without being an ideal way to acquire water.

As I see it, the underlying system in this case is that the general public should get to have a say in how the country is governed, by selecting a candidate from 1 of 5 or so groups offering expertise in the area. Now, if we ignore such complexities as whether these people are actually in a position to run the country or not and focus on the concept that running a country is a specialist job. Can we think of any other scenarios where we'd let the great unwashed public decide... well... anything?

I'm imagining NASA and two top engineers discussing the 3 most relevant theories of jet propulsion. Each gives a different answer and only 1 can be right.

Scientist 1: "Ok, well I just can't work it out, this is a total stumper."

Scientist 2: "Likewise, I guess the only thing left to do, is fill a room with people of average intelligence and get them to vote on it."

Scientist 1: "yea, make them mark the paper with crayon - edible crayon, we don't want a repeat of last time."

I walk to work and so I see a fair amount of the public. I believe it would be a landslide victory for the theory with the best name.

Scenario 2 - "we interrupt this episode of Coronation Street / So you think you can dance / Big Brother to inform viewers that the bomb squad is at an impasse, please dial the following number: ----- then press 1 for the green wire, 2 for the red wire or 3 for the blue.

Of the people I see in the street, I reckon I could trust 1 in 100 to vote on the correct way to run a bath. Perhaps we are better off with a smaller percentage of the population making decisions and our vote should be about how to select the right smaller percentage of the population. In much the same way that I have never put my xrays up on ebay to get a more rounded opinion of what is wrong.

Obviously this isn't a trivial issue and my only aim here is to gently mock, but I wonder what a country would be like if people who knew about stuff were in control?

Saturday, 16 April 2011

iphone web apps

I work on a mac at home and like it quite a lot, I am also a big fan of windows 7, so I have no axe to grind on the "fan boy" front. I have been working on a mobile development project recently and thought I would share my findings and thoughts. We decide to build a W3C Widget HTML, CSS and JavaScript packaged up as a web app. Because the iphone and Android don't yet support these we are wrapping them with the awesome Phonegap. At present, we are resisting the urge to use Phonegap for anything other than wrapping.

When Apple first said they wouldn't be supporting Flash on their mobile products, I thought it was a brave move and a sensible one. I justified it on the grounds that a big part of the problem with early Windows systems was that it allowed developers to do whatever they wanted. Many of the reported crashes with which Windows became synonymous were due to bad software rather than the operating system. I am mainly concentrating on "flash has not performed well" section of Apple's argument and less so on the "we're making the web an open field of delights with puppies for everyone" (1 of many sources on Apples position).

Developing on the iphone has given me a further glimpse into where this position has taken Apple. It's been quite interesting to work on a project where I have had multiple mobiles to develop on side by side.

Mobile libraries

Initially, we went for jQuery Mobile, which at the time was still in alpha. I think it will be an excellent product when finished if you want to do rapid mobile development using jQuery and it's theme system. I am not a bit fan of having the structure of my HTML and CSS taken away from me, especially by something in such early stage of development. So we decided to hand roll a mobile library, which was relatively easy, quite performant and a great learning experience.

position: fixed

At first we only had an Android to test on, while we waited for the iphone and developer licence - oh and the mac we'd need if we wanted to develop for the iphone... The app we built had a header, main and footer section. We affixed the header and footer with position: fixed and all was well. The first time we tested with iphone, we realised why jQuery mobile was using a JavaScript solution. Because many web sites built for desktop use large header and footers, supporting position: fixed could cause lots of sites to display poorly on a mobile phone. Apple's position seems to be to remove support for position: fixed as a preventative measure. PPK explains and has suggested a solution however, web developers are left hacking in fixes. We decided to hijack the touch events and build our own scrolling mechanism - on the iphone css transforms for the scrolling give a much better effect than the usual manipulating the CSS top.

Video

I was disappointed by my android when I found that it refused to play my html 5 video in either ogv or webm format when in webview mode (i.e. as a web page installed as an app). The same video would play perfectly well when browsed to normally. The iphone on the other hand was lovely, it played the video flawlessly, if you don't mind it taking control of the playing of the video fullscreen. However, the video element ignores all touch and click events. This is because it requires them for it's own controls. In theory, removing the control attribute from the video element should allow you to attach events, however, in our web app, this has not yet been the case - investigation continues.

I am torn here in that I like using my mac and it's ease of use, stability and performance. I dislike the reduction of freedom involved with the iphone and ipad - which is why I have an Android. But then, I bemoan the performance of my Android... What tears the balance for me, is developing for Apple, where I can't use standard code because Apple has deliberately stopped support without providing an alternative. This seems counter-intuitive from their point of view as it forces developers to introduce hacks outside of Apple's quality control.

Friday, 8 April 2011

Customer service tips

Ok, so, I am going to write this as a "how to improve your company's customer service" post to disguise the fact that it's merely a rant about Currys. Obviously I am going to avoid mentioning I purchased something from the same chain as PC World, because that makes everything that happened my own fault for choosing a company renowned for poor service.

Tip the first

Say a handsome young man walks into your store and orders a new fridge freezer. He then pays 10% extra just to have it delivered at a specific time. This customer is telling you something very important about his priorities: his time is worth more to him than that amount of money. This is very useful information if you want to keep him happy as a customer.

Tip the second

If you are going to use technology, use it wisely. If you have a "when will my stuff be delivered" section on your website, have it detect when the estimated delivery time has elapsed. If it has elapsed, offer the customer a contact route, remember, at this point they are likely frustrated.

As with the website, if you offer a phone service with a "if you are phoning about a delivery press..." service, if the delivery time has elapsed put the customer through to a representative, don't leave them with a constantly looping message telling them their item will be delivered at some point in the past.

Tip the third

Be helpful. I personally don't care how many times someone from a call centre tells me how sorry they are to hear I have an issue. I may be cynical but I am yet to be convinced of their genuine nature. This feeling is compounded when the person who is very sorry is also incapable or unwilling to be even remotely useful. I want to know when my item will be delivered and I also want a refund for the service I paid for and didn't get.

Tip the forth

Don't say stupid and annoying things which are not true. "I will fix this for you immediately":

  • That statement should not be followed by on hold music.
  • In my case, it would involve time travel.
  • "Fixing it" does not involve explaining why my delivery is late.
  • "Fixing it" does not involve not being able to give me a new ETA.
  • "Fixing it" does not involve not being able to give me a refund.

Tip the fifth

Make getting a refund easy. If someone pays money to save their time, making it difficult and time consuming to get a refund makes them feel cheated. Empower customer service people to give unhappy customers what they are looking for and entitled to.

Sunday, 27 March 2011

Top 5 games

This is a trip down memory lane and makes me want to install an emulator. You can have any game on the platform of your choice, with updated graphics, but the game play must remain the same.

  1. Elite

    Possibly my most fondly remembered game, I would have it as a console game now with updated graphics. I played this space based fighter / trading game for days and days, then weeks and months. It's open ended game-play allowed your imagination to turn it into a role-playing game inside your head. I, like so many others, think it should be resurrected as a modern game.

  2. Ultimate Doom

    I would have this as a console game too, with updated graphics. The arcade style action made this game ultimately re playable, it's one of the few games I can still clearly remember the route through quite a lot of the levels. It also had some amazing game-play moments, I still remember the ground shaking and seeing my first Cyberdemon - awesome. It also had fantastic level design and a co-op mode.

  3. World of Warcraft

    There's not much to be said about wow - it's like the heroin of addictive games, nothing else will suck down the hours quite like it. With a decent group of friends, there are few gaming experiences to match it. It is probably unrivalled in delivering memorable gaming moments, from your first epic, to seeing the Fel Reavers for the first time. I only stopped playing when world pvp become almost impossible to find.

  4. Unreal Tournament 2004

    My favourite online shooter of all time, I even spent hours practising against the bots. Bombing run was one of the best game types I have played - shame no-one else agreed and it was removed from future versions.

  5. Super Smash T.V.

    I wouldn't change a thing about this game, not the controls, the graphics, the console and certainly not the cheesy one liners "I'd buy that for a dollar". Way too many happy memories of both single player and 2 player mode.

Honourable Mentions

There are lots of amazing games I missed out - notably the plot driven games, which I feel lack the longevity for this type of scenario - Half Life (I didn't get into the multiplayer), System Shock 2, Assassin's Creed II, Dead Space 2. I also didn't have room for Quake 2 or Diablo - really looking forward to Diablo 3.

Top 5 T.V. Shows

This is a tough one as there are so many good series that were cut short with only 1 or 2 seasons (Terminator: The Sarah Connor Chronicles). Conversely, there are many average shows which aired relentlessly. Quality or quantity... hmmmmm.

  1. Archer

    Only in it's second series, but definitely the best thing on T.V. atm by some considerable distance. Adult viewing, not for the faint hearted, but it really does make me laugh. There are some things that only an animated series can get away with.

  2. Sons of Anarchy

    Another amazing series from FX. This details the ups and downs of a motor bike club. The premise didn't grip me at all at first, but I was badgered into watching it and was gripped from episode one. Fantastic story and great characters.

  3. Married with Children

    An oldie, but a goodie. What can I say, Al Bundie makes me laugh and he is personally responsible for my love of New York Cheesecake.

  4. American Dad

    I have too many fond memories of Stan and Rodger to miss this one out. When a series has added new accents and phrases to your way of speaking, you know it's had an effect - "Dimmer switches!". I have championed American Dad over Family Guy and seen a few people come round to my way of thinking.

  5. House

    As with all the series mentioned here, I can watch re-runs of house all day. I take the criticism that the episodes are formulaic - no-one knows whats wrong with the patient; things get worse till House decides to do something totally unorthodox; everyone disagrees, but House is right and saves the day. I don't watch the series to see what happens to the patients though, I watch it for the characters and the sub plots.

Honorable Mentions

Breaking Bad is an outstanding series, but it is very much story driven, so it's replay ability is low for this list - highly recommended though. Firefly was terminated during the first season, but was awesome. Fringe is a very easy watch too.

Top 5 babes in heaven

Because it's heaven you get five babes frozen in time at their prime. Choose well, as you have to spend eternity with them!

  1. Park Min Young

    A korean dancer who is fated to be the next Mrs Ant, as well as being an amazing dancer, her t.v. interviews seem to show her as impossibly sweet as well. If I was to watch one video for the rest of my days, it would be the one linked in the above.

  2. Michelle Pfeiffer

    She is just the awesome, no meal in heaven would be complete without her draped over a piano singing to me ala The Fabulous Baker Boys. She is probably my only enduring crush...

  3. Audrey Hepburn

    A true icon and IMHO one of the most beautiful women of all time. I haven't read much about her life, but I would be absolutely gutted to read that she wasn't a nice person. In the theatre of my mind, she is as sweet as she is lovely.

  4. Charisma Carpenter

    As well as being stunning, her character in Buffy the Vampire Slayer rocked the show. It seems in real life she's into rock climbing and fitness, it doesn't get much better than that!

  5. Elisha Cuthbert

    Unlike many of the other top 5's I was hard pressed to fill this one. I remember Elisha making my toes curl when I watched 24, but I've not seen much of her since.

In the honorable mentions list I would add Elle Macpherson and probably Kelly Brook, but really, I'd be happy with my top 4. I would worry that I may neglect number 5 and that would be rude...

Friday, 25 March 2011

Top 5's

I quite like making lists of things I like and trying to get the perfect 5. Rather than just being my favourite 5, the 5 things have to complement each other so that they create the perfect grouping. Here's my current thoughts on things, written down so I can look back and see how my thoughts have changed.

Top 5 authors to take take to heaven

If I was allowed to take the complete works of 5 authors to heaven and read only these books for the rest of eternity. So the authors have to be varied in pace, style and subject matter. They also have to have a fairly large collection of works to keep me going. This last point in some ways caused me the most grief - I've had to leave behind some of my favourite books because the author was lazy :)

  1. Ernest Hemingway

    I really love the way Hemingway writes, so I would be happy re-reading his works and even studying them to some extent. As he wrote some of my favourite books (especially The Old Man and the Sea) he was pretty much a shoe in for first place.

  2. Philip K. Dick

    Another shoe in, my favourite sci fi author and a prolific writer. His books are interesting, thought provoking and worthy of re-reads. His writing style sometimes requires effort on the readers part, though always well rewarded.

  3. David Gemmel

    My first "easy read" author, Gemmel was a childhood favourite and I still find many of his characters as engaging today as I did back then. His work is intelligent heroic fantasy and since his sad passing I have struggled to find a replacement author for the genre.

  4. Cormac McCarthy

    I just couldn't go to heaven without a copy of The Road, I rate it as my favourite novel mainly due to the prose. He paints a picture of such draining darkness that you see the characters in black and white. His other works are also excellent, but The Road is transcendant.

  5. Robert Anton Wilson

    One of the truly great minds of our time and a personal hero. He wrote both fiction and non-fiction on a truly inspiring variety of topics. Whilst some of his work was so heavily based in the ethos and culture of the 70's it seems a bit dated stylistically, the ideas are as relevant today as ever.

Honorable mentions

There are so many honourable mentions it's just as hard trimming these down. First off, I am sad I have no Eastern authors in my list, both Bulgakov and Turgenev were definitely in the running. Vonnegut was replaced by McCarthy. I will miss Heinlein's Starship Troopers and Job II, but along with William Gibson and Neal Stephenson he was pushed out by Philip K. Dick. Herman Hesse and A. E. Housman would have added to the collection with their style and subject matter. I also really like Jeff Lindsay, author of the Dexter novels of the popular TV series. Still, if making the list was easy, it would be no fun.

What would yours be?

Sunday, 20 March 2011

Popular Science

I am quite a big fan of popular science and have been watching prof Brian Cox's Horizon series with interest. I think it's an awesome show and I like the way information is presented to the viewer. However, I have been wondering for a while about scientific "leaps of faith". I don't see anyway around them and as part of my own view on the universe, I am quite happy to make them, simply because I understand that is what I am doing. My concern is that recently I have seen people accepting things as fact because "science says it is so".

"Can you get the project finished by Friday, yes or no?". Despite being the question being couched to provoke a boolean response, the question may well have more than 2 correct answers. The most correct is likely to be "Well, it depends". Despite being the most correct it is likely to be one of the least satisfactory possible answers to the asker. People don't like uncertainty and this often clouds the answers we give or alters the way we talk.

Leaps of faith

If I am making a point the validity of my argument will rest on some key ideas. If my argument rests on the value of x in the following: x - 2 = 7 and I state that x is 5, almost everyone will be in a position to know if I am correct or not immediately. However, if I state that for the inequality 3x - 7 > 5x + 11, x < -9, well, I'm guessing that the number of people who would go to the effort of solving the problem decreases significantly. If I then argue that E = mc2, well I think you see where I am going.

Of course, the validity of my claim can also be tested in practical application. For example, if I am talking about the pressure of a gas increasing with temperature and quote pV = NkT (the ideal gas law) you can rely on the fact that this is principle through which steam engines work. Thus gaining a degree of confidence in my point without resorting to first principles.

There are circumstances where the evidence isn't completely in yet and statements are made based on a consensus of opinion using the data that is currently available. One statement like this would be "the universe is 13.7 billion years old and will go on for ever...". The current evidence does seem to point in that direction, however, it's not the only possibility. It is possible that at some point in the future a new source of dark matter will be discovered, giving the universe sufficient mass to be closed. It doesn't seem likely, but it's far from impossible.

Reasons for post

I worry about the blind belief in "science" without the necessary tools for reasonable scepticism. Being wrong about the ultimate fate of the universe is one thing, but being wrong about the right type of medicine for you is entirely another. Whilst I applaud the current wave of scepticism over religion and homoeopathy, it unfortunately seems to go hand in hand with a blind acceptance of "scientific" western medicine. Pharmaceuticals are not produced by people working in the pursuit of pure knowledge, they are created by large corporations built to produce profit.

The current scientific thoughts on a subject are not dogma. Science is not a religion with absolute truths being handed down from on high. The scientific method is merely the best way we know of to solve problems and find answers. It is based on trying to find fault with the current theories of the day. It requires you to be sceptical of everything, not just those ideas which are not currently in fashion.

Friday, 11 March 2011

More Books...

Shardik

It is as the sleeve blurbs says "an epic allegory" and a "human saga". However, I have to say that it is a little heavy on the epic and a touch light on allegory for my taste. Perhaps I came at this book from the wrong angle, but I read Stephen King's "gun slinger" series in which Shardik has a small cameo and thought "you know, I really should read that". The book is well written and I really liked and agreed with the points about humanity it was making, but I spent way too long thinking, "yea, I get it" only to find that we were going to stick with the same theme for the next 100 pages just to ram the point right home. For me, the book could have been an awesome 300 pager and still had room to make more use of the fact that it has a massive kick-ass bear as the title character :).

Slaughterhouse 5

I read this book and instantly became a Vonnegut fan, writing these notes has reminded me I still have a few novels lined up to be read. A very personal book, which also, at times, trips the bizarre-o-meter, it really is a proper classic. Sometimes you enjoy a book because the story is interesting and the writing isn't bad enough to jolt you out of the world your imagination has created. Other times you get to read a book where the story has been crafted, by a real author, and you are transported into someone else's world with its own set of rules and laws. To describe the story itself in any way that had real meaning, I'd probably have to re-print the book, but it's kind of about the Dresden fire-bombing from an antiwar point of view.

Faust

Yea, one of those "I really should read it" things that I decided to cross off my list. It's an epic poem about Faust's deal with the devil, their beguilement of the lovely Margaret and Faust's desire to repent of his treatment of her.

I felt the reward to reading this was more in the destination than the journey. It was hard work at the time, but I am really glad I read it and can now enjoy certain passages on re-reading. I also feel a bit smarter when Stephen Fry quotes it on QI :)

The Wind-up Bird Chronicles

This is one of those books you read with no pre-knowledge of the plot. I am loathe to describe the plot as I really am not going to make much sense without describing a fair bit of detail. I liked the style of writing quite a lot here and I think this originally lead me to expect more from the story than I eventually feel I got. This is actually a minor criticism as there are some outstanding set pieces and a few memorable moments. It's well written and gripping to the end - I think I just expected spectacular as opposed to good.

The Grand Design

A very readable popular science book, fascinating content and well presented. I read it in two plane journeys, simply because it's absorbing and maths light. In someways I was prepped for a little bit of the science by reading "The Omega Point" a much older work (also popular science) so some of the concepts were familiar. I immediately fell for the idea of M Theory because it complements the theory of psychological reality I have been thinking about for a fair while. The very basic idea being that there are a collection of overlapping mathematical theories that define the universe rather than one unified theory to rule them all.

A Farewell to Arms

I like Hemingway, a lot, but the start of the book confused me a little, the constant overuse of "and" to link descriptive sections made me wonder what to make of the narrator. Eventually I think it just made me trust his naivety, it's something I remember about the book though. I felt connected to all the characters, not always immediately, but eventually and strongly. There is a section of the book where you know for a long time that something bad is in the post, this gave me a tremendous sense of foreboding. The arrival of said "bad post" was delayed by the plot making me became more and more emotionally involved as I tried to guess which way the story would go. Highly recommended from a personal point of view, but I can imagine people with whom the emotional attachment to the characters doesn't take disliking the seemingly unnecessary elongation of the plot.

The Master and Margarita

I really like the Russian authors and so when this book was recommended to me, I moved it to the top of my list. It contains a retelling of the tale of Pontius Pilate with a nice twist on the Faust legend (It's synchronous that I read Faust then this in succession without knowing the plot of this book). A well written and evocative novel which left me thinking about the story for quite a while afterwards. I found the novel held my interest from the start, but the ending is worth getting to even if you don't.

Saturday, 5 March 2011

Training - current state of play

I've been running quite a lot recently. One long run per week along a track that takes me an hour and a half to run. I've no idea the actual distance and I will admit to finding excuses not to measure it, in case it's not as long as I hope. I also do a shorter run at about 5k - the idea being that I really need to work on my pace. I can manage all of this fine so long as I don't try and train my legs, which is difficult as I've been enjoying some dead lifting recently.

I am also managing to get between 1 and 2 yoga sessions a week. I really feel they've worked well on my legendary lack of flexibility. I am now merely in the "very poor for his age range section" as opposed to my previous "freakishly inflexible and to be mocked on sight", which is nice.

On the weights front things are going quite well, I've dropped my body weight down to 103kg, but have worked my bench back up to 5 sets of 5 at 120kg. As a consequence of my weight loss, my pull-ups are pretty sweet at the moment with my first set at 15 and tapering off after that.

Thursday, 3 March 2011

Ollie Williams explains black holes


  • Tom Tucker:And now over to Ollie Williams to find out why black holes are black, Ollie?
  • Ollie Williams:Light can't escape!
  • Tom Tucker:So light can enter a black hole, but not return?
  • Ollie Williams:Yes!
  • Tom Tucker:Isn't that a clear violation of the second law of thermodynamics, Ollie?
  • Ollie Williams:No!
  • Tom Tucker:Why, Ollie?
  • Ollie Williams:Has entropy!
  • Tom Tucker:How, Ollie?
  • Ollie Williams:Hawking radiation!
  • Tom Tucker:Thanks Ollie

Saturday, 19 February 2011

Parsing JSON

For reasons I won't go into, I had need to write a JSON parser recently - yea, I genuinely couldn't just use Doug Crockford's json2.js. It was my first attempt at writing a parser and was an awesome learning experience. I was lucky that I had some pretty smart people on hand to help with the methodology for doing this. The process is relatively simple once you know how, but I will admit it took me a while to get my head round how to approach the problem.

The task was to write something that would take a JSON string and parse it back into a JSON object. The string might contain n depth of nested types (for example an array of objects with each object containing other objects or arrays). I initially expected to have to work out what the first tier primitive types were, then recursively pass in their contents to the parsing functions. So, I was somewhat surprised to find that the method suggested to me was simply to run through the string character by character, from left to right, keeping track of my position within the string, recursively calling the parse function each time I found a symbol which denoted a new primitive.


Functions

I wrote a few helper functions:

  • ignoreTrash - which moved past trash characters in the space between primitives, such as spaces, commas and semi-colons
  • MoveToNextCharacter - which moved the string position counter
  • amEscaping - which checked for backslashed quotes

Ok, so that list was shorter than I recalled. The parse function itself was really just a glorified if statement, looking for the first character in the string - if it is quotation marks, call parseString; if square bracket, call parseArray and so on.

The parse primitive functions would create a new object of their type, then they contained while loops to move through the string until they found their corresponding terminator symbol (usually a regular expression). If during the parsing they found another starter character, they simply called the main parse function again.

It all sounds pretty simple and the nice thing is that the code is really readable, but at the time, it took me about a day of thinking hard, to get my head round the concept. Still it was time well spent, as I think I learned quite a lot during the process. Unfortunately, one of the things I learned here is that the browser implementation of the javascript regular expression engine is a real let down on most browsers. The language seems to support groupings using parantheses, allowing lookahead and lookbehind, but I certainly couldn't get them to work.

Monday, 7 February 2011

XULRunner - an odyssey

When I first discovered that we were using XULRunner as part of our app. I have to admit to being quite excited. I thus jumped at the chance to work on that part of the project when the opportunity arose, a chance to play with some cool technology and learn a thing or too. The project sounded pretty interesting, create a small interface in XUL and add some functionality to it. Then implement some of browsers accessibility features and open them to the web page through an API.


XUL

XUL itself is fairly nice and the MDN documentation is readable enough to make initial progress rapid enough to be fun. However, I was a bit disappointed that CSS support is not complete, in particular z-index is not supported, which immediately removes you from your confort zone when trying to make your interface cool. There are two entirely reasonable solutions to these problems, the easiest is simply to abandon ideas of web 2.0 interfaces and go with what XUL provides natively, such as overlays. The other is to add html elements into the mix. Clearly, these must be namespaced to differentiate them from XUL elements, as outlined in MDN

So far so good, XUL is pretty simple and the documentation is helpful, lets move on to adding the functionality... This is where, unless you are doing something pretty trivial, problems can occur. It's not that the way XULRunner works is difficult, or indeed illogical, it's that the documentation is sparse, confusing, confused or a heady mixture of all 3. I ended up coding initially by trial and error, which is a big problem because de-bugging straight out of the box in XULRunner is painful. After a bit of searching, I found a great resource for setting up a reasonable debugging environment.


The type attribute

It turns out that when opening an API from the chrome to the browser, the type attribute is very important. It seems a little odd to me that the default setting for type is "chrome" which carries a security warning. It also seemed odd to me that when trying to access the API with this incorrect type, there is no error, the functionality simply appears buggy, for example, when accessing the full zoom property the page zooms, but only partially requiring a screen redraw to display correctly. This lead me to try and fix the apparent buggy behaviour, rather than realise there was a security issue.


However, once I did realise there was a security issue, things fell into place and the methodology for creating an API seems sane, logical and more importantly bug free. However, I will freely admit that there was much wailing and gnashing of teeth prior to this from myself and the others I dragged in to help figure out what was going wrong. To give an idea of how hard won this knowledge was, we got most of our information from downloading plugins such as Venkman and Firebug and just trawling through the source code to see how they work. I even have a copy of the Firefox source code checked out... N.B. I was impatient to get the download, but I still feel Mercurial was pretty slow.


Progress Listeners

Once the type was set, we wanted to attach an object to the browser window which would allow us to call functions in the Chrome javascript. This turned out to be a bit more complex than I had hoped, as there are timing issues; what chrome event corresponds to when the window of the browser will exist and can have objects attached. For this, I pretty much used the code from the Progress Listeners MDN page. OnStateChange was the only event needed and when aFlag and STATE_START were both true we knew the browser window existed for the first time. As stated in that documentation, aWebProgress.DOMWindow gave me access to the browser window object and we were but one hurdle away from glory :)


Wrapped JS Object

I had missed another security hurdle and somehow skipped this section in the documentation. To make my object available to the browser, I needed to use wrappedJSObject, fortunately, an astute colleague remembered reading about this somewhere during the early days of development.

The API was now available to the browser! Using aWebProgress.DOMWindow.wrappedJSObject.myAPI = { ... } within the chrome and simply accessing myAPI within the browser, the work was complete and not a moment too soon!


Looking back

It all seems pretty straightforward looking back and the documentation all seems in place. However, what I think is missing is the continuity between the two. It's pretty difficult to find a page that talks about all of the pieces of the puzzle mentioned here in one place. Still, it was good practice solving problems by reading the source code of other plugins.

Saturday, 5 February 2011

Kindle and reading

As I had a 3 month contract in Cambridge, I had little time to post, but lots of time to read. I got a kindle for Christmas, which I will admit to absolutely adoring. I've read quite a lot of the free kindle books and revisited many old favourites. I spent a lovely amount of time reading and re-reading The Raven, by Edgar Allen Poe, I also read Machiavelli's The Prince, which was an interesting read. Travelling always makes for lots of reading and over the past 3 months, I have been averaging a book a week and have been really lucky in reading quite a few belters, so I though a post might be in order.


Rodger Penrose - Shadow's of the mind

A very hard read, I found this book exceptionally challenging, but a revelation once I grasped the concepts. The book discusses how we think and the actual process of conciousness and the concept of understanding. It challenges the assumption that the human brain processes information solely in a computational manner - which has an enormous impact on the future of A.I.. I admit to already being sympathetic to the view that true A.I. is a much more complex task than people seem to think and that in fact we are a very long way away from machines that can understand the problems they solve, rather than simply perform pre defined instructions at increasing rapid rates.


This is one of those books that I would love to recommend unreservedly, but there is an awful lot (to my mind...) of maths and logic, that make it a challenging book, whose reward is only worth it if you have a definite interest in the field. If you do, this is the guy to be reading.


Philip K. Dick

I have been a big fan of Philip K. Dick for a long time. His books are often challenging, but never without a definite point to make on either the human condition or the nature of reality. I have never read a book of his that I wouldn't recommend, so I am slowly working my way through his entire works. During the last 3 months I have read Ubik, Do androids dream of electric sheep, The man in the high castle, Flow my tears, said the police man. Do androids dream of electric sheep (the book from which Blade Runner was made) stands out among the books... It differs from the film greatly, the book is a discussion about empathy, in which the androids are simply held up as humans without empathy. I found it fascinating and inspiring of many discussions with friends.


Turgenev - Short Stories

I have always had a very soft spot for Russian literature and music. Crime and Punishment being my favourite book as a teenager. War and Peace also features high on my list of favourite reads. The settings of the stories (particularly His first love) remind me of Dostoevsky's The Fool and the romantic nature and depictions of passion are just what you would expect. Well written and very touching, I was especially moved by Mumu as it involves a dog! A highly recommended read.


H. Ryder Haggard - King Solomon's Mines

These stories come from a time when the British "stiff upper lip" was a thing to be feared. They are proper "Boy's own" type stories of manly men, with adventuring to do and no time for lady folk. Well written and utterly engaging, they reveal both the good and bad sides of a time gone past. It's hard to get behind a hero who is an ivory hunter, but it's written with such an innocent view and such good intentions, that it gradually wears down your reserves.


Robert A. Heinlein - The Man From Mars

Heinlein was a fine author and a great mind. This book is a truly thought provoking look at how alien, aliens would actually be. He overcomes this issue in the story by having a human raised by aliens and then returned to earth. He depicts with a thought provoking ease, how an this alien human might pick up our language with great ease and yet still utter lack the contexts which would give words meaning.


It's quite a long book and for me, the payoff was almost all in the first half, when the alien struggles to understand (or grokk) humanity. In the second half of the book, the alien tries to shine a light on some of the issues of society from this new and innocent perspective. I didn't dislike the second half of the book, it's just that reading a book like this, some 30 years after publication, can make ideas which were shocking and new then, seem tired and overused now. Well worth the read though, especially for the first half.


John Christopher - The Death of Grass

Now here is a book I can safely recommend to all and state that people "should" read this book. It's an "end of society" book, which, even after 70 odd years is still the most elegant expression of how quickly and easily our society could fall. With it's utterly realistic plot line and character, it depicts the change in morality of a group of people travelling across the UK during the collapse of society. I can't recommend this book highly enough - I've already purchased additional copies for friends.


Thomas Hardy - Tess of the d'Urbervilles

Another of the free kindle books and one I'd been meaning to read for a while now. This was a strange read, I immediately admired the quality of the prose and how well written the characters were. I was impressed by the ending and yet, I couldn't wait to finish the book. I think with so many other books to read I was a little impatient with a story that didn't have something to teach me. Perhaps, had I read this book on holiday with nothing else in the wings to read I may have been able to enjoy it more. I genuinely believe this was more my fault than the books.


Hunter S. Thomson - The Rum Diaries

As always with Hunter Thomson, you know that whatever the topic, it will be related with an absolute fairness to all characters. The work will be subject to his astounding attention to detail and an uncanny ability to get directly to the heart of the matter. I absolutely love his style of writing and his descriptions of scenes, such details in the minutia that you could be sat in the bar with him and yet not a single word is wasted. This is a little like the Fear and loathing in las vegas for Rum addicts.