March 1, 2013 0

Compiling LESS from a node.js script

By in Uncategorized

LESS is a tool that allows you to write CSS in a programmer friendly way (with variables, and some simple functions), it then converts it to regular CSS for browser friendly consumption.

It’s amazingly easy to use, during development you don’t have to change a thing. You simply import your .less file, then under you import ‘less.js’ and it does it’s magic.

Eventually you need to preprocess it as part of your build operation.

For some reason I could not find a simple response for how to do this. I found many articles / answers for how to run LESS from the command line, or using it with Express to pre-compile it for you when serving then cache it.

Here’s what I ended up using, much of it referenced from the lessc command line tool.

var less = require( 'less' );
var fs = require( 'fs' );
var path = require('path');
 
 
// Load the file, convert to string
fs.readFile( '../less/gaf.less', function ( error, data ) {
  var dataString = data.toString();
  var options = {
    paths         : ["../less"],      // .less file search paths
    outputDir     : "../css",   // output directory, note the '/'
    optimization  : 1,                // optimization level, higher is better but more volatile - 1 is a good value
    filename      : "gaf.less",       // root .less file
    compress      : true,             // compress?
    yuicompress   : true              // use YUI compressor?
  };
 
 
  // Create a file name such that
  //  if options.filename == gaf.js and options.compress = true
  //    outputfile = gaf.min.css
  options.outputfile = options.filename.split(".less")[0] + (options.compress ? ".min" : "") + ".css";
  // Resolves the relative output.dir to an absolute one and ensure the directory exist
  options.outputDir = path.resolve( process.cwd(), options.outputDir) + "/";
  ensureDirectory( options.outputDir );
 
  // Create a parser with options, filename is passed even though its loaded
  // to allow less to give us better errors
  var parser = new less.Parser(options);
  parser.parse( dataString, function ( error, cssTree ) {
      if ( error ) {
        less.writeError( error, options );
        return;
      }
 
    // Create the CSS from the cssTree
    var cssString = cssTree.toCSS( {
      compress   : options.compress,
      yuicompress: options.yuicompress
    } );
 
    // Write output
    fs.writeFileSync( options.outputDir + options.outputfile, cssString, 'utf8' );
    console.log("Converted Less: '" + options.filename + "', to CSS: " + options.outputDir + options.outputfile);
  });
});
 
//
var ensureDirectory = function (filepath) {
  var dir = path.dirname(filepath);
  var existsSync = fs.existsSync || path.existsSync;
  if (!existsSync(dir)) { fs.mkdirSync(dir); }
};
February 26, 2013 0

Unwritten help for Tempo.js

By in Howto, html, javascript

Tempo.js is a templating library for HTML (in javascript) that uses JSON to smartly populate the HTML. This makes it great for doing things such as having a file that you use to localize your app.
There are probably actual localization libraries for just for JS. I don’t care.

