Archive for the 'Code and Cruft' Category

Communication Between Directives in AngularJS

Monday, December 17th, 2012

Warning: This article is long and thorough. If you’re in a hurry, you can skip straight to the final product here:

http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview

Prerequisites to this article

Before reading this, get to know these AngularJS terms. You don’t need too much depth, but you need to know what they are:

You should also peruse the Angular Developer Guide, but don’t feel bad if a lot of the jargon does not make much sense at first.

Step 0: Roadmap

We’re going to create two custom directives that communicate with each other. We’ll really dig deep into the first directive, explaining every line of code as we go.

Then we’ll glue the directive to a controller via a scope object.

Lastly, we’ll create a second directive and glue it all together.

Step 1: A basic directive, dissected

For this example, we’ll create a custom search box that can be placed in our app with a custom <my-search-box> element. This directive causes Angular to convert <my-search-box> in your HTML into <span>My Custom Search Box</span>. This is not useful yet, but it will become immensely useful as we grow this concept in a few paragraphs.

We’ll create a file called “app.js” with this content:

angular.module("MyApp", []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      replace: true,
      template: '<span>My Custom Search Box</span>'
    };
  });

Let’s walk through each line of that directive:

angular.module("MyApp", []).

This line declares a new module called “MyApp”. The empty array to the right can contain the names of other modules on which this module depends (this is where you would put AngularUI modules for example if you want to use AngularUI). In this case, this module happens to be our “main” application module, but Angular really doesn’t know that from this line of code. That happens in the HTML with <html ng-app="MyApp">. Also, you only declare your main application module once, even if you have many directives. There are ways to look up your module if your code spans multiple files, or you can just create a global variable to reference your module and use that when building your directive.

  directive('mySearchBox', function() {

Here we are declaring a new directive. Notice that we camel case the directive name. When Angular encounters <my-search-box> in the HTML, it will normalize that into “mySearchBox” to look up the directive. Thus, “mySearchBox” is called the “normalized” name.

    return {

Angular expects the directive function to return an object with properties that describe the directive.

      restrict: 'E',

This tells Angular that “my-search-box” must be an element. Angular directives can also exist as HTML attributes, HTML class names, and even HTML comments (!). It’s okay if this doesn’t make sense yet.

      replace: true,

This tells Angular to fully replace <my-search-box> with the directive’s template HTML. Alternatively, Angular can add the directive’s template HTML to the <my-search-box> element as a child element. For our example, we want Angular to fully replace <my-search-box> because <my-search-box> is not a valid HTML element name. You can imagine wanting Angular to simply augment an element with child elements in some scenarios, but not this example. We’re effectively creating a “widget” that can be instantiated and reused in our HTML.

      template: '<span>My Custom Search Box</span>'

This is the directive’s HTML template that will be rendered by the browser. I don’t recommend using hard-coded template strings in your directives like I’ve done here. I do it this way to make the example clear. Normally, I use the templateUrl property and serve the HTML as a “partial” from my web server. Angular caches these partials, and you can even pre-load them when your app loads. This way, I can use server-side template technologies for things like localization. Although, for the best performance, I recommend that you serve these partials statically from a CDN or other fast caching service.

Now we can use this directive in our HTML like this:

<html ng-app="MyApp">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body> 
      <my-search-box></my-search-box>
  </body>
</html>

When you visit that page in your browser, you’ll see “My Custom Search Box” if all went well above.

So far this is a pretty useless directive, but we’are about to take it to the next level.

Step 2: Giving your directive its own scope

Each instance of a directive has its own scope. And of course, the scope is a child of the enclosing scope where you instantiated the directive in the HTML. For example, if your directive exists inside a <div ng-controller="MyController">, then your directive’s scope will be a child of MyController‘s $scope.

For example, the following HTML uses two <my-search-box> elements. Angular gives each <my-search-box> its own independent scope:

  <body> 
      <my-search-box></my-search-box>
      <my-search-box></my-search-box>
  </body>

Let’s define our directive’s interface to the outside world using the scope property. Our interface will have two values: searchText and isSearching. We will use searchText to store the user’s search text that they enter into an <input> box, and we’ll use isSearching to tell the directive when a search is in progress.

angular.module("MyApp", []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        searchText: '=',
        isSearching: '='
      },
      template: '<span>My Custom Search Box</span>'
    };
  });

