Very Simple Line Graph With D3

I’ve been learning more about D3 and decided to apply what I learned about composition to make a very simple line graph. I’ll just post the pen and comment on it below:

See the Pen Very Simple Line Graph with D3 by Mike Newell (@newshorts) on CodePen.

Basically, the important parts are that I’m using a factory to create “LineGraph()”. It takes some data, a class name of the actual svg element to target and some default options. Once you call, “lineGraph.draw()” the real work begins.
First we get the dimensions of the svg element on the page:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var svgElem = state.svg[0][0];
  var width = svgElem.offsetWidth;
  var height = svgElem.offsetHeight;

[/pastacode]
Then we get the min,max of each set of data. In this case we get min/max for x and y datasets.

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var extentX = d3.extent(state.data, function(d) { return d.x });
  var extentY = d3.extent(state.data, function(d) { return d.y });

[/pastacode]
We also need to tell the graph how to scale the data to actual dimensions of the graph itself. This is done by plugging the width and height of the graph into a function d3 can use to scale our data points. We also add some padding so the data doesn’t touch the edge of the graph and get cut off. Moar on scaling here: http://www.d3noob.org/2012/12/setting-scales-domains-and-ranges-in.html

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var scaleX = d3.time.scale().range([state.padding, width - state.padding]);
  var scaleY = d3.scale.linear().range([height - state.padding, state.padding]);
  scaleX.domain(extentX);
  scaleY.domain([0,extentY[1]]);

[/pastacode]
Once we have our data ranges and scales, we can create our line:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var line = d3.svg.line()
    .x(function(d) { return scaleX(d.x); })
    .y(function(d) { return scaleY(d.y); })
    .interpolate(state.interpolation);

[/pastacode]
In many cases, d3 will return a function you’ve prepared before hand to run on some data. In this case we prepare a line. You can see we pass functions into the x and y values.

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function(d) { return scaleX(d.x); }

[/pastacode]
These functions are used by d3 to “loop the data” and the return value is what the actual data value is set to. So we use our scale functions here to scale the x and y values after we have pulled them out of each object. We then return the scaled value to the loop.
Finally, we set up our “draw()” method, when called, will draw the actual line on the graph:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

draw: function() {
      state.svg.data([state.data]).append('g').append("path").attr("d", line);
    }

[/pastacode]

Composing ‘Chainable’ Functions

Mattias Petter Johansson has a great video explaining the difference between composition and inheritance chains in development.

I won’t repeat the tutorial he gives in the video because frankly, his video is better than anything I could write. But!

I want to add a tweak to his factory function in order to make your factories “chainable”. Basically so you can call something like this:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

sniffles.speed(15).walk();

[/pastacode]

If you aren’t familiar with factory functions, he also has a video here: https://www.youtube.com/watch?v=ImwrezYhw4w that again, explains things better than I could.

So here’s what we want to do. Let’s make a dog. A dog can walk and bark. Our dog will be our main “thing” factory:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

// the thing it is
function Dog(name) {
  var state = {
    name: name
  };
  
  return Object.assign(
    {},
    barker(state),
    walker(state)
  );
}

[/pastacode]

The most perceptive of you might notice that we have something in here called a “barker” and a “walker”. They are functions that we will define in a minute. The thing to notice here is that this function takes a “name” parameter. Essentially, this follows the same end user workflow as a class. A developer using your code will just have to use:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

// use this for factories
var dog = Dog('sniffles');

// instead of classes
var dog = new Dog('sniffles');

[/pastacode]

So you can see, it’s almost the same thing! In fact, in most cases you’ll never notice a difference.

Now for the fun part. Let’s make these “doing” functions that take the state argument. Then lets make their methods chainable.

A dog can bark, so let’s make a “barker” factory:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function barker(state) {
  var _state = state;
  return {
    bark: function() {
      console.log('I am a ' + _state.name);
    }
  };
}

[/pastacode]

Simple enough. However things get more complex when we want to make a “walker” factory. Instead of just having a function called “walk” we want to be able to set the speed of the walk, as well as have a default in case the user just calls .walk().

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function walker(state) {
  var _state = Object.assign(
    {
      speed: 100
    },
    state
  );
  return {
    walk: function() {
      var speed = _state.speed || 50;
      console.log('walking at speed: ' + _state.speed);
    },
    speed: function(speed) {
      _state.speed = speed;
    }
  }
}