When I used Tempo.js today, there were a few things that threw me off, and I found the site’s page which acts as its only documentation to be lacking. (It’s great to show me a lot of cool features, but sometimes you want a realistic and simple hello-world that doesn’t cram everything your library can do in one place)


  • When you pass an object to Tempo, it should be the parent container of the object / objects you wish to templatize.
  • When you pass in an object, make sure it is the actual object (not a jquery object, although it claims to accept them so this is a bug)
  • Here is an example of a snippet from my HTML file:

    <div class="bigCotnainer">
      <div data-template="data-template" >{{instructions}}</div>
    </div>

    Here is an example of my JSON file
    (I love comments / commenting, so I like to put my JSON comments in a node called _COMMENTS)

    [
      {
        "_COMMENT" : "PERFORMANCE CALCULATOR",
        "selector": ".bigContainer",
        "data": {
          "instructions": "Explore the interactive chart to see how the fund has performed during key points of market volatility."
        }
      }
    ]

    As you can see, I have my selector set as .bigContainer not the object with the actual template stub! I like to my strings in a separate file which makes sense, but keep all of that mess inside that file and leave it out of your code.

    Ideally I would like to just run Tempo.js on page init and be done with it.
    Well my solution was to make my JSON container an array of objects, where each object has a selector and a data object. If you have that you can then do something like this:

    $.get( url, function ( dataString ) {
      var data = JSON.parse( dataString );
      for ( var i = 0; i < data.length; i++ ) {
        Tempo.prepare( $( data[i].selector )[0] ).render( data[i].data );
      }
    } ;

    (I used Jquery in the above example. I hate jquery, don’t use it if you can avoid it which is often!)
    That will parse your strings file, and find the given ‘selector’ and render it with the accompanying data for each object in your root array.
    If you use the _COMMENT tag, these things combined are a very pretty way to keep web-app organized.

    December 8, 2012 0

    A Little About Digital Audio and Linear PCM

    By in iOS

    This is from Apple’s documentation on CoreAudio.

    Since I find wikipedia to be only marginally helpful these days (it actually suffers from TOO much information) I found it explained these concepts so well, I had to quote it for future reference.

    A Little About Digital Audio and Linear PCM Most Core Audio services use and manipulate audio in linear pulse-code-modulated (linear PCM) format, the most common uncompressed digital audio data format. Digital audio recording creates PCM data by measuring an analog (real world) audio signal’s magnitude at regular intervals (the sampling rate) and converting each sample to a numerical value. Standard compact disc (CD) audio uses a sampling rate of 44.1 kHz, with a 16-bit integer describing each sample—constituting the resolution or bit depth.

    A sample is single numerical value for a single channel. A frame is a collection of time-coincident samples. For instance, a stereo sound file has two samples per frame, one for the left channel and one for the right channel. A packet is a collection of one or more contiguous frames. In linear PCM audio, a packet is always a single frame. In compressed formats, it is typically more. A packet defines the smallest meaningful set of frames for a given audio data format.

    In linear PCM audio, a sample value varies linearly with the amplitude of the original signal that it represents. For example, the 16-bit integer samples in standard CD audio allow 65,536 possible values between silence and maximum level. The difference in amplitude from one digital value to the next is always the same.

    Tags: , ,

    November 18, 2012 0

    Excellent open-course, from NAND to Tetris

    By in Uncategorized

    Came across this while I was reading an entry on #ALTDEVBLOGADAY. The entry was part 2 of 9, C / C++ Low Level Curriculum part 2 which is interesting in it’s own right.

    There was a link to this interesting MIT open course called: From NAND to Tetris, which discussing building an entire computer from first principals. The idea is to work backward, instead of starting at high-level abstraction beginning at the lowest interesting level in computer science (logic gates)

    Although not required, it’s meant to be consumed with it’s own accompanying book, which i’ve already ordered and should get here by Tuesday – i’m very excited to start reading it and going through the course.

    The Elements of Computing Systems: Building a Modern Computer from First Principles

    November 8, 2012 0

    List of programmer shiny things

    By in Opinion

    This is from Andrew Bell’s talk at the EyeO festival. I’m taking it out of context, and in fact he was talking about focusing in on your craft, not being distracted, and finishing projects that you start. “Which of these will you avoid this year, in order to finish your projects?”

    I think it’s also a good list of interesting technologies to jump into… blasphemy i know.

    The talk is awesome and worth watching in full:
    https://vimeo.com/51533137

    October 27, 2012 1

    Thoughts on Dart

    By in Dart, Opinion

    Lately I’ve started playing around with the Dart programming language by Google. The idea behind Dart, is that writing applications in javascript is really a painful act. Sure overtime many of us have gotten used to the various pain points, and there are conventional workarounds that have essentially become part of the ‘hidden standard’ of Javascript language. But why should we have to live with them? Just because it is, doesn’t mean we should be forced to deal with it!

    Let me give you an example, in Javascript how would you go about creating a class (Note: Please don’t bother me with the semantics of class vs prototypical inheritance, just go with it for the sake of argument)? Well here’s one way:

    Animal = function () {
        this.isAlive = true;
    }
    Animal.prototype = {
        eat: funciton(){},
        pray: function(){},
        love: function(){}
    }

    So far so good, no big deal here, now we can create many new Animal’s all we want. However what if we want to subclass Animal, to a more specific type of say Dog?

    Well here’s where javascript’s faults come into play, there is no one way to do this so what you have is many people reinventing the wheel and confusion for new comers especially from other languages when they attempt to implement something as simple as creating a Dog that inherrits from Animal.

    Here’s one way of doing it in Javascript:

    Dog = function() {
        Animal.call( this ); // Call super's constructor
    }
    Dog.prototype = Object.create( Animal.prototype );

    Here’s a different way of tackling the problem:

    function extend( subclass, superclass ) {
     
        var originalSubclassPrototype = subclass.prototype;
     
        // Store the superclass prototype in a surrogate function
        var F = function(){};
        F.prototype = superclass.prototype;
     
        subclass.prototype = new F();
        subclass.superclass = superclass.prototype;
        subclass.prototype.constructor = superclass;
     
        for(var method in originalSubclassPrototype) {
            if( originalSubclassPrototype.hasOwnProperty(method) )
                subclass.prototype[method] = originalSubclassPrototype[method];
        }
     
    }

    Which is correct? Well the answer is both, there’s plenty of ways to skin a classy cat in Javascript, and these are just two of them, there’s plenty more out there as well. To me having too many ways to do something as simple as creating a subclass is a A Bad Thing.

    In Dart there is only one way to create a Class, and only one way to create a subclass:

        class Vec2 {
            num x;
            num y;
            Vec2( this.x, this.y );
        }

    That’s it, and in case you’re wondering about that sleek looking constructor, as you should be, well that is a special type of syntatic sugar shorthand in Dart that is the equivalent of:

        class Vec2 {
            num x;
            num y;
            Vec2( num pX, num pY ) {
                x = pX;
                y = pY;
            }
        }

    How many times have you had to create a constructor where the first 10 lines were just simply setting the variables of the local instance? A lot i’m sure. Instead Dart allows you to simply state that the arguments passed in should be set to the respective local variables. Also notice that I did not type the word this. In Dart the scoping is already correct, so there is no need to explicitely type ‘this’ (although you can if you like).

    Creating a subclass is equally as straight forward:

    /// A circle is similar to a [Vec2] except it contains an area.
    class Circle extends Vec2 {
      /// Radius of the [Circle]
      num radius;
     
      /// Creates a new [Circle] with [radius]
      Circle( num pX, num pY, this.radius) : super(pX, pY);
     
      /// Returns whether a point is contained within [this] [Circle]
      bool containsPoint( Vec2 p ) => ( distanceSquared(p) <= radius*radius );
    }

    That’s all there is to it, no confusion about which is the correct way, the “fastest” way, etc.

    A couple of other things to notice here as well. Firstly are the comments. In Dart a comment that contains three slashes, ///, is considered a Documentation comment. It will be parsed by the built-in (!!) Dart-Doc generator. It even uses Markdown so you don’t have to write annoying HTML in your Documentation comments. Again notice the brackets around [Vec2], because Dart has full knowledge of your application, it knows to go and find the class Vec2 and link to it in the documentation.

    So back to subclassing, notice our constructor:

    Circle( num pX, num pY, this.radius) : super(pX, pY) {
        print("My radius is ${radius}");
    }

    Here we are using another two special constructs Dart provides for constructors. The first is the ‘initializer list’, which come from C++. They allow you to set properties separated by comma’s after the constructor, but outside of the function’s body. Notice the call to super, very straightforward.

    Finally the last thing to notice is the string interpolation occuring in the ‘print’ function (essentially console.log). Here we have a single string, and inside we have a special syntax ‘${}’, where inside we can place an expression ( or value ), that dart will evaluate for us. No more having to concact strings with plus signs and making typos that are hard to spot.

    Overall I’m very much liking the things that Dart is bringing to the table, best of all it compiles to Javascript so it will work on any modern browser. Currently Dart’s compiled javascript, runs at 80% speed of something written in vanilla javascript, and getting it’s not even at version 1.0 yet! Also worth mentioning that DartVM is already outperforming V8 in nearly all javascript benchmarks.

    In the next post I’ll dissect a few more interesting things that I like about Dart, and a few who I dislike. In the meantime, don’t waste any time, go watch the screencast that sold me http://www.dartlang.org/docs/editor/

    October 23, 2012 0

    Calculating the gravity of the gravitational force or 0.00000000000667

    By in math, snippet, sourcecode

    Gravity is by far the best force in the universe. Despite being the weakest of the “main” four (strong nuclear force, weak nuclear force, electromagnetism, gravity). It is the one that dominates given enough time and distances. All this even though it falls of inversely to the square of the distance, meaning, if you double the separation between the two objects you quarter the force, or if you cut the separation in half you quadruple the force of attraction.

    It’s also one of my favorite things when creating visualizations, because things move so beautifully when you simply let gravity take over.

    So I thought I would give it it’s own tiny blog post, in honor of its value 0.00000000000667

        // Compute the net force acting between the invoking body a and b, and
        // add to the net force acting on the invoking Body
        public void addForce(Body b) {
            Body a = this;
            double G = 0.00000000000667;
            double EPS = 0.0001;      // softening parameter
            double dx = b.rx - a.rx;
            double dy = b.ry - a.ry;
            double dist = Math.sqrt(dx*dx + dy*dy);
            double F = (G * a.mass * b.mass) / (dist*dist + EPS*EPS);
            a.fx += F * dx / dist;
            a.fy += F * dy / dist;
        }
    September 28, 2012 0

    Eclipse template project with cocos2dx

    By in C++, eclipse, gamedev, Howto

    I have created an eclipse project template, which contains an SDK project, with a NDK C++ bindings ( done via ‘javah’ build step ), combined with Cocos2dx helloworld project. I have used it as the base for 2 projects, and figured I would share.

    https://github.com/onedayitwillmake/EclipseAndroid_NDK_SDK/tree/cocos2dx

     

    May 24, 2012 0

    Using EclipseLovesCinder template

    By in C++, C++11, cinder, eclipse

    About a year ago, I created a template to use the Cinder framework within Eclipse. I still use it all the time, as I still find Eclipse a better C++ editor (although xcode is slowly catching up if you use the compile and use the latest LLVM). I recently decided to revisit it and update it to better fit the workflow I prefer, and fix issues I’ve over time found work arounds for.

    With that I decided that it was time to give some new instructions so here they are. I’ll revisit this post with more details, but if pictures are a 1000 words this is a pretty big post.

    Read the rest of this entry »

    April 14, 2012 1

    Better Eclipse Icon for Android Development

    By in C++

    Every time I setup eclipse for a new computer, new OS install, or decide to use it for a different language/platform I find myself recreating the icon for it. This usually occurs at the VERY beginning of the affair with a new whatever, so I have plenty of energy and really want to get off on the right foot. It’s kind of part of the fun.

    Read the rest of this entry »