Did you see the scope = {...} property above? That defines the public elements of this directive’s scope. Notice how we used '='? That tells Angular that we want a scope variable to have two way binding to the outside world. This is part of the directive’s HTML interface. This allows callers to use our directive like this:

<my-search-box
  search-text="someScopeVariable"
  is-searching="someOtherScopeVariable">
</my-search-box>

In other words, the directive allows outside callers to bind their own scope variables to this directive’s searchText and isSearching variables. This is how you communicate with the directive from the outside world.

The variables someScopeVariable and someOtherScopeVariable come from the enclosing scope, which usually is managed by a controller outside the directive. If, for example, we had <div ng-controller="MyController"> enclosing <my-search-box>, then someScopeVariable and someOtherScopeVariable would be managed by MyController.

In the code above, the search-text gets normalized into searchText in the directive’s scope. Likewise, is-searching becomes isSearching.

When we assign search-text="someScopeVariable", we are telling Angular to bind this directive’s searchText scope variable to a scope variable from the enclosing scope called someScopeVariable. Any time the enclosing scope’s someScopeVariable changes, the directive’s scope variable searchText will also change. And it works in the other direction too. Any time the directive changes its searchText variable, Angular will automatically change the enclosing scope’s someScopeVariable to match.

These scope variables are useless unless we also make them visible somehow, so let’s modify our template HTML to use them. While we’re at it, let’s make this actually look like a search box instead of a simple piece of text:

angular.module("MyApp", []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      scope: {
        searchText: '=',
        isSearching: '='
      },
      controller: function($scope) {
        $scope.localSearchText = '';
        $scope.clearSearch = function() {
          $scope.searchText = "";
          $scope.localSearchText = "";
        };
        $scope.doSearch = function() {
          $scope.searchText = $scope.localSearchText;
        };
      },
      replace: true,
      template:
      '<form>' +
        '<div>' +
          '<input ng-model="localSearchText" type="text" />' +
        '</div>' +
        '<div>' +
          '<button ng-click="clearSearch()" class="btn btn-small">Clear</button>' +
          '<button ng-click="doSearch()"    class="btn btn-small">Search</button>' +
        '</div> ' +
        '<div ng-show="isSearching">' +
          '<img ng-show="isSearching" src="http://loadinggif.com/images/image-selection/3.gif" /> ' +
          'Searching...' +
        '</div>' +
      '</form>'
    };
  })

Remember, I suggest you use templateUrl instead of template when your HTML starts to grow like this.

Now we have a search box form that lets the user enter some search terms, which we store in the directive’s scope as localSearchText. Notice that we didn’t put localSearchText in the scope: {…} definition, because it needs no external binding. In other words, this is a “private” scope variable that the directive uses to store the human text input until we are ready to actually do the search. This is because we don’t want every single keystroke to initiate a search. Only when the user clicks the “Search” button.

Notice also that we added a controller with controller: function($scope) {...}. This code defines a typical controller so our directive can take action in response to user input, like button clicks with ng-click.

This HTML also provides a “Clear” button to zero out the search box and a spinner to show when the search is in progress. The directive relies on outside callers to tell it when a search is in progress by setting the isSearching variable to a “truthy” value.

After making these changes to app.js, our page should look like this:

Now that directive is finished. Notice it doesn’t do much. It requires an outsider to stimulate it into action.

Step 3: Creating a Controller

Let’s create a controller that communicates with the directive we wrote. This isn’t strictly required to allow two directives to communicate, but in most cases it will be necessary because someone has to glue them together with the business logic specific to your application. This is a job well suited to an Angular controller.

Let’s make a simulated city search that allows the user to search for cities. Because it’s an example, the search will always return the same results.