[/pastacode]

So now we can start walking!

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

// make a dog named sniffles
var sniffles = Dog('sniffles');

// set the walking speed
sniffles.speed(10);

sniffles.walk();

[/pastacode]

What would be nice is if you could update the speed as you go. If you haven’t made functionality to update any attribute of the state, there’s not really a good way to get changes in speed into sniffle’s state. Also, let’s say you want to limit a developer’s ability to tamper with the internal state of your object. To do this, it would be nice to set speed before we call walk. Of course, we could pass speed as an argument of walk:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

sniffles.walk(1000);

[/pastacode]

But not we have to make special functionality inside our walk function to share the speed in case another function needs to use speed as well. Not good!

So by adding:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

return this;

[/pastacode]

to the speed function we return the context of the speed function which happens to be sniffles! Now we can chain speed().

The function now looks like this:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function walker(state) {
  var _state = Object.assign(
    {
      timeToWalk: 100
    },
    state
  );
  return {
    walk: function() {
      var speed = _state.speed || 50;
      console.log('walking at speed: ' + _state.speed + ' for ' + _state.timeToWalk + ' seconds.');
    },
    speed: function(speed) {
      _state.speed = speed;
      return this;
    }
  }
}

[/pastacode]

So now we can do:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

sniffles.speed(15).walk();

[/pastacode]

Here’s a codepen so you can play with it:

 

See the Pen Dog Factory (chainable) by Mike Newell (@newshorts) on CodePen.

Smart Serialization of JSON

Just wanted to point this one out with Chrome moving dom attributes to the prototype chain.

If you’re used to stringifying dom objects for requests either to local/remote storage. You might be doing something like this alot:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

JSON.stringify(object)

[/pastacode]

But what you’ll find with chrome 43+ is that the properties in prototype chain don’t get serialized. This presents a problem. Luckily, there’s some recursive magic that html5 rocks gives us to do out own serializationZ:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function stringifyDOMObject(object)
{
    function deepCopy(src) {
        if (typeof src != "object")
            return src;
        var dst = Array.isArray(src) ? [] : {};
        for (var property in src) {
            dst[property] = deepCopy(src[property]);
        }
        return dst;
    }
    return JSON.stringify(deepCopy(object));
}
var s = stringifyDOMObject(domObject);

[/pastacode]

Short and quick today!

SVN 101

Let’s start with the basics. I’m assuming you know what svn is and the purpose for it. If not, use Google. This tutorial is to get you going with it. I’m assuming you have it installed and are working on a mac.

UPDATE:

There’s an easier way to structure your project (sorry, I’m learning as I go here…)

Pretty simple, you’re going to create a place to put your repos, populate them, then checkout a working copy:

 

For those of you who want a simpler step by step version, see below:

Set up your test environment:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual” manual=”mkdir%20~%2FLearning%0Acd%20~%2FLearning%0Amkdir%20rawfiles%0Atouch%20rawfiles%2Fstuff.txt”/]

First step is to create a local repository (I’m assuming we don’t want to make this first tutorial more complex than it needs to be…usually your repo lives on a remote server where people can get access, but we are going to work with everything locally to keep it easy):

Create a repo:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual” manual=”svnadmin%20create%20remote”/]

Import your files:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual” manual=”svn%20import%20rawfiles%20file%3A%2F%2F%2FUsers%2F%7BYOUR_NAME%7D%2FLearning%2Fremote%2Ftrunk%20-m%20%22initial%20import%22″/]

Now we assume the “remote” is our repo living on a server somewhere. Time to pull down the project so we can start working with it:

Checkout a working copy:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual” manual=”mkdir%20local%0Asvn%20co%20file%3A%2F%2F%2FUsers%2F%7BNAME%7D%2FLearning%2Fremote%2Ftrunk%20local%2Ftrunk”/]

Let’s see what we have in there:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual” manual=”ls%20-la%20local%2Ftrunk”/]

