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

  http://www.apache.org/licenses/LICENSE-2.0

  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 https://code.google.com/apis/console/?api=plus under API Access.
  Activate the Google+ service at https://code.google.com/apis/console/ under Services
-->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--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
      // https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
      // 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
      // https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
      // 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 = 'https://www.googleapis.com/auth/calendar';
   
      // Use a button to handle authentication the first time.
      function handleClientLoad() {
        gapi.client.setApiKey(apiKey);
        window.setTimeout(checkAuth,1);
      }

      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) {
          authorizeButton.style.visibility = 'hidden';
          makeApiCall();
          insertButton.style.visibility = '';
          insertButton.onclick = handleInsertClick;
        } else {
          authorizeButton.style.visibility = '';
       
          insertButton.style.visibility = 'hidden';
       
          authorizeButton.onclick = handleAuthClick;
        }
      }

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

      function makeApiCall() {
     gapi.client.load('calendar', 'v3', function() {
       var request = gapi.client.calendar.events.list({
         'calendarId': 'primary'
       });
           
       request.execute(function(resp) {
         for (var i = 0; i < resp.items.length; i++) {
           var li = document.createElement('li');
           li.appendChild(document.createTextNode(resp.items[i].summary));
           document.getElementById('events').appendChild(li);
         }
       });
     });
    }

      function makeInsertApiCall() {
     gapi.client.load('calendar', 'v3', function() {
       var request = gapi.client.calendar.events.insert({
         "calendarId": "primary",
         resource:{
             "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++) {
           console.dir(resp);
         }
       });
     });
    }
   
    </script>
<script
src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<div id='content'>
<h1>Events</h1>
<ul id='events'></ul>
</div>

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

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

BDD vs. TDD

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 = [
  {"product":"Apricots","lbs":877,"costPerLb":"1.32"},
  {"product":"Figs","lbs":1557,"costPerLb":"2.11"},
  {"product":"Celery","lbs":1314,"costPerLb":"1.00"},
  {"product":"Tomatos","lbs":645,"costPerLb":"0.26"},
  {"product":"Guava","lbs":1928,"costPerLb":"0.84"},
  {"product":"Celery","lbs":1503,"costPerLb":"0.87"},
  {"product":"Lettuce","lbs":1546,"costPerLb":"0.82"},
  {"product":"Celery","lbs":1119,"costPerLb":"0.78"},
  {"product":"Apples","lbs":583,"costPerLb":"0.36"},
  {"product":"Apples","lbs":1272,"costPerLb":"0.42"},
  {"product":"Pears","lbs":127,"costPerLb":"0.84"},
  {"product":"Tomatos","lbs":1992,"costPerLb":"0.29"},
  {"product":"Apricots","lbs":1426,"costPerLb":"1.28"},
  {"product":"Apricots","lbs":1045,"costPerLb":"1.71"},
  {"product":"Celery","lbs":1633,"costPerLb":"1.14"}
];

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);
         location.removeAttr('data-stork-product');
         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');
               testElem.id = 'stork-css-ready';
               testElem.style = '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')
                    {
                          callback();
                    } 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)) {
                callback();

               // 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('http://camerastork.com/javascripts/util.js', scriptsDone());
loadScript('http://camerastork.com/javascripts/dom.js', scriptsDone());
loadScript('http://code.jquery.com/jquery-1.9.1.min.js', scriptsDone());

function scriptsDone() {
numberOfFiles++;

return function () {
i++;

if(i === numberOfFiles) {
callback();
}
};
}
}

          Passing script arguments



       
https://github.com/rhanak/thirdpartyjs

Taken from Third-Party JavaScript http://www.manning.com/vinegar/

River Trail – Parallel Programming in JavaScript





http://www.infoq.com/presentations/Parallel-JavaScript

Now go play with the interactive Repl below!

http://rivertrail.github.com/interactive/

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.