<div ng-controller="CitySearchController">
  <h1>Search for Cities</h1> 
  <my-search-box search-text="citySearchText" is-searching="isSearchingForCities"></my-search-box>
</div>

And the accompanying controller, which I placed in app.js:

function CitySearchController($scope, $timeout) {
  $scope.$watch("citySearchText", function(citySearchText) {
    $scope.citySearchResults = [];
    if (citySearchText) {
      $scope.isSearchingForCities = true;
      $timeout(function() {
        // simulated search that always gives the same results
        $scope.isSearchingForCities = false;
        $scope.citySearchResults = ['New York', 'London', 'Paris', 'Moab'];
      }, 1000);
    } else {
      $scope.isSearchingForCities = false;
    }
  });
}

This controller’s $scope.citySearchText and $scope.isSearchingForCities variables are bound to the directive’s scope variables searchText and isSearching because of the HTML attributes that we specified on <my-search-box>.

This controller is pretty basic, so I won’t describe every line of code. All it does is $watch() for changes to citySearchText and get some fake search results with Angular’s $timeout service.

Because of Angular’s excellent isolation-centric design, this controller would be very easy to write unit tests for, but that’s another article.

When you visit the page, you should now see a search box. If you enter some text into the input box and click “Search”, you’ll see a spinner for 1 second, which then disappears:

Step 4: Finally add a second directive

Now we’re ready to add another directive. For this example, we’ll create a search results directive. This directive has almost the same public interface (i.e., scope) as the <my-search-box> directive, with one extra variable: the actual search results that caller wants to display.

It looks like this:

 directive('mySearchResults', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {
        isSearching: '=',
        searchResults: '=',
        searchText: '='
      },
      replace: true,
      template:
        '<div ng-hide="isSearching">' +
          '<h4 ng-show="searchResults">Found {{searchResults.length}} Search Results For "{{searchText}}":</h4>' +
          '<ul ng-show="searchResults">' +
            '<li ng-repeat="searchResult in searchResults">' +
              '{{searchResult}}' +
            '</li>' +
          '</ul>' +
        '</div>'
    };
  });

Everything should look familiar from your study of the first directive. There are no new concepts here. Let’s use our directive in our HTML:

  <div ng-controller="CitySearchController" style="margin: 20px">
      <h1>Search for Cities</h1> 
      <my-search-box search-text="citySearchText" is-searching="isSearchingForCities"></my-search-box>
      <my-search-results is-searching="isSearchingForCities" search-results="citySearchResults" search-text="citySearchText"></my-search-results>
    </div>

Now your page should show some search results after clicking the “Search” button and waiting for 1 second:

Just to prove that there is indeed zero coupling between the two directives and the controller, I added a second controller and a second instance of each directive to search for fruits, which you can see in the plunk below.

The Finished Product

Here it is: http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview

Conclusion

From the sheer length of this article, you may think that this is complicated, but the reality is that it only took me about 30 minutes to whip together the working example in the plunk.

Main points I hope you took from this article:

  • Directives are easy to create.
  • Directives have their own scope
  • Directives can communicate with the outside world via HTML attributes
  • Directives encourage loose coupling
  • Directives encourage reuse and UI consistency
  • Directives are easy to test (well, this is a future article)
  • Controllers can use directives with zero coupling
  • The Prime Directive has nothing to do with AngularJS (bummer)

AngularJS is too humble to say you’re doing it wrong

Sunday, December 2nd, 2012

For years, web application developers have used DOM manipulation tools like jQuery to control their user interface. Astute developers have taken it to the next level with client-side templating tools like Mustache and Handlebars.js to build sophisticated user interfaces on the client side.

And then AngularJS came along.

And we all realized we’ve been doing it wrong.

Way wrong.

The Old Way

Remember before you discovered AngularJS? Back when your code was organized like this:

  1. HTML that defines your page
  2. JavaScript that downloads AJAX data
  3. HTML that defines a client side template
    (yeah, this: <script type="text/html">...</script>)
  4. JavaScript that renders the client-side template
  5. JavaScript that injects the rendered template HTML into the DOM

