Tuesday 11 December 2012

JavaScript Base64

This is brilliant! I've used this once already and dare say I will again soon, so good to encode text within data-attributes!

Thank you webtoolkit!

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

Monday 10 December 2012

empty()

This is just brilliant and deserves to be kept forever:

function empty(data) {
    if (typeof (data) == 'number' || typeof (data) == 'boolean') {
        return false;
    }
    if (typeof (data) == 'undefined' || data === null) {
        return true;
    }
    if (typeof (data.length) != 'undefined') {
        return data.length == 0;
    }
    var count = 0;
    for (var i in data) {
        if (data.hasOwnProperty(i)) {
            count++;
        }
    }
    return count == 0;
}

It's from the fabulous JSPro.

Yon peeps who are Java and C# heads at work used to sneer at my various attempts to check to see if a value was null or an empty string, well not any more thanks to this little gem!

Sunday 2 December 2012

Five Kisses

It's about three months since we lost #3 son. Three months of utter shite!

People have, by and large, been bloody brilliant!

But it's getting on for Xmas and I've been hitting Amazon. Lovely as they'll even wrap the presents.

Normally I'd write something along the lines of:

Dear [whoever],
Have a lovely Christmas and all the best for [next year]
Lots and lots of Love,
Dominic, Katrina (reverse, depending who it's for), #1, #2 and #3 XXXXX

This year I'm having to alter the last line to:

Dominic, Katrina (reverse, depending who it's for), #1 and #2

But I'll be buggered if I'm just putting 4 kisses!

Friday 9 November 2012

You say "expenses" and I hear "benefit".

So how would we feel if some slapper from a sink-hole council estate conned the tax-payer out of more than £60K and went to court with a pair of underpants on her head and sticking two pencils up her nose and the judge said that she wasn't well?

I know how the Tory media would portray it (Yes, I'm looking at you Daily Mail (I'm not allowed to read it any more in the pub as I get all ranty... even more ranty than I was this evening whilst listening to the news on Radio 4 and the idiocy of Cameron (Pie would've been proud!))).

So someone who claims to work for our good is guilty of stealing £60K from us and we say, "There, there love. You sit down and have a nice cup of tea. Don't you worry your pretty little head, just go home and we'll tell you all about it when it's all over"?

What's wrong with the system of government in this, and probably other, countries? We've just had the most expensive election campaign ever in the USA and China has just told it's population who it's leader is going to be. Do we really need government? Belgium managed 535 days without a leader, in that time did anything dodgy happen? It's arguable that the only reason that they had to form a proper government was the Eurozone crisis; a crisis caused by other governments!

Thursday 8 November 2012

What? No straight witch-hunt?

Is anyone else confused by Cameron's warning of a gay witch-hunt?

There hasn't been a straight witch-hunt after the Jimmy Savile furore.

And just why was Leah McGrath Goodman banned by Theresa May from entering the UK a year ago (hint, follow the link)?

Just don't make sense to me. I know Cameron isn't the brightest bulb in government but all the same - it does sound ever so slightly silly. A little like the joke:

Q: What's the difference between an apple and an orange?

A: A tub of margarine.

Or:

Q: Would you be interested in knowing which of your predecessors were nasty kiddy-fiddlers?

A: A tub of margeri... I don't want to start a gay witch-hunt!

Tuesday 16 October 2012

Colour vs Color

I'm not a designer by trade but by hobby so I'm always fascinated by colours. I live and breath HTML code so I end up using shed loads of hex values in page design work both at work and at home.

As such I don't really take much notice of the names of colours used in HTML code but prefer to use the hex value, I've spent an awful lot of time creating little JavaScript snippets and functions to manipulate those hex values - which has helped my understanding of hexadecimal no end (My first test when I applied to do my conversion Masters in Computer Science was to take away a set of sums in hex and return with the answers - with the help of a tame Java developer I managed it as well). I remember once creating a lovely little script which rotated a set of numbers throughout the hex spectrum and allowed me to create nearly every colour eventually. Magic (I'll have to find it soon as it made lovely little patterns).

Anyway there's been a number of related articles about colours of late which fascinated me. I think the first of which was this one by Jacob Sloan writing in disinfomation. He talks about how we as a species have evolved our distinction of colours - almost like moving from a black & white TV to a colour TV. I was especially interested in his quotation from Empirical Zeal:

Blue and green are similar in hue. Before the modern period, Japanese had just one word, Ao, for both blue and green. The wall that divides these colors hadn’t been erected as yet.

Fascinating ehh?

But along with that article is this one on colour names around the world from CrowdFlower which investigated whether or not people in different countries had different colour boundaries. There's a lovely visualization on there as well which allows the user to check the colour names depending upon where the respondent answered and which country s/he belonged to.

It was interesting though in that it might have had more to do with the standard of English of the respondent though. I can't imagine many people who speak English as a foreign language being able to comfortably use some of the more esoteric English names for a colour (I do love the word Teal - not a lovely colour but a lovely word).

But alongside the differences between cultures there seems to be a much more significant difference between the sexes. Data Pointed have another lovely visualization where the different sexes were asked to name colours. That again has a lovely hover facility where you can hover over a colour to see what it is names by respondents of different sexes.

Sunday 23 September 2012

Dashlane to the rescue...

So my poor old work laptop was feeling the strain and work decided that I needed a desktop which could cope with all the development work we're doing at the minute. I'm not a huge fan of big old clunkers but on this instance I thought I'd give it a whirl... WOW! Peter specced and built it and it's the bees knees, he only sniggered a little when I said that I'd like to try Windows 8 but he did check that I was joking, Gawd bless him!

Anyway, I've not long been through the whole Windows re-install procedure so I had a little idea of just what was entailed in transfering all my stuff. There's the huge music library managed by MediaMonkey and then the eBook collection manged by Calibre and synced across various machines with AVGs Live-Kive. But then there's all the little things that need passwords and such-like. Chrome is lovely and manages to remember everything but what with being a development team I test everything on other browsers. There's Chrome, Firefox, Opera, Internet Explorer and (if I'm feeling brave) Safari too!

I need to remember the log-ins I've got for all those little services too, thankfully most of them have a web front-end so it's just a matter of logging in and downloading the installer but then I need to remember the password I used as well for the client application. That's where Dashlane comes in so useful. The link will to Dashlane will credit me but will offer no financial gain but I'm putting it there anyway as I trust that you'll love it too!

It was pretty much the first thing I installed on the machine so that I didn't need to worry about remembering all those passwords and log-ins. I have at least two browsers open at any one time - one for development (Firefox with Firebug) and one for GMail and Google Reader (Chrome usually). Dashlane syncs my credentials between these two browsers beautifully so taht I only ever have to remember the Dashlane password. Utterly brilliant! It's nice that things just work, especially at the minute.

But hey, don't just take my word for it, give it a try! There're apps for Android and iPad too - you wouldn't believe how useful they are too. Just fire them up and I can get access to my credentials without having to boot a big machine!

Saturday 22 September 2012

Flirting with Catholicism



I've been polishing this anecdote for a while so I thought I'd best share it.

I've been going through the mill over the past two or three weeks and last Thursday (13th September, 2012) I couldn't sleep. I was well into my cups at this point and just not able to turn my brain off, not even Tesco's value whiskey was working - though I kept trying and purposefully ignoring the head-ache I knew I'd have in the morning.

I got to thinking about all the lovely people I knew who were getting some measure of comfort from their faith. One of my mates at school was one a Catholic, a good friend from work is one. One of people who's been phoning regularly in order to insult me and who's helped me ever so much is one. The lady up the road is one and, shock and horror, I discovered that I would've been one if my Grandma hadn't lost her faith. Most of my extended family are Catholics and they, as well as the people I've already mentioned are lovely, bright and sincere people. I felt that I simply must join their ranks! I'm re-reading this now and realising that the list of lovely people I know who are Catholics is staggering!

It all made perfect sense to me - I've always felt guilty of something or other: I've always felt as if I was to blame! Goodness knows I've an awful lot to feel guilty for, but even when I was too young to remember having done anything wrong I felt guilty. Perhaps a little confession would help ease that...? But without that feeling of original sin (whether it was real or imagined) what would I be left with? If I were washed clean of all my previous sins what'd be left? Would I be reborn as a psychopath? Without all the anxieties I have about doing right would I feel able to do what's wrong? All these questions and so many more were whirling around in my head lubricated by the ever so gritty whiskey - so I decided to do what every good geek does - I looked online.

I picked up the iPad and started up Chrome and entered "convert to Catholicism Cambridge UK". The number of results returned was just staggering but eventually I found a link which had a list and not just blah blah blah words. Ahh, a list, something I can work down and check I can fulfil the requirements.
  1. These was something about taking communion... I'd been to one when I did some voluntary work in a hotel for the disabled as a teenager in Southport and a lady needed an escort but the staff had been lovely about me not having to take the bread and wine. My old history teacher at school had talked for ages about Transubstantiation and the idea of mystic cannibalism had me thinking of all sorts of things like developing some sort of kuru. If I ignored the possibility of divine Mad Cow disease then I guess the option of a bit of plonk and a biscuit on a Sunday morning wouldn't be too bad - though with my propensity for strong drink the afternoon service might be better: at least the sun'd be o'er the yard arm! Tick!
  2. There was something about leading a good and moral life. Please refer to my rant about guilt! The load I carry is so huge that I really can't face adding to it so I try to lead as good a life as possible. I don't even kill bugs or anything like that. That crunch you hear when you accidentally stand on a snail in the dark means that I have to turn around and apologise. If I were anymore twitched I'd end up being a Jain! Tick!
  3. Confession? Hell yes! That's what I want. Feeling unguilty (should that be innocent?) for at least a little while (until I stood on a snail on the way out of the church or something) would be lovely. Perhaps my back would miraculously unkink and I might be able to stand up straight (Having said that I think I stoop because I was a tall kid and I didn't want others to feel intimidated by my height - of course I'm no longer tall what with diets improving over the last few years and me hitting 40 a month or so back (aren't you suppossed to loose an inch in height for each decade over the age of 40 you hit)). Perhaps I'd be able to do something immoral without fear of being crushed by guilt? Tick!
  4. There were ever so many other things, things that looked just strange and ridiculous but things that I felt I could do. Tick, Tick and Tick!
  5. Then there was the one about believing in Jesus as my lord and saviour (I'm pretty sure I should've capitalised that lord before?). Arse! Busted! That'll be a big fat angry red Cross!
At that point my crushing disappointment was met by the accumulated alcohol and I was able to retire with some hope of oblivion so I went and cuddled up with 'er indoors, sniggering at her groan and shiver when I placed my cold legs against the back of hers. Ohh goodness, more guilt ;-)

Perhaps though, I already am, my ex-wifes Grandmother was suspicious of me for ages because of my name. It took ever such a long time for her to be convinced that I was called Dominic because my Ma had high-church leanings rather than because I was a Tim. Things like that seemed to make a difference in Birkenhead in the 90s... If that's the case and I have some measure of genetic Catholicism then I've lost out on the redeeming bit. All I want is a little absolution.

Tuesday 11 September 2012

17:00hrs Tuesday

In work at 6:00hrs, as is my want anyway, but really couldn't leave until after 4. It's a Tuesday see. Pie might have come after school with it being a Tuesday... he more often than not hadn't over the last few months, but he might've.

Sunday 22 July 2012

JavaScript Unit Testing.

(Thanks Mrs Pop for the image, would've asked first but then you wouldn't have seen it in context. If you want I'll take it down?)
My Coding is, if I do say so myself, bloody brilliant. I test and test and test but that testing isn't done in a formal manner and I'm coming to realise that this has got to change. I've been doing the odd bit of unit testing in SalesForce and Andy at work mentioned JsUnit last week when he suggested I write the coding standards for JavaScript, so I guessed I should learn a little about what it means.
I did a little unit testing whilst doing my Java course at the OU so I knew a little bit about the whole Test Driven Development thing. I also use the jQuery JavaScript extensively and I guess that that has already been tested extensively - at least I hope it has. So the only things left to test are the functions I write myself and JsUnit is perfect for that.
For a friend who lives and works in France I'm developing an invoicing system which has to read and write out French currency formats. For those that don't know: the French use a space for a thousand separator and a comma rather than a full stop for the decimal separator, they also have the Euro symbol at the end rather than at the beginning of the amount. So a million Euros and twenty-five Cents would be written out as “1 000 000,25 €". Complicated ehh?
So I've two functions: one which take a float and outputs it as a French formatted currency string and another that takes a French currency string and returns a float.
I won't bore you with the functions, needless to say they involve shed loads of conversions between numbers and string s and then splits etc...
I will bore you with how I tested them using JsUnit though.
I downloaded JsUnit from github and placed the extracted folder on my server. I then created the following file:
<!DOCTYPE HTML>
<html>
  <head>
    <title>Unit Tests for my Functions</title>
    <script src="./resources/jsunit/app/jsUnitCore.js"></script>
    <script src="./resources/js/toEuro.js"></script>
  </head>
  <body>
    <script>
      function testToFloat() {
        assertEquals("0,50 € should result in 0.5", 0.5, toFloat("0,50 €"));
        assertEquals("1 000 000,25 € should result in 1000000.25", 1000000.25, toFloat("1 000 000,25 €"));
      }
      function testToEuro() {
        assertEquals("0.5 should result in '0,50 €'", "0,50 €", toEuro(0.5));
        assertEquals("1000000.25 should result in '1 000 000,25 €'", "1 000 000,25 €", toEuro(1000000.25));
      }
    </script>
  </body>
</html>
I then opened up the included testRunner.html using my browser and pointed it at the file I created above and, after a little playing with the functions, managed to get the tests to pass.
It's an interesting approach to coding TBH but one that I think I could get used to it!
The people behind JsUnit now no longer use it but prefer Jasmine. I've had a wee squint but really don't have time to investigate it further this weekend. I code all week at work and most of the weekend at home and really need to do something else this afternoon. I'm 40% through Gary Gibson's The Thousand Emperors and can't justify buying Neal Asher's Zero Point until I'm done... and browsing for SodaStreams is doing my poor nut in.

Sunday 15 July 2012

Are The Archer's Anti-Traveler?

Caravan Boat image

There's reckoned to be a natural progression on BBC radio, You're supposed to start your listening experience with Radio 1 and then, as you mature, make your way up to Radio 4. I started with Radio 4 and had my choice confirmed for me when a nursing tutor suggested that if I wanted to be informed about what was happening in the world I should at least listen to Today every day.

I don't do this as much as I used to though as I'm no longer a nurse and I prefer to get my news either online via Reader or by listening to the No Agenda Podcast. That's not to say that I've totally given up on Radio 4. I turn it on when I'm cooking or eating and always first thing in the morning for a little fix of News. I even listen to The Archers, not religiously like. Just often enough to keep up with what's happening in Ambridge. I'll get lost every now and then though but I can always rely on my Ma to tell me what's been happening.

As an intermittent listener then I've been keeping abreast of the recent problems on Brookfield Farm (Have a wee squint 'ere: #farmageddon). I'm not totally up there with what's happening but I'm getting the gist and it's a wee bit concerning. David Archer is due to give evidence against a group of people who assaulted Adam Macy and left him in a coma after he tried to stop them stealing something from a farm...

That's all well and good and a reasonable attempt to liven up a show that's described as like real life - but more boring. But I'm not sure it's only me that sees this group of white van driving thugs as being an allegory for the problems faced by rural communities from Irish Travelers (Tony Martin anyone?). I've not heard an Irish twang in the threatening phone calls yet but I'm waiting.

What's more, I'm still not overly sure how I feel about it, that's if it isn't all in my head TBH. I've watched a couple of episodes of My Big Fat Gipsy Wedding, and I'm not sure how I feel about that either (I do watch an awful lot of TV for someone without a TV). I'm just not sure and I vacillate between how I feel about Irish Travelers but I'm conscious that they are in a vulnerable position in terms of the bigotry that's always just bubbling under the surface in the UK.

As an aside: I loved The Riches and would advise everyone to watch it.

As a second generation lapsed Catholic and a Bargee I'm even more conflicted. I'd have thought that the similarity of life-styles between Travelers and Bargees would've meant that we shared something but I think that I might be mistaken. I guess the enemy of your enemy isn't necessarily your friend - not that I see people in houses as the enemy. I've been called a "Water Gypsy" before and, while I was away with the fairies pondering the bucolic lifestyle of a boater with a nice camp-fire going in the twilight in a meadow beside a gentle canal, the chap hastily retracted it thinking I was away with the demons pondering GBH after being so insulted. Before I moved aboard there were some problems with Travelers and the boating community at Midsummer Fair. Even now there is a mass exodus of boats from Midsummer Common when the fair is due. I still remember seeing boats with wooden covers over their windows to protect the glass from projectiles.

This conflict is only exacerbated by a close run in I had with being a New Age Traveler in my youth. If my Ma hadn't put her foot down with such a firm hand I would have been on my way down to Glastonbury in the back of a smelly truck and sleeping in a Bender. The call of the road was loud but the fear of my Ma was ever so much greater ;-).

Interesting ehh? But like some sort of grotesque icing on the cake there is the issue of slavery. The case is interesting in that the people enslaved were "recruited" from the streets... some in the media were outraged but not so much that they could think of ways of providing homes for the homeless. So yeah, I'm conflicted, I'm also aware that one really shouldn't tar every member of a minority with the same brush - á la the "Water Gypsy" comment above. Indeed, so reticent am I to acknowledge membership of any other minority other than Yorkshireman I'm wary of even saying that I'm a Bargee. I know what happens to minorities historically and I don't want to be herded into a cattle-truck any time soon.

So what's to do? We go France at least annually (How very middle-class of us ehh?) and they've taken a rather drastic approach to the issue of Travelers, they've ejected them! I'm not sure that that approach is possible and I'm certainly sure that it's not one I'd suggest. There does seem to be animosity bubbling under the surface though and I'm pondering how long it'll be before Cameron et al decides that their campaign to make the poor the villains in the current economic crisis is a wash-out and decide to alter their focus to a target even more hated by the middle-class of middle England. A minority that is insular and doesn't pay taxes and has little or no respect for the laws-of-the-land perhaps shouldn't be tolerated in that land? That was ironic by the way; I'm more than sensitive to allegations of racism. I guess that's the joy of being a Yorkshireman, we hate everyone equally and don't discriminate, the only exception being that the only people we hate more than everyone else is each other or ourselves!

Is #farmageddon the opening salvo in a pseudo class war? And it could be that the animosity has always been there, I admit. Being a Yorkshireman I only ever heard the word "Pikey" when I was visiting relatives down South in my youth. I had absolutely no idea what the word meant and it was only when I moved down here that I clocked the sheer level of animosity. I guess there must have been reason for the animosity but I'll be blown if I know what the cause was, it seems to be just that way. I hear all sorts of stories but apart from the odd run-in with Traveler youth - no more than run-ins with non-traveler youths TBH - I'm unsure as to the rationale for the animosity - unless it's just the English animosity to the strange?

Goodness me this is a long post! I beg forgiveness but this is an issue that's been percolating for a while and I've got all sorts of conflicted feelings about it. I'm glad to have this forum in which the air them though so I'd welcome your thoughts/comments.

Thursday 5 July 2012

JSRender Rocks!

var newCustomer = $("<div></div>", {"class": "customer row-fluid", "data-id": data.msg}).appendTo($("#customers"));
var newName = $("<div></div>", {"class": "row-fluid thingTop"}).appendTo(newCustomer);
newName.append($("<div></div>", {"class": "span6"}).html("<strong>Name:</strong>"));
newName.append($("<div></div>", {"class": "span6 name", "text": data.name}));
var newCompany = $("<div></div>", {"class": "row-fluid thing"}).appendTo(newCustomer);
newCompany.append($("<div></div>", {"class": "span6"}).html("<strong>Company:</strong>"));
newCompany.append($("<div></div>", {"class": "span6 company", "text": data.company}));
var newStreet = $("<div></div>", {"class": "row-fluid thing"}).appendTo(newCustomer);
newStreet.append($("<div></div>", {"class": "span6"}).html("<strong>Street:</strong>"));
newStreet.append($("<div></div>", {"class": "span6 street", "text": data.street}));
var newTown = $("<div></div>", {"class": "row-fluid thing"}).appendTo(newCustomer);
newTown.append($("<div></div>", {"class": "span6"}).html("<strong>Town:</strong>"));
newTown.append($("<div></div>", {"class": "span6 town", "text": data.town}));
var newPhone = $("<div></div>", {"class": "row-fluid thingBottom"}).appendTo(newCustomer);
newPhone.append($("<div></div>", {"class": "span6"}).html("<strong>Phone:</strong>"));
newPhone.append($("<div></div>", {"class": "span6 phone", "text": data.phone}));

So the above is what I used to do on a mates web application when she entered a new user to her system. I just knew there must be a better way though so I got to looking and looking and looking and saw something about jQuery Templates but then saw that they'd fallen out of favour. I think that that is a shame but they've been replaced with JsRender - which just rocks!

All of the code above ended up being replaced with this:

$("#customers").append(
    $("#addCustomer").render(data)
);

Of course I had to add this to the base page:

<script id="addCustomer" type="text/x-render">
    <div class="row-fluid customer" data-id="{{>id}}">
        <div class="row-fluid thingTop">
            <div class="span6"><strong>Name:</strong></div>
            <div class="span6 name">{{>name}}</div>
        </div>
        <div class="row-fluid thing">
            <div class="span6"><strong>Company:</strong></div>
            <div class="span6 company">{{>company}}</div>
        </div>
        <div class="row-fluid thing">
            <div class="span6"><strong>Street:</strong></div>
            <div class="span6 street">{{>street}}</div>
        </div>
        <div class="row-fluid thing">
            <div class="span6"><strong>Town:</strong></div>
            <div class="span6 town">{{>town}}</div>
        </div>
        <div class="row-fluid thingBottom">
            <div class="span6"><strong>Phone:</strong></div>
            <div class="span6 phone">{{>phone}}</div>
        </div>
    </div>
</script>

But what the hey, at least I'm keeping my markup where it needs to be, on the page. Who cares if it's something of a fudge...? I dare say I will soon, but it'll do for now ;-)

Monday 2 July 2012

Android Emulator for Development with Arcus Global

At work we've been doing a fair bit of Android development of late at work and I was right naffed off with waiting for the Android Emulator to boot up each and every time I needed to test something (I do so wish I could sort out in my head what I need to do in one fell swoop but I generally plan like a loon and then implement a little bit at a time).

I installed BlueStacks and tried that and it was bloody brilliant, but I hadn't checked that it was great before-hand so I had to justify my choice (I'd tried it before you see at home) so I went through a process defined by a colleague and I documented the result on the work blog. I think it's well worth a read...

I hope you like the picture on the blog, it was taken on the way back from getting the boat blacked at the Lazy Otter on the 18th of June, 2012.

Monday 23 April 2012

We live here

I thought I'd share this from Helen Lynn. I guess we'd be just out of shot on the right of the image...

Friday 20 April 2012

ifttt

Testing a new action I created, this should auto-post to Tumblr

Thursday 19 April 2012

Finding the numbers that a number is divisible by...

I'm no Math geek (Hi Dr G!) but I needed to figure out all the numbers that a particular number was divisible by so that I could scale it without having to rely on The Gimps algorithms to smooth it so I wrote the following script:

(function(){
  var num = 15;
  for(var n = 1; n < (num / 2); n++){
    var res = num / n;
    if (res === Math.round(res)){
      document.write("<p>" + res + "</p>");
    }
  }
})();
Works a treat, just add your number as num variable and run in the browser

Monday 26 March 2012

Exam Prepration jQuery Tool

I do love 'er-indoors but she's not the most patient of people. Sure, she manages to actively listen for a while but ask her to do something that doesn't interest her and the result is obvious boredom. Which is a shame as I needed her help to revise for my DEV 401 exam.

I asked if I could borrow her for an hour or two on Saturday and Sunday. "Sure", says she in a nice surrendered wife type of way. My idea was to go through possible questions and give answers and ask her to say if I'd got it right or wrong. She agreed and we sat down but the delay of a few micro-seconds before I got a reply when I asked her a question was doing my nut in. I looked down to see her farming Smurfs or something. I really couldn't face putting her, or myself, through it all again the next day.

jQuery to the rescue!

I copied the questions I had into an array of JSON objects with the questions, the possible answers and the solution. This worked a treat as I could swap over questions easily enough and re-task it for other purposes.

I thought about trying to pluginify it but I don't really think it needs it as it takes a set of questions, answers and solutions and spits back a set of divs into the container of your choice. Props to David for the compare function.

(function(){
    prepareExam("chap1.json", "body");
    $("select#paper").on("change", function(){
        $val = $(this).val();
        $("div.question").empty().remove();
        $("div.score").empty().remove();
        prepareExam($val, "body");                    });
})();
jQuery.fn.compare = function(t) {
    if (this.length != t.length) {         return false;     }
    var a = this.sort(),
        b = t.sort();
    for (var i = 0; t[i]; i++) {
        if (a[i] !== b[i]) {             return false;
        }
    }
    return true;
};
function prepareExam(paper, target) {
    $.getJSON(paper, function(exam) {
        $.each(exam.exam, function(i, question){
            var d = $("<div></div>").addClass("question").appendTo(target);
            var q = $("<p></p>").html(i+1+". "+question.question).appendTo(d);
            var f = $("<fieldset></fieldset>").appendTo(d);
            $.each(question.answers, function(letter, possible){
                var labelID = letter+(i+1);
                $("<input></input>", {"type":"checkbox", "name":i+1,"value":letter, "id":labelID}).appendTo(f);
                $("<label></label>", {"for":labelID}).text(letter+". "+possible).appendTo(f);
                f.append('<br />');
            });
            d.data({"answer":question.solution});
            var c = $("<span></span>").addClass("check").text("Submit").button().appendTo(f).on("click", function(){
                var $parent = $(this).parent().parent();
                var allVals = [];
                $.each($parent.find("input:checked"), function(x, y){
                    allVals.push($(y).attr("value"));
                })
                if($(allVals).compare($parent.data("answer"))){
                    $parent.css("background-color","#ccffcc");
                    $parent.find("span.check").remove();
                    $parent.data({"success":true});
                }else{
                    $parent.css("background-color","#ffcccc");
                    $parent.find("span.check").remove();
                    $parent.data({"success":false});
                }
            });
            var leg = (question.solution.length !== 1) ? "answers" : "answer";
            $("<legend></legend>").text("Please choose "+question.solution.length+" "+leg+":").prependTo(f);
        });
        var s = $("<div></div>").addClass("score").appendTo(target);
        $("<p></p>").text("Ready to calculate your final score?").appendTo(s);
        $("<span></span>").addClass("final").text("Check").button().appendTo(s).on("click", function(){
            var total = 0, correct = 0;
            $.each($("div.question"), function(i, div){
                total++;
                if($(div).data("success")){
                    correct++;
                }
            });
            var l = $("<p></p>").text("Total Score = "+(((correct/total)*100).toFixed(2))+"%").appendTo($("div.score"));
            if(((correct/total)*100).toFixed(2) >= 68){
                l.css("color","green")
            }else{
                l.css("color","red")
            }
            $("span.final").remove();
        });
    });
};

As you can probably tell I used a lot of different sets of questions and I added them to a select input so I could load up a set of new questions when I'd done a paper and scored myself.

The format of the JSON should be:

{
    "exam": [
        {
            "question": "Jack and Jill went up the hill to fetch?",
            "answers": {
                "a": "A pail of water",
                "b": "Porridge",
                "c": "Vinegar"
            },
            "solution": [
                "a"
            ]
        },
        {
            "question": "What did the old woman who lived in a shoe do to her children?",
            "answers": {
                "a": "She gave them some broth without any bread.",
                "b": "She starved them.",
                "c": "She sent them to sweep chimneys.",
                "d": "She whipped them all soundly and put them to bed."
            },
            "solution": [
                "a",
                "d"
            ]
        }
    ]
}

Have fun!

I think it's lovely so by all means take it, use it and let me know if you improve it, let me see where you use it too ehh?

This is now on github.