Wednesday, April 24, 2013

Using Google Calendar's new Javascript Library

Here is a quick example of getting started with list events and inserting events in google calendar. This is using their new javascript library.

Make sure to to create a project under the Google APIs Console and long with this you will generate an api key and client id for use with this project.

Make sure to also read this page below to further understand authentication with the service.

Using OAuth 2.0 to Access Google APIs

  Copyright (c) 2011 Google Inc.

  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy of
  the License at

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  License for the specific language governing permissions and limitations under
  the License.

  To run this sample, replace YOUR API KEY with your application's API key.
  It can be found at under API Access.
  Activate the Google+ service at under Services
<!DOCTYPE html>
<meta charset='utf-8' />
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<button id="insert-button" style="visibility: hidden">Insert</button>
<script type="text/javascript">
      // Enter a client ID for a web application from the Google Developer Console.
      // The provided clientId will only work if the sample is run directly from
      // In your Developer Console project, add a JavaScript origin that corresponds to the domain
      // where you will be running the script.
      var clientId = 'PUT CLIENT ID HERE';

      // Enter the API key from the Google Developer Console - to handle any unauthenticated
      // requests in the code.
      // The provided key works for this sample only when run from
      // To use in your own application, replace this API key with your own.
      var apiKey = 'PUT API KEY HERE';

      // To enter one or more authentication scopes, refer to the documentation for the API.
      var scopes = '';
      // Use a button to handle authentication the first time.
      function handleClientLoad() {

      function checkAuth() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);

      function handleAuthResult(authResult) {
        var authorizeButton = document.getElementById('authorize-button');
        var insertButton = document.getElementById('insert-button');
        if (authResult && !authResult.error) {
 = 'hidden';
 = '';
          insertButton.onclick = handleInsertClick;
        } else {
 = '';
 = 'hidden';
          authorizeButton.onclick = handleAuthClick;

      function handleAuthClick(event) {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        return false;
      function handleInsertClick(event) {

      function makeApiCall() {
     gapi.client.load('calendar', 'v3', function() {
       var request ={
         'calendarId': 'primary'
       request.execute(function(resp) {
         for (var i = 0; i < resp.items.length; i++) {
           var li = document.createElement('li');

      function makeInsertApiCall() {
     gapi.client.load('calendar', 'v3', function() {
       var request ={
         "calendarId": "primary",
             "summary": "Appointment",
             "location": "Somewhere",
             "start": {
               "dateTime": "2011-12-16T10:00:00.000-07:00"
             "end": {
               "dateTime": "2011-12-16T10:25:00.000-07:00"
       request.execute(function(resp) {
         for (var i = 0; i < resp.items.length; i++) {
<div id='content'>
<ul id='events'></ul>

<p>Connecting to Google Calendar with the Javascript Library.</p>

Thursday, April 11, 2013

IaaS vs. PaaS vs. SaaS

Saas, A simple example of SaaS is an online email service, like Gmail. SaaS is really geared toward the end users in your organization and doesn't take much to get started.

IaaS is at the other end of the cloud spectrum. In this scenario, you want to maintain control of your software environment, but you don't want to maintain any equipment. You don't want to have to buy servers and put them in a climate-controlled room or any of that. Instead, you go to an IaaS provider and request a virtual machine.

PaaS is somewhere in between IaaS and SaaS. It's not a finished product, like SaaS, and it's not a tabula rasa, like IaaS. PaaS gives your application developers hooks and tools to develop to that particular platform. For example, Microsoft's Windows Azure gives you tools to develop mobile apps, social apps, websites, games and more. You build these things, but you use the APIs and tools to hook them into the Azure environment and run them there.

Wednesday, April 10, 2013


Behavior Driven Development vs. Test Driven Development

Excellent explanation of why we do not write our tests tied to the implementation of the solution. If you are developing in the Java world, and want to try out BDD, checkout JBehave. BDD vs TDD (explained)

Another great video on the topic. Behavior Driven Development

Writing software in an organisation or for ourselves, many people feel that they "should" somehow be doing Test Driven Development (TDD) because "everybody else" is and it's cool, somewhere between necessary and useful and they heard testing was good. When informed that must of TDD isn't about testing (despite the name!), confusion reigns.

Behaviour Driven Development is a different way of approaching the "how to validate your code" problem.
TDD You are actually specifying what should be happening and not testing what is happening.Instead of thinking about what is the next function I need to implement think about what is the next feature I need to implement.

Tuesday, April 2, 2013

Computing the weighted mean

Recently I was asked to compute the weighted average over aggregating some shipments and coming up with a average price paid per lb for each product. Hope someone finds it useful, and remember you need underscore.

function avgBetterReduce(purchases) {
  var weightedAvgs = [];

  _.each(_.reduce(purchases, function(memo, p) {
      // If we haven't seen the product yet intialize the object memo[product]
      memo.hasOwnProperty(p.product) ? 0 : memo[p.product] = { avg: 0, totalLbs: 0};
      memo[p.product] = { avg: memo[p.product].avg + p.costPerLb * p.lbs, totalLbs: memo[p.product].totalLbs + p.lbs };
      return memo;
    }, {}), /* Function to handle the resulting map from reduce */ function(value, key) {
        weightedAvgs.push({ product: key, avgCost: value.avg / value.totalLbs });

  return weightedAvgs;

Input something like the following:

var purchases = [

Output will look similar:

[ { product: 'Apricots', avgCost: 1.4236599007668016 },
  { product: 'Figs', avgCost: 1.9670220089046067 },
  { product: 'Celery', avgCost: 0.9623391958858117 },
  { product: 'Tomatos', avgCost: 0.30542861699968105 },
  { product: 'Guava', avgCost: 0.9120219665767172 },
  { product: 'Lettuce', avgCost: 0.8001419032810235 },
  { product: 'Apples', avgCost: 0.3580237647589682 },
  { product: 'Pears', avgCost: 0.8805333538010198 } ]

Third Party Javascript 2

Chapter 3. Rendering HTML and CSS
        Decoupling render targets

        I like the following approach the best for identifying the render point and 

        allowing multiple widgets to be displayed.

    jQuery('[data-stork-product]').each(function() {
         var location = jQuery(this);
         var id = location.attr('data-stork-product');
         getWidgetData(id, function(data) {
              renderWidget(data, location);
         }); }); 

         Loading CSS Files

         function loadStylesheet(url) {

              var link = document.createElement('link');
              link.rel = 'stylesheet';
              link.type = 'text/css';
              link.href = url;
              var entry = document.getElementsByTagName('script')[0];
              entry.parentNode.insertBefore(link, entry);

         function isCssReady(callback) {

               var testElem = document.createElement('span');
      = 'stork-css-ready';
      = 'color: #fff';
               var entry = document.getElementsByTagName('script')[0];
               entry.parentNode.insertBefore(testElem, entry);
               (function poll() {
                     var node = document.getElementById('css-ready');
                     var value;
                     if (window.getComputedStyle) {
                        value = document.defaultView
                          .getComputedStyle(testElem,  null).getPropertyValue('color');
                     else if (node.currentStyle) {
                            value = node.currentStyle.color;
                     if (value && value === 'rgb(186, 218, 85)' 
                              || value.toLowerCase() === '#bada55')
                    } else {
                          setTimeout(poll, 500);

            Defensive HTML and CSS

         Do you want your application to look the same everywhere? Or do you want the 
         application to inherit the native look and feel of the page on which it’s hosted? 
         Your answer will have a profound effect on your strategy for rendering.

Third Party Javascript

 Chapter 2. Distributing and loading your application
          Loading additional files

          The book recommends the following snippet of code load additional files from within your main third party script.

          function loadScript(url, callback) {
var script = document.createElement('script');

script.src = url
                script.async = true;

                var entry = document.getElementsByTagName('script')[0];

                entry.parentNode.insertBefore(script, entry);

                script.onload = script.onreadystatechange = function() {
               var rdyState = script.readyState;

                if(!rdyState || /complete|loaded/.test(script.readyState)) {

               // Detach our handlers to avoid memory leaks
               script.onload = null;
               script.onreadystatechange = null;

          I created the following function to let me know once all the scripts have finished loading. Maybe you will find it useful as well.

          function loadSupportingFiles(callback) {
var i = 0;
var numberOfFiles = 0;

loadScript('', scriptsDone());
loadScript('', scriptsDone());
loadScript('', scriptsDone());

function scriptsDone() {

return function () {

if(i === numberOfFiles) {

          Passing script arguments

Taken from Third-Party JavaScript

River Trail – Parallel Programming in JavaScript

Now go play with the interactive Repl below!

Monday, April 1, 2013

Why we write tests

Why we write tests and when to write tests.

Unit tests I think are essential especially when you have a complex piece of code such as computing a weighted average or turning a math formula into code.

I would be careful though when creating tests to make sure that, as you are writing the test you are always thinking how likely is this test to actually catch bugs. Too often I see tests that are testing such basic functionality that is unlikely to ever break. Make your tests useful!

One person writes the test and one person writes the code. This helps to encourage the person writing the tests to focus on what the code should do and not how it goes about doing it.

Another proposed benefit is that writing tests helps to split up your code into smaller methods. In my opinion splitting your code into smaller methods is always a good practice and depending on the person -- they may need tests to help them do this while others just do this as they code.

Finally Integration Tests tend to be too brittle and should be used carefully as not to waist too much time on them, especially maintaining them. Integration tests tend be mocked up heavily so much so that they are no longer testing real world usage. If you are going to write a integration test, once again think about what you are actually testing with it as a whole and whether or not you think the part you are testing will ever break. One should also consider whether not the test they are writing is already covered somewhere else. For instance I have seen integration tests written that in effect test a libraries functionality but this test was written outside the library thereby duplicating a test that was already including in the library.