You thought that was pretty cool. “Hey look,” you said, “I’ve off-loaded template rendering to the browser!”. Yeah, you were pretty cool.

But then AngularJS showed you how you were wrong. You could accomplish the same client-side magic with a lot less code.

The New Way

Under AngularJS, your code can be organized like this:

  1. HTML that defines your page and client-side templates inline
  2. JavaScript that downloads AJAX data

How does that even work? I mean, you’ve got like less than half of the bullet points now.

The answer: Data Binding.

Data Binding is the secret sauce of AngularJS (along with a couple dozen other delicious spices and condiments). Oh, and it’s not a secret at all. The code is actually pretty easy to read, despite being pure magic awesomeness on environmentally-friendly steroids.

Shall We Do Show-and-Tell?

The old way

This should be very familiar. You’ve got an HTML page, and you want to add some dynamic content with a client-side template:

Here’s the page HTML:

<html>
  <body>
    <div id="my-list-of-animals">
    </div>
  </body>
</html>

Let’s use Handlebars for the client-side template:

<script id="animal-template" type="text/x-handlebars-template">
  <div>
    <div>{{animalName}}</div>
    <div>{{favoriteFood}}</div>
  </div>
</script>

And you need some JavaScript to download the AJAX data, render the client side template, and inject it into the DOM:

$.get("/api/animals/", function(response) {
  var source = $("#animal-template").html();
  var template = Handlebars.compile(source);
  $.each(response, function() {
    var html = template(this);
    $("#my-list-of-animals").append(html);
  });
});

Put all that together somehow, and wow, that’s a lot of code to do something that should be very simple.

That covers all 5 bullet points above. You’re still cool, right?

The AngularJS Way

Remember how there are only two bullet points. Well, here they are:

First, your page HTML:

<html ng-app>
  <body>
    <div ng-controller="MyAnimalController">
      <div ng-repeat="animal in animals">
        <div>{{animal.animalName}}</div>
        <div>{{animal.favoriteFood}}</div>
      </div>
    </div>
  </body>
</html>

Did you see that? There’s no <script> hack. The template is right inside the page! Right there. In-line. Right where you wanted it all along, but never had the guts to ask. But I digress.

Second, the JavaScript:

function MyAnimalController($scope, $http) {
  $http.get("/api/animals/").success(function(response) {
    $scope.animals = response;
  });
}

And that’s it. It really is glorious. The AngularJS team really distilled the client-side template problem to its essence and produced an elegant solution. But don’t take my word for it. Check out the win list below.

Win List

Look at all the prizes you won by using AngularJS:

  1. CSS classes are just for CSS now.
    You used to abuse the HTML class attribute so you could find elements in the DOM with jQuery. Now, your class attributes are only for CSS. You don’t have to wonder anymore whether a particular class is used by JavaScript or CSS. The answer is always CSS: The way nature intended
  2. No <script> hacks.
    You don’t have to trick the browser into ignoring your client-side templates anymore. Don’t you feel cleaner?
  3. Client side templates are cohesive with your page
    You used to have a pile of client-side template files scattered throughout your project, or all crammed into your HTML <head>. Now they are right in the page, exactly where you wanted to read them in the first place.
  4. You don’t have to name every template
    You used to name each <script> element with an “id” attribute to make it findable by jQuery. You can nuke those strings in your JavaScript and HTML, and not worry about them getting out-of-sync.
  5. You have control over the scope of your JavaScript
    Previously you had to worry about your jQuery selectors casting too wide a net and selecting elements beyond what you intended. For example, suppose there happened to be an element in the page somewhere with class “animal”, and you didn’t know about it. Then you wrote a jQuery selector like $(“.animal”). Boom, you just mofidied an element you didn’t intend to. With AngularJS, your JavaScript cannot reach outside the ng-controller demarkation.
  6. You don’t have to remember to clean up HTML on refresh
    Let’s say I want to refresh the animal list in this example. Under jQuery, I have to remember to do this: $("#my-list-of-animals").html("") before I start .append()ing new animals. In AngularJS, I just replace $scope.animals with the newly downloaded list, and it automatically clears out the old HTML.
  7. Your JavaScript is cleaner
    Your JavaScript has no CSS selectors anymore. It used to be littered with strings to locate elemenents in the DOM. Now it’s just got business logic. Pure, sweet business logic.
  8. You can unit test your JavaScript without a DOM
    I should have mentioned this first. Notice how my JavaScript has no knowledge of a DOM? It doesn’t even know there’s HTML involved at all. This makes it much easier to unit test, because you don’t need to load a big chunk of fixture HTML to test your JavaScript. AngularJS provides some great docs on testing too.