“Trunk” is just the main repository. It’s common in svn to use trunk the same way someone might use “Master” in git. It’s the production version of things. Not required, but it is convention.

At this point you’re ready to begin working with the files. In 102, I’ll show you how to setup your project to ignore certain files and begin modifications and commits. Then we’ll create some branches and start merging!

Conflict resolution:

Let’s say you get some while working with your branch. I’ll show how to resolve each situation and why they are occuring in the first place.


Local delete, incoming dir edit/delete

local missing or deleted or moved away, incoming dir edit upon merge

These types of conflicts (usually something called a tree conflict) happen when you have removed a directory locally, but there are property changes coming from another branch/trunk on the same directory. Ask yourself the following:

Am I sure these folders are supposed to be deleted?

If you are, then it’s safe to resolve the conflicts in the following ways:

[pastacode lang=”bash” manual=”svn%20resolve%20–accept%3Dworking%20%2FPATH%2FTO%2FFOLDER” message=”” highlight=”” provider=”manual”/]

This will tell svn “hey I’ve resolved everything manually, just take the changes I have locally.”

 

 

 

Cordova Getting Started

Once you have it installed. Run the following:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual”]

cordova create hello com.example.hello HelloWorld
cordova platform add ios
cordova build

[/pastacode]

Open your project in Xcode (under the platforms folder/ios) and you should be able to run it on an ios device!

Git Untrack and Retrack

If you want to untrack an accidentally committed file, then retrack it later:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual”]

git update-index --assume-unchanged path/to/file

[/pastacode]

To untrack it and:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual”]

git update-index --no-assume-unchanged path/to/file

[/pastacode]

to retrack it later!

From here: http://stackoverflow.com/questions/6964297/untrack-files-from-git

How To Build GearVR Apps with Unity

 

Great step by step instructions for setting up your environment correctly here: https://www.reddit.com/r/GearVR/comments/2qcryc/step_by_step_guide_to_building_apps_for_the_gear/

Oculus Signature File:

Get your device id by:

[pastacode lang=”bash” message=”” highlight=”” provider=”manual”]

adb devices

[/pastacode]

Copy the id and paste it on the site below to get your signature file

Oculus signature file: https://developer.oculus.com/osig/

Oculus Android Utility Package:

Download the oculus utilities package: https://developer.oculus.com/downloads/game-engines/0.1.0-beta/Oculus_Utilities_for_Unity_5/

Made a quick video to show you how to build and run on GearVR:

Arguments has a length, Object Literals do not?

I’m going to research on this and get back here. Basically, I’m wondering the following:

Why am I able to test inside of a function for arguments.length. But I can create an object literal and length is undefined? example:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function count(a,b) {
    console.log(arguments.length); // 2
}
count(1,2);

var obj = { a: 1, b : 2 };
console.log(obj.length); // undefined!

[/pastacode]

 

Guaranteed Instantiation in Javascript

quick one today.

Let’s say you like the constructor pattern for objects. You probably do something similar to this:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function Person(name) {
    var __ = this;
    
    __.name = name;
    
    return __;
}

[/pastacode]

Let’s say you forget to use the”new” operator to instantiate the function and instead just call it as is while trying to assign it to a variable:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var mike = Person('Mike');
name = 'john';

console.log(mike.name) // results in john

[/pastacode]

The problem is “this”. Without referring to the “new” keyword, the function’s “this” refers to the global “this”. When you call the function, it can collide with any other variable in the global scope.

Of course you can fix it by doing:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var mike = new Person('Mike');
name = 'john';

console.log(mike.name) // results in mike

[/pastacode]

Of course, this is the right way to do it. But how can you make sure that even if the user doesn’t call it correctly, your class doesn’t create crazy collisions and potentially cause someone to spend hours debugging?

Easy! Check your object scope. Figure out who you belong to and force instantiation otherwise:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function Person(name) {
    var __ = this;
    
    if(!(__ instanceof Person)) {
        return new Person(name);
    }
    
    __.name = name;
    
    return __;
}

[/pastacode]

Now your object will return an instance of itself, even if called the wrong way.

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var mike = Person('Mike');
name = 'john';

console.log(mike.name) // still results in Mike

[/pastacode]

Bye!