Almost Too Humble

I started reading about AngularJS and re-working parts of my projects to use it in earnest only a few weeks ago. A day into the effort, the light bulb went on for me:

I’ve been doing this all wrong

At that point, I started to wonder why the AngularJS team didn’t write article after article with the same title: “You’re Doing It Wrong”. And that’s what inspired me to write this.

So there you have it. An opinionated blog post about an opinionated framework.

Temporarily Suppress Console Output in Python

Thursday, October 25th, 2012

Have you ever wanted to temporarily suppress console output in Python? But you really want it to be temporary, even if an exception happens. Maybe you are calling into some idiot’s library who spams your console. Yeah, that’s happened to me before (maybe I was the idiot–I’m not tellin’).

Here’s a handy way to suppress stdout temporarily in your program:

First, slap this code into your project:

Use it like this:

Compiler vs. Interpreter

Thursday, October 18th, 2012

What’s the difference between writing a compiler and writing an interpreter?

Easy:

Writing an interpreter is like reading an instruction manual and performing the steps.

Writing a compiler is like reading an English instruction manual, translating it into German, and handing it to a German person to execute the steps.

Throttling Your Network Connection on Mac OS X

Wednesday, April 11th, 2012

Sometimes you just need to sloooooow doooooooown to test how your software behaves when your internet connection is crappy.

Linux has tc to do this, but what about Mac OS X?

That’s where ipfw comes in. It does a lot of stuff. I mean a lot, but we’re just going to use it to slow down our internet connection today.

Here’s an example that throttles your web browsing experience to 50 KBytes/second:

sudo ipfw pipe 1 config bw 50KByte/s >/dev/null
sudo ipfw add 1 pipe 1 src-port 80
sudo ipfw add 1 pipe 1 dst-port 80

And to turn it off (this is an important step!):

sudo ipfw delete 1

To make this super easy to use, I wrote a handy little shell script called network-throttle, which you can put in your PATH and run like this:

network-throttle on --port 80 --rate 50KByte/s

And to turn it off:

network-throttle off

You can download the shell script below. Put it in your PATH and name it network-throttle.

Or, if you like things shiny, pointy, and clicky, you can use the Apple Network Link Conditioner by installing X-Code.

Here’s the magical shell script:

#!/bin/bash
#
# Throttles your Mac OS X internet connection on one port.
# Handy for testing

set -e

RATE=15KByte/s
PORT=80
PIPE_NUMBER=1
ACTION=

function usage()
{
    echo $1
    echo
    echo "Usage: `basename "$0"` <action> [options]"
    echo "  Action:"
    echo "     on"
    echo "     off"
    echo
    echo "  Options:"
    echo "  --rate <rate>"
    echo "      Example: --rate 100KByte/s"
    echo "  --port <port> (default is 80 if you don't specify --port)"
    echo "      Example: --port 80"
    exit 1
}

function turn_throttling_off()
{
    echo "Turning off network throttling"
    sudo ipfw delete $PIPE_NUMBER || echo "Is it already turned off?"
}

function turn_throttling_on()
{
    echo "Throttling traffic to port $PORT: $RATE"
    sudo ipfw pipe $PIPE_NUMBER config bw $RATE >/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER src-port $PORT >/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER dst-port $PORT >/dev/null
}

# Grab command line args:
while [ -n "$1" ]; do
  case $1 in
    --rate)
      shift
      RATE=$1
      ;;
    --port)
      shift
      PORT=$1
      ;;
    *)
      ACTION=$1
  esac
  shift
done

[ -n "$ACTION" ] || usage "Error: no action specified"

case $ACTION in
  on)
    turn_throttling_off >/dev/null 2>&1 # in case it's already on, clear out the old one
    turn_throttling_on
    ;;
  off)
    turn_throttling_off
    ;;
  *)
    usage "Error: Bad action specified"
    ;;
esac

Dangerous Python Default Arguments

Sunday, April 1st, 2012

Dangerous? Really? Well, not if you understand how it works.

Note: I’m not the first to write about this subject.

When writing a function in Python, it’s handy to use default argument values like this:

And you think this will provide an easy way to let lazy callers pass no arguments to your function, and it will simply be called as if they had passed ['some item'].

But you would be wrong.

What actually happens is this (interactive shell output):

That’s right. Python creates a new object, named some_list that persists as an attribute of the function. If callers don’t pass their own some_list object, this one, the same one, is used each time your function is called.

Weird, huh?

If users pass their own some_list object, then sanity is restored:

So why is this? Python stores each default argument value in a special attribute on the function called func_defaults. You can inspect any function’s default arguments like this:

Because functions in Python are just objects, you can store arbitrary attributes on them. And indeed, you can actually modify the default function arguments at run time, like this:

But remember: Just because you can doesn’t mean you should. I would not recommend making a habit of stuff like this, especially if you like not having your co-workers hate you.

It’s always good to know how your tools work. Inside and out.

I discovered this behavior when investigating the pylint W0102 message, and discovered that this message actually inspired an entire wiki of Pylint message descriptions.

The Code Quality Continuum

Monday, March 5th, 2012

What does it take to write high quality code?

Here’s a little table that I use to judge my own code quality:

Code Quality Continuum Chart

Future axes to add:

  1. Ratio of the initial development cost to the long term maintenance cost
  2. Code testability: Code can be manually tested, code can be tested with automation, code can be tested via continuous integration

Book Review: Treading on Python

Wednesday, December 28th, 2011

Treading on Python by Matt Harrison provides a basic introduction to the Python programming language for programming novices.

Background of the reviewer

I have been writing code professionally for 10 years. I’ve spent most of my time in C++, but I’ve written a handful of small Python scripts (less than 100 lines) and a couple medium-sized Python applications (hundreds of lines with multi-threading).

In Treading on Python, I was looking to shore up my Python foundation before jumping into my first big Python project.

I was not disappointed.

Who is this book for?

If you are interested in learning how to write computer programs as a beginner, this book is probably a pretty good place to start. The book starts by persuading you to choose Python as your first programming language for two main reasons:

  1. Python is used widely in industry
  2. Python is easy to learn

This book is written primarily for brand new programmers. It provides practical advice for getting started at the very early stages of programming:

  • How to edit Python code
  • How to run Python programs
  • How to use the Python interactive shell
  • What a variable is (complete with cattle analogy)
  • How to use strings, integers, and lists

However, even if you have, like me, written some small to medium sized Python programs, you will still probably benefit from the following useful information:

  • Python’s handy dir and help functions
  • The enumerate() function
  • The dictinoary setdefault() method
  • Python’s concept of None and object id
  • List slicing
  • import and from...import semantics
  • And a surprisingly good list of pitfalls to avoid

Early in the book, Matt spends a lot of time explaining basic programming concepts (like variables). He does this by providing real world analogies (like cattle) that will probably seem superfluous to the experienced programmer, but that may be beneficial to the programming novice. I was tempted to skip the first few chapters but I’m glad I read them competely. The book is peppered with little gems that reveal what writing Python code is all about, and even the most basic topics still provide these insights.

Who is this book not for?

If you are looking for a book that delves deep into Python, this is not the book for you. Notably absent concepts from this book include:

I don’t offer this list as a criticism of the book. The book’s stated purpose is clearly not to provide a comprehensive Python treatise for the experienced programmer. But if you are considering this book as a way to delve into any of these concepts, this is not the book for you.

Opinion of the book

Matt clearly knows his Python. He has peppered the book with helpful tips that compelled me to whip out my Python interpreter to experiment. Many of the tips were very handy, even for a semi-experienced Python programmer such as myself.

Matt is pleasingly frank in his recommendations to avoid certain approaches, and after reading the book, I feel like I have a better eye for assessing how “Pythonic” something is. In fact, now that I have finished the book, I can look back on Python code I wrote before reading the book, and critique the heck out of it. Prior to reading this book, my Python code looked a lot like my C++ code, which is just a shame. This book can help inoculate you against such behavior.

The book reads smoothly and quickly. Matt is very careful to keep his explanations succinct and clear, such that you don’t feel like you’re reading a college text book or a reference manual. Even still, the book does contain a high information density.

On my iPad, with the default font size, the book is 243 pages in landscape mode and 147 pages in portrait mode.

I finished the book in fewer than a dozen 15-30 minute sittings.

Conclusion

If you can already crank out Python list comprehensions and lambda expressions, this is probably not the book for you. If you are an experienced programmer and want to learn Python, this is a fast way to start. If you are a total programming novice, this may be a good way to begin, but I’m not a great judge for this audience.

Fun Python Solution to Euler Problem 79

Tuesday, December 27th, 2011

Nothing says Merry Christmas like Project Euler.

Here’s a nifty solution to Problem 79 that uses Python and Graphviz.

The problem is to identify a user’s password given a bunch of successful logins (taken from some kind of nefarious keylogger–those crafty devils). The çatch is that each login is actually a subset of the actual password. Of course, they give you a sample of 50 successful logins.

So I decided to whip up some Python code to ingest each login and store a list of digit precedence. Then, the code prints out a Dot file which we turn into an image using the “dot” command. I ran this on Mac OS X, but it should work just fine on any Linux box (hint: install the “graphviz” package).

Here’s the Python code:

problem79.py:

digit_precendence = dict()

for line in [line.strip() for line in open("./keylog.txt")]:
    for index, char in enumerate(line):
        digits = digit_precendence.setdefault(int(char), set())
        if index < len(line)-1:
            digits.add(int(line[index+1]))

print "digraph problem79 {"
for (digit, subsequent_digits) in digit_precendence.iteritems():
    for subsequent_digit in subsequent_digits:
        print "   %d -> %d;" % (digit, subsequent_digit)
print "}"

Save that as problem79.py, download keylog.txt into the same folder, and run the program like this:

python problem79.py | dot -Tpng > problem79.png

Then view problem79.png, and voila! Graphviz just put the answer right in front of your nose: 73162890.

Cocoa Noob Pitfalls

Monday, September 12th, 2011

I just finished writing my first iPhone app. I have a background in Java, C++, Python, and a smattering of other programming languages on Linux and Windows in both embedded and desktop environments, so that hopefully explains my brain damaged context.

Here are the pit falls I stumbled upon while climbing up the Cocoa learning curve:

Retain/Release Memory Leaks

It wasn’t immediately obvious to me that adding an NSObject pointer to an NSMutableArray (and other containers) would actually increment the NSObject’s retain count. Not knowing this right away, I got into the (bad) habit of double-retaining objects. It took some investigation to find out what was happening, and thanks to Apple’s ingenius profiler and analyzer, I was able to identify the problem. After learning this, I came to find out that, by convention, lots of containers do this, but it’s not too apparent from the documentation.

No Container Static Type Checking?

Apple provides several container classes, including NSArray, NSDictionary, and several others. Much like old versions of Java (like the Java 1.3 stone age), you are free to add instances of any NSObject* child class. As a result, it’s possible to end up with objects of types you did not expect, and the compiler cannot prevent you or even warn you about this.

Sub-Class Insanity

It seems you have to sub-class to do very basic things, like adding items to a UIPickerView. I would have expected a trivial method call to do something like this.

Verbose Names

Stuff like appending one string to anoher is usually pretty trivial and terse in most languages. For example, in C++, you might see this:

myString += "suffix";

But in Cocoa, it looks like this:

myString = [NSString stringByAppendingString:@"suffix"];

That is a seriously verbose method name. If you count, it uses the word “String” 3 times, and that’s not even counting my variable name.

No Static Function Checking

Because Objective-C’s message-passing system is evaluated at runtime, the compiler won’t complain (much) if you try to send a message to an object that does not respond to that message (i.e., like calling a member function in C++ that does not exist). The compiler does warn you, but it will compile, run, and fail with a run-time exception. Some people consider this an advantage of Objective-C, so I can’t hold it against Apple (Smalltalk fans, I’m looking at you).

Bogus Compiler Warnings

If I define a couple messages like this in my class, without putting them in the .h file:

-(void) foo
{
    [self bar];  // compiler warning here
}

-(void) bar
{
}

The compiler will issue a warning, even though this is perfectly safe and will run without exceptions. The compiler is apparently very eager to warn you about this perfectly safe usage, and yet still allows you to send messages that definitely won’t be responded to at run time.

Weird Autorelease Pool Crashes

The first time I misused the autorelease message, I discovered that my application would crash in the event loop processing context. The stack gave no indication where I had gone wrong, because it contained none of my own code. The autorelease pool object itself would crash because it was calling release on an object that had already been freed. The runtime exception was so counter-intuitive that I ended up reverting my code (using git) back to a prior state. I eventually isolated the cause of the problem to my misuse of autorelease, which prompted me to do a more thorough exploration of the feature. Now I recognize those kinds of crashes for what they are, but the first time I encountered it, I was confused for a while before I figured it out.

Managing Multiple Sub-Views

If you have multiple UIPickerView sub-views within your view, managing their contents can be difficult. This is because you have to write a class to implement the UIPickerViewDataSource protocol, which is usually easiest to do right inside your view controller. However, when you add a second or third UIPickerView sub-view to your view, it gets difficult to manage. The UIPickerViewDataSource protocol sends you a pointer to the UIPickerView so you can keep track of which one is which, but it just feels cumbersome. I ended up using this guy’s code to make it easier.

Permissive Compiler Stuff

The Objective-C compiler will allow you to do this:

NSMutableDictionary *myDictionary =
    [[NSDictionary alloc] init];

I would expect it to work the other way around, but not this way. This leads to runtime exceptions when you try to add an element to “myDictionary”, which can be surprising until you realize you have an instance of an immutable NSDictionary. The runtime exception is pretty vague too: All you get is “invalid selector”.

Disappearing Outlets

If you connect an outlet or action in Interface Builder and then later delete the outlet or action object in your Objective-C code, you will get a very cryptic error when you try to instantiate the view:

'NSUnknownException", reason: "[<uiview 0%48a3e0>
setValue:forUndefinedKey:]: this class is not
key value coding-complaint

What it should say is “This xib file is trying to reference item ‘foo’ which does not exist”

Working with UINavigationController

UINavigationController can only have one delegate, even though all it does is notify the delegate when the current view changes. If you want to notify more than one view controller that navigation has moved, then you have to do some juggling to save and restore the UINavigationController’s delegate. It should be easier to notify interested parties when navigation changes.

Good Stuff

Cocoa has a lot of good stuff about it too. Here are some of the highlights from my experience:

Consistent Time Units

Times are always expressed in seconds (and fractions of seconds) instead of having to guess whether it’s seconds, milliseconds, or something else. This is extremely gratifying having come from a world where you pretty much always have to guess (although Google Go’s concept of typing is still far superior).

Analys and Profiling Tools

The X-Code 4 analysis and profiling tools are excellent. I mostly learned how retain/release worked by following the memory leaks that the code analyzer told me about. It even draws little arrows on your code to show you the code path you screwed up. Also, the memory leak finder is fantastic. It shows you when your application leaks, and where each leaked object was originally allocated. This made it trivial to track down and fix my memory leaks.

Easy Animation

Animation is as easy as giving a view a destination size and position, and telling it to go. Animation is integrated into the very core of Cocoa, and it is both easy to use and beautiful on screen.

Conclusion

So there you have it. Cocoa has some pitfalls and some good stuff. That’s all I have to say about it.