<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dave Smith&#039;s Blog</title>
	<atom:link href="http://thesmithfam.org/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://thesmithfam.org/blog</link>
	<description>Your blog is probably better than mine.</description>
	<lastBuildDate>Tue, 22 Jan 2013 20:46:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Communication Between Directives in AngularJS</title>
		<link>http://thesmithfam.org/blog/2012/12/17/communicating-between-directives-in-angularjs/</link>
		<comments>http://thesmithfam.org/blog/2012/12/17/communicating-between-directives-in-angularjs/#comments</comments>
		<pubDate>Tue, 18 Dec 2012 05:11:45 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1249</guid>
		<description><![CDATA[Warning: This article is long and thorough. If you&#8217;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&#8217;t need too much depth, but you need to know what they are: Directive Scope Controller Injecting services into [...]]]></description>
				<content:encoded><![CDATA[<style>
img {
  box-shadow: 0 0 10px #aaa;
  border: 1px solid #999;
  border-radius: 5px;
  padding: 10px !important;
}
tt {
  background: #f4f4ff !important;
  padding: 2px 4px !important;
  border: 1px solid #e6e6ff !important;
  border-radius: 4px !important;
}
.syntaxhighlighter table td.code .container {
  padding: 5px !important;
}
</style>
<p>Warning: This article is long and thorough. If you&#8217;re in a hurry, you can skip straight to the final product here:</p>
<p><a href="http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview">http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview</a></p>
<h2>Prerequisites to this article</h2>
<p>Before reading this, get to know these AngularJS terms. You don&#8217;t need too much depth, but you need to know what they are:</p>
<ul>
<li><a href="http://docs.angularjs.org/guide/directive">Directive</a></li>
<li><a href="http://docs.angularjs.org/guide/scope">Scope</a></li>
<li><a href="http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller">Controller</a></li>
<li><a href="http://docs.angularjs.org/guide/dev_guide.services.injecting_controllers">Injecting services into controllers</a></li>
<li><a href="http://docs.angularjs.org/api/ng.directive:ngShow">ng-show</a> and <a href="http://docs.angularjs.org/api/ng.directive:ngHide">ng-hide</a></li>
<li><a href="http://docs.angularjs.org/api/ng.directive:ngClick">ng-click</a></li>
<li><a href="http://docs.angularjs.org/api/ng.directive:ngModel">ng-model</a></li>
<li><a href="http://docs.angularjs.org/api/ng.directive:ngRepeat">ng-repeat</a></li>
</ul>
<p>You should also peruse the <a href="http://docs.angularjs.org/guide/">Angular Developer Guide</a>, but don&#8217;t feel bad if a lot of the jargon does not make much sense at first.</p>
<h2>Step 0: Roadmap</h2>
<p>We&#8217;re going to create two custom directives that communicate with each other. We&#8217;ll really dig deep into the first directive, explaining every line of code as we go.</p>
<p>Then we&#8217;ll glue the directive to a controller via a scope object.</p>
<p>Lastly, we&#8217;ll create a second directive and glue it all together.</p>
<h2>Step 1: A basic directive, dissected</h2>
<p>For this example, we&#8217;ll create a custom search box that can be placed in our app with a custom <tt>&lt;my-search-box&gt;</tt> element. This directive causes Angular to convert <tt>&lt;my-search-box&gt;</tt> in your HTML into <tt>&lt;span&gt;My Custom Search Box&lt;/span&gt;</tt>. This is not useful yet, but it will become immensely useful as we grow this concept in a few paragraphs.</p>
<p>We&#8217;ll create a file called &#8220;app.js&#8221; with this content:</p>
<pre class="brush: jscript; title: ; notranslate">
angular.module(&quot;MyApp&quot;, []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      replace: true,
      template: '&lt;span&gt;My Custom Search Box&lt;/span&gt;'
    };
  });
</pre>
<p>Let&#8217;s walk through each line of that directive:</p>
<pre class="brush: jscript; title: ; notranslate">
angular.module(&quot;MyApp&quot;, []).
</pre>
<p>This line declares a new module called &#8220;MyApp&#8221;. 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 &#8220;main&#8221; application module, but Angular really doesn&#8217;t know that from this line of code. That happens in the HTML with <tt>&lt;html ng-app="MyApp"&gt;</tt>. 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.</p>
<pre class="brush: jscript; title: ; notranslate">
  directive('mySearchBox', function() {
</pre>
<p>Here we are declaring a new directive. Notice that we camel case the directive name. When Angular encounters <tt>&lt;my-search-box&gt;</tt> in the HTML, it will normalize that into &#8220;mySearchBox&#8221; to look up the directive. Thus, &#8220;mySearchBox&#8221; is called the &#8220;normalized&#8221; name.</p>
<pre class="brush: jscript; title: ; notranslate">
    return {
</pre>
<p>Angular expects the directive function to return an object with properties that describe the directive.</p>
<pre class="brush: jscript; title: ; notranslate">
      restrict: 'E',
</pre>
<p>This tells Angular that &#8220;my-search-box&#8221; must be an <b>element</b>. Angular directives can also exist as HTML attributes, HTML class names, and even HTML comments (!). It&#8217;s okay if this doesn&#8217;t make sense yet.</p>
<pre class="brush: jscript; title: ; notranslate">
      replace: true,
</pre>
<p>This tells Angular to fully replace <tt>&lt;my-search-box&gt;</tt> with the directive&#8217;s template HTML. Alternatively, Angular can <b>add</b> the directive&#8217;s template HTML to the <tt>&lt;my-search-box&gt;</tt> element as a <b>child</b> element. For our example, we want Angular to fully replace <tt>&lt;my-search-box&gt;</tt> because <tt>&lt;my-search-box&gt;</tt> is not a valid HTML element name. You can imagine wanting Angular to simply <b>augment</b> an element with child elements in some scenarios, but not this example. We&#8217;re effectively creating a &#8220;widget&#8221; that can be instantiated and reused in our HTML.</p>
<pre class="brush: jscript; title: ; notranslate">
      template: '&lt;span&gt;My Custom Search Box&lt;/span&gt;'
</pre>
<p>This is the directive&#8217;s HTML template that will be rendered by the browser. I don&#8217;t recommend using hard-coded template strings in your directives like I&#8217;ve done here. I do it this way to make the example clear. Normally, I use the <tt>templateUrl</tt> property and serve the HTML as a &#8220;partial&#8221; 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.</p>
<p>Now we can use this directive in our HTML like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html ng-app=&quot;MyApp&quot;&gt;
  &lt;head&gt;
    &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt; 
      &lt;my-search-box&gt;&lt;/my-search-box&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When you visit that page in your browser, you&#8217;ll see &#8220;My Custom Search Box&#8221; if all went well above.</p>
<p>So far this is a pretty useless directive, but we&#8217;are about to take it to the next level.</p>
<h2>Step 2: Giving your directive its own scope</h2>
<p>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 <tt>&lt;div ng-controller="MyController"&gt;</tt>, then your directive&#8217;s scope will be a child of <tt>MyController</tt>&#8216;s <tt>$scope</tt>.</p>
<p>For example, the following HTML uses two <tt>&lt;my-search-box&gt;</tt> elements. Angular gives each <tt>&lt;my-search-box&gt;</tt> its own independent scope:</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;body&gt; 
      &lt;my-search-box&gt;&lt;/my-search-box&gt;
      &lt;my-search-box&gt;&lt;/my-search-box&gt;
  &lt;/body&gt;
</pre>
<p>Let&#8217;s define our directive&#8217;s interface to the outside world using the <tt>scope</tt> property. Our interface will have two values: <tt>searchText</tt> and <tt>isSearching</tt>. We will use <tt>searchText</tt> to store the user&#8217;s search text that they enter into an <tt>&lt;input&gt;</tt> box, and we&#8217;ll use <tt>isSearching</tt> to tell the directive when a search is in progress.</p>
<pre class="brush: jscript; title: ; notranslate">
angular.module(&quot;MyApp&quot;, []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        searchText: '=',
        isSearching: '='
      },
      template: '&lt;span&gt;My Custom Search Box&lt;/span&gt;'
    };
  });
</pre>
<p>Did you see the <tt>scope = {...}</tt> property above? That defines the public elements of this directive&#8217;s scope. Notice how we used <tt>'='</tt>? That tells Angular that we want a scope variable to have <b>two way binding</b> to the outside world. This is part of the directive&#8217;s HTML interface. This allows callers to use our directive like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;my-search-box
  search-text=&quot;someScopeVariable&quot;
  is-searching=&quot;someOtherScopeVariable&quot;&gt;
&lt;/my-search-box&gt;
</pre>
<p>In other words, the directive allows outside callers to <b>bind</b> their own scope variables to this directive&#8217;s <tt>searchText</tt> and <tt>isSearching</tt> variables. This is how you communicate with the directive from the outside world.</p>
<p>The variables <tt>someScopeVariable</tt> and <tt>someOtherScopeVariable</tt> come from the <b>enclosing</b> scope, which usually is managed by a controller outside the directive. If, for example, we had <tt>&lt;div ng-controller="MyController"&gt;</tt> enclosing <tt>&lt;my-search-box&gt;</tt>, then <tt>someScopeVariable</tt> and <tt>someOtherScopeVariable</tt> would be managed by <tt>MyController</tt>.</p>
<p>In the code above, the <tt>search-text</tt> gets normalized into <tt>searchText</tt> in the directive&#8217;s scope. Likewise, <tt>is-searching</tt> becomes <tt>isSearching</tt>.</p>
<p>When we assign <tt>search-text="someScopeVariable"</tt>, we are telling Angular to bind this directive&#8217;s <tt>searchText</tt> scope variable to a scope variable from the enclosing scope called <tt>someScopeVariable</tt>. Any time the enclosing scope&#8217;s <tt>someScopeVariable</tt> changes, the directive&#8217;s scope variable <tt>searchText</tt> will also change. And it works in the other direction too. Any time the directive changes its <tt>searchText</tt> variable, Angular will automatically change the enclosing scope&#8217;s <tt>someScopeVariable</tt> to match.</p>
<p>These scope variables are useless unless we also make them visible somehow, so let&#8217;s modify our template HTML to use them. While we&#8217;re at it, let&#8217;s make this actually look like a search box instead of a simple piece of text:</p>
<pre class="brush: jscript; title: ; notranslate">
angular.module(&quot;MyApp&quot;, []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      scope: {
        searchText: '=',
        isSearching: '='
      },
      controller: function($scope) {
        $scope.localSearchText = '';
        $scope.clearSearch = function() {
          $scope.searchText = &quot;&quot;;
          $scope.localSearchText = &quot;&quot;;
        };
        $scope.doSearch = function() {
          $scope.searchText = $scope.localSearchText;
        };
      },
      replace: true,
      template:
      '&lt;form&gt;' +
        '&lt;div&gt;' +
          '&lt;input ng-model=&quot;localSearchText&quot; type=&quot;text&quot; /&gt;' +
        '&lt;/div&gt;' +
        '&lt;div&gt;' +
          '&lt;button ng-click=&quot;clearSearch()&quot; class=&quot;btn btn-small&quot;&gt;Clear&lt;/button&gt;' +
          '&lt;button ng-click=&quot;doSearch()&quot;    class=&quot;btn btn-small&quot;&gt;Search&lt;/button&gt;' +
        '&lt;/div&gt; ' +
        '&lt;div ng-show=&quot;isSearching&quot;&gt;' +
          '&lt;img ng-show=&quot;isSearching&quot; src=&quot;http://loadinggif.com/images/image-selection/3.gif&quot; /&gt; ' +
          'Searching...' +
        '&lt;/div&gt;' +
      '&lt;/form&gt;'
    };
  })
</pre>
<p>Remember, I suggest you use <tt>templateUrl</tt> instead of <tt>template</tt> when your HTML starts to grow like this.</p>
<p>Now we have a search box form that lets the user enter some search terms, which we store in the directive&#8217;s scope as <tt>localSearchText</tt>. Notice that we didn&#8217;t put <tt>localSearchText</tt> in the <tt>scope: {&hellip;}</tt> definition, because it needs no external binding. In other words, this is a &#8220;private&#8221; 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&#8217;t want every single keystroke to initiate a search. Only when the user clicks the &#8220;Search&#8221; button.</p>
<p>Notice also that we added a controller with <tt>controller: function($scope) {...}</tt>. This code defines a typical controller so our directive can take action in response to user input, like button clicks with <tt>ng-click</tt>.</p>
<p>This HTML also provides a &#8220;Clear&#8221; 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 <tt>isSearching</tt> variable to a &#8220;truthy&#8221; value.</p>
<p>After making these changes to <tt>app.js</tt>, our page should look like this:</p>
<p><img src="/images/my-search-box-1.png" /></p>
<p>Now that directive is finished. Notice it doesn&#8217;t do much. It requires an outsider to stimulate it into action.</p>
<h2>Step 3: Creating a Controller</h2>
<p>Let&#8217;s create a controller that communicates with the directive we wrote. This isn&#8217;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.</p>
<p>Let&#8217;s make a simulated city search that allows the user to search for cities. Because it&#8217;s an example, the search will always return the same results.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div ng-controller=&quot;CitySearchController&quot;&gt;
  &lt;h1&gt;Search for Cities&lt;/h1&gt; 
  &lt;my-search-box search-text=&quot;citySearchText&quot; is-searching=&quot;isSearchingForCities&quot;&gt;&lt;/my-search-box&gt;
&lt;/div&gt;
</pre>
<p>And the accompanying controller, which I placed in <tt>app.js</tt>:</p>
<pre class="brush: jscript; title: ; notranslate">
function CitySearchController($scope, $timeout) {
  $scope.$watch(&quot;citySearchText&quot;, 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;
    }
  });
}
</pre>
<p>This controller&#8217;s <tt>$scope.citySearchText</tt> and <tt>$scope.isSearchingForCities</tt> variables are <b>bound</b> to the directive&#8217;s scope variables <tt>searchText</tt> and <tt>isSearching</tt> because of the HTML attributes that we specified on <tt>&lt;my-search-box&gt;</tt>.</p>
<p>This controller is pretty basic, so I won&#8217;t describe every line of code. All it does is <tt>$watch()</tt> for changes to <tt>citySearchText</tt> and get some fake search results with Angular&#8217;s <tt>$timeout</tt> service.</p>
<p>Because of Angular&#8217;s excellent isolation-centric design, this controller would be very easy to write unit tests for, but that&#8217;s another article.</p>
<p>When you visit the page, you should now see a search box. If you enter some text into the input box and click &#8220;Search&#8221;, you&#8217;ll see a spinner for 1 second, which then disappears:</p>
<p><img src="/images/my-search-box-2.png" /></p>
<h2>Step 4: Finally add a second directive</h2>
<p>Now we&#8217;re ready to add another directive. For this example, we&#8217;ll create a search <b>results</b> directive. This directive has almost the same public interface (i.e., scope) as the <tt>&lt;my-search-box&gt;</tt> directive, with one extra variable: the actual search results that caller wants to display.</p>
<p>It looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
 directive('mySearchResults', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {
        isSearching: '=',
        searchResults: '=',
        searchText: '='
      },
      replace: true,
      template:
        '&lt;div ng-hide=&quot;isSearching&quot;&gt;' +
          '&lt;h4 ng-show=&quot;searchResults&quot;&gt;Found {{searchResults.length}} Search Results For &quot;{{searchText}}&quot;:&lt;/h4&gt;' +
          '&lt;ul ng-show=&quot;searchResults&quot;&gt;' +
            '&lt;li ng-repeat=&quot;searchResult in searchResults&quot;&gt;' +
              '{{searchResult}}' +
            '&lt;/li&gt;' +
          '&lt;/ul&gt;' +
        '&lt;/div&gt;'
    };
  });
</pre>
<p>Everything should look familiar from your study of the first directive. There are no new concepts here. Let&#8217;s use our directive in our HTML:</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;div ng-controller=&quot;CitySearchController&quot; style=&quot;margin: 20px&quot;&gt;
      &lt;h1&gt;Search for Cities&lt;/h1&gt; 
      &lt;my-search-box search-text=&quot;citySearchText&quot; is-searching=&quot;isSearchingForCities&quot;&gt;&lt;/my-search-box&gt;
      &lt;my-search-results is-searching=&quot;isSearchingForCities&quot; search-results=&quot;citySearchResults&quot; search-text=&quot;citySearchText&quot;&gt;&lt;/my-search-results&gt;
    &lt;/div&gt;
</pre>
<p>Now your page should show some search results after clicking the &#8220;Search&#8221; button and waiting for 1 second:</p>
<p><img src="/images/my-search-box-3.png" /></p>
<p>Just to prove that there is indeed <b>zero coupling</b> 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.</p>
<h2>The Finished Product</h2>
<p>Here it is: <a href="http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview">http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview</a></p>
<h2>Conclusion</h2>
<p>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.</p>
<p>Main points I hope you took from this article:</p>
<ul>
<li>Directives are easy to create.</li>
<li>Directives have their own scope</li>
<li>Directives can communicate with the outside world via HTML attributes</li>
<li>Directives encourage loose coupling</li>
<li>Directives encourage reuse and UI consistency</li>
<li>Directives are easy to test (well, this is a future article)</li>
<li>Controllers can use directives with zero coupling</li>
<li>The Prime Directive has nothing to do with AngularJS (bummer)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/12/17/communicating-between-directives-in-angularjs/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>AngularJS is too humble to say you&#8217;re doing it wrong</title>
		<link>http://thesmithfam.org/blog/2012/12/02/angularjs-is-too-humble-to-say-youre-doing-it-wrong/</link>
		<comments>http://thesmithfam.org/blog/2012/12/02/angularjs-is-too-humble-to-say-youre-doing-it-wrong/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 05:12:29 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1237</guid>
		<description><![CDATA[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&#8217;ve been doing [...]]]></description>
				<content:encoded><![CDATA[<p>For years, web application developers have used DOM manipulation tools like <a href="http://jquery.com/">jQuery</a> to control their user interface. Astute developers have taken it to the next level with client-side templating tools like <a href="http://mustache.github.com/">Mustache</a> and <a href="http://handlebarsjs.com/">Handlebars.js</a> to build sophisticated user interfaces on the client side.</p>
<p>And then <a href="http://angularjs.org/">AngularJS</a> came along.</p>
<p>And we all realized we&#8217;ve been doing it wrong.</p>
<p>Way wrong.</p>
<h2>The Old Way</h2>
<p>Remember before you discovered AngularJS? Back when your code was organized like this:</p>
<ol>
<li>HTML that defines your page</li>
<li>JavaScript that downloads AJAX data</li>
<li>HTML that defines a client side template<br />(yeah, this: <tt>&lt;script type="text/html"&gt;...&lt;/script&gt;</tt>)</li>
<li>JavaScript that renders the client-side template</li>
<li>JavaScript that injects the rendered template HTML into the DOM</li>
</ol>
<p>You thought that was pretty cool. &#8220;Hey look,&#8221; you said, &#8220;I&#8217;ve off-loaded template rendering to the browser!&#8221;. Yeah, you were pretty cool.</p>
<p>But then AngularJS showed you how you were wrong. You could accomplish the same client-side magic with a <strong>lot</strong> less code.</p>
<h2>The New Way</h2>
<p>Under AngularJS, your code can be organized like this:</p>
<ol>
<li>HTML that defines your page and client-side templates inline</li>
<li>JavaScript that downloads AJAX data</li>
</ol>
<p>How does that even work? I mean, you&#8217;ve got like <strong>less than half of the bullet points</strong> now.</p>
<p>The answer: <strong>Data Binding</strong>.</p>
<p>Data Binding is the secret sauce of AngularJS (along with a couple dozen other delicious spices and condiments). Oh, and it&#8217;s not a secret at all. The code is actually <a href="https://github.com/angular/angular.js">pretty easy to read</a>, despite being pure magic awesomeness on environmentally-friendly steroids.</p>
<h2>Shall We Do Show-and-Tell?</h2>
<h3>The old way</h3>
<p>This should be very familiar. You&#8217;ve got an HTML page, and you want to add some dynamic content with a client-side template:</p>
<p>Here&#8217;s the page HTML:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
  &lt;body&gt;
    &lt;div id=&quot;my-list-of-animals&quot;&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Let&#8217;s use Handlebars for the client-side template:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script id=&quot;animal-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  &lt;div&gt;
    &lt;div&gt;{{animalName}}&lt;/div&gt;
    &lt;div&gt;{{favoriteFood}}&lt;/div&gt;
  &lt;/div&gt;
&lt;/script&gt;
</pre>
<p>And you need some JavaScript to download the AJAX data, render the client side template, and inject it into the DOM:</p>
<pre class="brush: jscript; title: ; notranslate">
$.get(&quot;/api/animals/&quot;, function(response) {
  var source = $(&quot;#animal-template&quot;).html();
  var template = Handlebars.compile(source);
  $.each(response, function() {
    var html = template(this);
    $(&quot;#my-list-of-animals&quot;).append(html);
  });
});
</pre>
<p>Put all that together somehow, and wow, that&#8217;s a lot of code to do something that should be very simple.</p>
<p>That covers all 5 bullet points above. You&#8217;re still cool, right?</p>
<h3>The AngularJS Way</h3>
<p>Remember how there are only two bullet points. Well, here they are:</p>
<p>First, your page HTML:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html ng-app&gt;
  &lt;body&gt;
    &lt;div ng-controller=&quot;MyAnimalController&quot;&gt;
      &lt;div ng-repeat=&quot;animal in animals&quot;&gt;
        &lt;div&gt;{{animal.animalName}}&lt;/div&gt;
        &lt;div&gt;{{animal.favoriteFood}}&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Did you see that? There&#8217;s no &lt;script&gt; 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.</p>
<p>Second, the JavaScript:</p>
<pre class="brush: jscript; title: ; notranslate">
function MyAnimalController($scope, $http) {
  $http.get(&quot;/api/animals/&quot;).success(function(response) {
    $scope.animals = response;
  });
}
</pre>
<p>And that&#8217;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&#8217;t take my word for it. Check out the win list below.</p>
<h2>Win List</h2>
<p>Look at all the prizes you won by using AngularJS:</p>
<ol>
<li><b>CSS classes are just for CSS now.</b><br />
You used to abuse the HTML class attribute so you could find elements in the DOM with jQuery. Now, your class attributes are <b>only</b> for CSS. You don&#8217;t have to wonder anymore whether a particular class is used by JavaScript or CSS. The answer is always CSS: The way nature intended</li>
<li><b>No &lt;script&gt; hacks.</b><br />
You don&#8217;t have to trick the browser into ignoring your client-side templates anymore. Don&#8217;t you feel cleaner?</li>
<li><b>Client side templates are cohesive with your page</b><br />
You used to have a pile of client-side template files scattered throughout your project, or all crammed into your HTML &lt;head&gt;. Now they are right in the page, exactly where you wanted to read them in the first place.</li>
<li><b>You don&#8217;t have to name every template</b><br />
You used to name each &lt;script&gt; element with an &#8220;id&#8221; 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.</li>
<li><b>You have control over the scope of your JavaScript</b><br />
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 <b>happened</b> to be an element in the page somewhere with class &#8220;animal&#8221;, and you didn&#8217;t know about it. Then you wrote a jQuery selector like $(&#8220;.animal&#8221;). <b>Boom</b>, you just mofidied an element you didn&#8217;t intend to. With AngularJS, your JavaScript <b>cannot</b> reach outside the ng-controller demarkation.</li>
<li><b>You don&#8217;t have to remember to clean up HTML on refresh</b><br />
Let&#8217;s say I want to refresh the animal list in this example. Under jQuery, I have to remember to do this: <tt>$("#my-list-of-animals").html("")</tt> before I start <tt>.append()</tt>ing new animals. In AngularJS, I just replace <tt>$scope.animals</tt> with the newly downloaded list, and it automatically clears out the old HTML.</li>
<li><b>Your JavaScript is cleaner</b><br />
Your JavaScript has no CSS selectors anymore. It used to be littered with strings to locate elemenents in the DOM. Now it&#8217;s just got business logic. Pure, sweet business logic.</li>
<li><b>You can unit test your JavaScript without a DOM</b><br />
I should have mentioned this <b>first</b>. Notice how my JavaScript has no knowledge of a DOM? It doesn&#8217;t even know there&#8217;s HTML involved at all. This makes it much easier to unit test, because you don&#8217;t need to load a big chunk of fixture HTML to test your JavaScript. AngularJS provides <a href="http://docs.angularjs.org/guide/dev_guide.unit-testing">some great docs on testing</a> too.
</li>
</ol>
<h2>Almost Too Humble</h2>
<p>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:</p>
<p><center><b style="font-size: 120%">I&#8217;ve been doing this all wrong</b></center></p>
<p>At that point, I started to wonder why the AngularJS team didn&#8217;t write article after article with the same title: &#8220;You&#8217;re Doing It Wrong&#8221;. And that&#8217;s what inspired me to write this.</p>
<p>So there you have it. An opinionated blog post about an opinionated framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/12/02/angularjs-is-too-humble-to-say-youre-doing-it-wrong/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Temporarily Suppress Console Output in Python</title>
		<link>http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/</link>
		<comments>http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/#comments</comments>
		<pubDate>Thu, 25 Oct 2012 23:58:45 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1225</guid>
		<description><![CDATA[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&#8217;s library who spams your console. Yeah, that&#8217;s happened to me before (maybe I was the idiot&#8211;I&#8217;m not tellin&#8217;). Here&#8217;s a handy way to suppress [...]]]></description>
				<content:encoded><![CDATA[<p>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&#8217;s library who spams your console. Yeah, that&#8217;s happened to me before (maybe I was the idiot&#8211;I&#8217;m not tellin&#8217;).</p>
<p>Here&#8217;s a handy way to suppress stdout temporarily in your program:</p>
<p>First, slap this code into your project:</p>
<p><script src="https://gist.github.com/3956189.js?file=gistfile1.py"></script></p>
<p>Use it like this:</p>
<p><script src="https://gist.github.com/3956195.js?file=gistfile1.py"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compiler vs. Interpreter</title>
		<link>http://thesmithfam.org/blog/2012/10/18/compiler-vs-interpreter/</link>
		<comments>http://thesmithfam.org/blog/2012/10/18/compiler-vs-interpreter/#comments</comments>
		<pubDate>Thu, 18 Oct 2012 23:40:41 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1223</guid>
		<description><![CDATA[What&#8217;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.]]></description>
				<content:encoded><![CDATA[<p>What&#8217;s the difference between writing a compiler and writing an interpreter?</p>
<p>Easy:</p>
<p>Writing an interpreter is like reading an instruction manual and performing the steps.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/10/18/compiler-vs-interpreter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Throttling Your Network Connection on Mac OS X</title>
		<link>http://thesmithfam.org/blog/2012/04/11/throttling-your-network-connection-on-mac-os-x/</link>
		<comments>http://thesmithfam.org/blog/2012/04/11/throttling-your-network-connection-on-mac-os-x/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 16:26:03 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1206</guid>
		<description><![CDATA[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&#8217;s where ipfw comes in. It does a lot of stuff. I mean a lot, but we&#8217;re just going to use it to slow [...]]]></description>
				<content:encoded><![CDATA[<p>Sometimes you just need to sloooooow doooooooown to test how your software behaves when your internet connection is crappy.</p>
<p>Linux has <a href="http://linux-ip.net/articles/Traffic-Control-HOWTO/">tc</a> to do this, but what about Mac OS X?</p>
<p>That&#8217;s where <a href="http://en.wikipedia.org/wiki/Ipfirewall">ipfw</a> comes in. It does a lot of stuff. I mean a <b>lot</b>, but we&#8217;re just going to use it to slow down our internet connection today.</p>
<p>Here&#8217;s an example that throttles your web browsing experience to 50 KBytes/second:</p>
<pre class="brush: plain; title: ; notranslate">
sudo ipfw pipe 1 config bw 50KByte/s &gt;/dev/null
sudo ipfw add 1 pipe 1 src-port 80
sudo ipfw add 1 pipe 1 dst-port 80
</pre>
<p>And to turn it off (this is an important step!):</p>
<pre class="brush: plain; title: ; notranslate">
sudo ipfw delete 1
</pre>
<p>To make this super easy to use, I wrote a handy little shell script called <b>network-throttle</b>, which you can put in your PATH and run like this:</p>
<pre class="brush: plain; title: ; notranslate">
network-throttle on --port 80 --rate 50KByte/s
</pre>
<p>And to turn it off:</p>
<pre class="brush: plain; title: ; notranslate">
network-throttle off
</pre>
<p>You can download the shell script below. Put it in your PATH and name it <b>network-throttle</b>.</p>
<p>Or, if you like things shiny, pointy, and clicky, you can use the <a href="http://stackoverflow.com/questions/9659382/installing-apples-network-link-conditioner-tool">Apple Network Link Conditioner</a> by installing X-Code.</p>
<p><img src="/images/network-link-conditioner-mac-osx.png" /></p>
<p>Here&#8217;s the magical shell script:</p>
<pre class="brush: plain; title: ; notranslate">
#!/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 &quot;Usage: `basename &quot;$0&quot;` &lt;action&gt; [options]&quot;
    echo &quot;  Action:&quot;
    echo &quot;     on&quot;
    echo &quot;     off&quot;
    echo
    echo &quot;  Options:&quot;
    echo &quot;  --rate &lt;rate&gt;&quot;
    echo &quot;      Example: --rate 100KByte/s&quot;
    echo &quot;  --port &lt;port&gt; (default is 80 if you don't specify --port)&quot;
    echo &quot;      Example: --port 80&quot;
    exit 1
}

function turn_throttling_off()
{
    echo &quot;Turning off network throttling&quot;
    sudo ipfw delete $PIPE_NUMBER || echo &quot;Is it already turned off?&quot;
}

function turn_throttling_on()
{
    echo &quot;Throttling traffic to port $PORT: $RATE&quot;
    sudo ipfw pipe $PIPE_NUMBER config bw $RATE &gt;/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER src-port $PORT &gt;/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER dst-port $PORT &gt;/dev/null
}

# Grab command line args:
while [ -n &quot;$1&quot; ]; do
  case $1 in
    --rate)
      shift
      RATE=$1
      ;;
    --port)
      shift
      PORT=$1
      ;;
    *)
      ACTION=$1
  esac
  shift
done

[ -n &quot;$ACTION&quot; ] || usage &quot;Error: no action specified&quot;

case $ACTION in
  on)
    turn_throttling_off &gt;/dev/null 2&gt;&amp;1 # in case it's already on, clear out the old one
    turn_throttling_on
    ;;
  off)
    turn_throttling_off
    ;;
  *)
    usage &quot;Error: Bad action specified&quot;
    ;;
esac
</pre>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/04/11/throttling-your-network-connection-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dangerous Python Default Arguments</title>
		<link>http://thesmithfam.org/blog/2012/04/01/dangerous-python-default-arguments/</link>
		<comments>http://thesmithfam.org/blog/2012/04/01/dangerous-python-default-arguments/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 02:26:40 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1157</guid>
		<description><![CDATA[Dangerous? Really? Well, not if you understand how it works. Note: I&#8217;m not the first to write about this subject. When writing a function in Python, it&#8217;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 [...]]]></description>
				<content:encoded><![CDATA[<style>
span.intro-crap a {
text-decoration: underline;
}
</style>
<p>Dangerous? Really? Well, not if you understand how it works.</p>
<p><span class="intro-crap">Note: <a href="http://www.deadlybloodyserious.com/2008/05/default-argument-blunders/">I&#8217;m</a> <a href="http://effbot.org/zone/default-values.htm">not</a> <a href="http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html">the</a> <a href="http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">first</a> to write about this subject.</span></p>
<p>When writing a function in Python, it&#8217;s handy to use default argument values like this:</p>

<p>And you <b>think</b> 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 <tt>['some item']</tt>.</p>
<p><b>But you would be wrong.</b></p>
<p>What <b>actually</b> happens is this (interactive shell output):</p>

<p>That&#8217;s right. Python creates a new object, named <tt>some_list</tt> that persists as an attribute of the function. If callers don&#8217;t pass their own <tt>some_list</tt> object, this one, the same one, is used each time your function is called.</p>
<p>Weird, huh?</p>
<p>If users pass their own <tt>some_list</tt> object, then sanity is restored:</p>

<p>So why is this? Python stores each default argument value in a special attribute on the function called <tt>func_defaults</tt>. You can inspect any function&#8217;s default arguments like this:</p>

<p>Because functions in Python are just objects, you can store arbitrary attributes on them. And indeed, you can actually <b>modify</b> the default function arguments at run time, like this:</p>
<script src="https://gist.github.com/2280054.js"></script><noscript><pre><code class="language- ">&gt;&gt;&gt; do_something.func_defaults = ([42],)
&gt;&gt;&gt; do_something()
[42, 'some item']
&gt;&gt;&gt; </code></pre></noscript>
<p><b>But remember</b>: Just because you <b>can</b> doesn&#8217;t mean you <b>should</b>. I would not recommend making a habit of stuff like this, especially if you like <b>not</b> having your co-workers hate you.</p>
<p>It&#8217;s always good to know how your tools work. Inside and out.</p>
<p>I discovered this behavior when investigating the pylint <a href="http://pylint-messages.wikidot.com/messages:w0102">W0102 message</a>, and discovered that this message actually inspired an entire <a href="http://pylint-messages.wikidot.com/">wiki of Pylint message descriptions</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/04/01/dangerous-python-default-arguments/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Code Quality Continuum</title>
		<link>http://thesmithfam.org/blog/2012/03/05/the-code-quality-continuum/</link>
		<comments>http://thesmithfam.org/blog/2012/03/05/the-code-quality-continuum/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 05:27:06 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1155</guid>
		<description><![CDATA[What does it take to write high quality code? Here&#8217;s a little table that I use to judge my own code quality: Future axes to add: Ratio of the initial development cost to the long term maintenance cost Code testability: Code can be manually tested, code can be tested with automation, code can be tested [...]]]></description>
				<content:encoded><![CDATA[<p>What does it take to write high quality code?</p>
<p>Here&#8217;s a little table that I use to judge my own code quality:</p>
<p><a href="/images/code-quality-continuum.png"><img src="/images/code-quality-continuum.png" alt="Code Quality Continuum Chart" style="border: 1px solid gray;" /></a></p>
<p><strong>Future axes to add:</strong></p>
<ol>
<li>Ratio of the initial development cost to the long term maintenance cost</li>
<li>Code testability: Code can be manually tested, code can be tested with automation, code can be tested via continuous integration</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/03/05/the-code-quality-continuum/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>iPhone + Microscope = Awesome</title>
		<link>http://thesmithfam.org/blog/2012/01/03/iphone-microscope-awesome/</link>
		<comments>http://thesmithfam.org/blog/2012/01/03/iphone-microscope-awesome/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 03:09:20 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Miscellany]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1146</guid>
		<description><![CDATA[I was trying to repair my TV, and I wasn&#8217;t happy with the crummy iPhone camera resolution of this chip: So I took the part to work, put it under the microscope, lined up the iPhone camera with the eye piece, and voila! I put my left index finger in the frame for size reference. [...]]]></description>
				<content:encoded><![CDATA[<p>I was trying to repair my TV, and I wasn&#8217;t happy with the crummy iPhone camera resolution of this chip:</p>
<p><img src="/images/tv-mosfet-1.jpg" /></p>
<p>So I took the part to work, put it under the microscope, lined up the iPhone camera with the eye piece, and voila!</p>
<p><img src="/images/tv-mosfet-2.jpg" /></p>
<p>I put my left index finger in the frame for size reference.</p>
<p>Note: in the second photo, the chip has been removed. :)</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/01/03/iphone-microscope-awesome/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Book Review: Treading on Python</title>
		<link>http://thesmithfam.org/blog/2011/12/28/book-review-treading-on-python/</link>
		<comments>http://thesmithfam.org/blog/2011/12/28/book-review-treading-on-python/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 05:48:57 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1129</guid>
		<description><![CDATA[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&#8217;ve spent most of my time in C++, but I&#8217;ve written a handful of small Python scripts (less than 100 lines) and a couple [...]]]></description>
				<content:encoded><![CDATA[<p><em>Treading on Python</em> by Matt Harrison provides a basic introduction to the Python programming language for programming novices.</p>
<p><strong>Background of the reviewer</strong></p>
<p>I have been writing code professionally for 10 years. I&#8217;ve spent most of my time in C++, but I&#8217;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).</p>
<p>In <em>Treading on Python</em>, I was looking to shore up my Python foundation before jumping into my first big Python project.</p>
<p>I was not disappointed.</p>
<p><strong>Who is this book for?</strong></p>
<p>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:</p>
<ol>
<li>Python is used widely in industry</li>
<li>Python is easy to learn</li>
</ol>
<p>This book is written primarily for brand new programmers. It provides practical advice for getting started at the very early stages of programming:</p>
<ul>
<li>How to edit Python code</li>
<li>How to run Python programs</li>
<li>How to use the Python interactive shell</li>
<li>What a variable is (complete with cattle analogy)</li>
<li>How to use strings, integers, and lists</li>
</ul>
<p>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:</p>
<ul>
<li>Python&#8217;s handy <tt>dir</tt> and <tt>help</tt> functions</li>
<li>The <tt>enumerate()</tt> function</li>
<li>The dictinoary <tt>setdefault()</tt> method</li>
<li>Python&#8217;s concept of <tt>None</tt> and object <tt>id</tt></li>
<li>List slicing</li>
<li><tt>import</tt> and <tt>from...import</tt> semantics</li>
<li>And a surprisingly good list of pitfalls to avoid</li>
</ul>
<p>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&#8217;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.</p>
<p><strong>Who is this book not for?</strong></p>
<p>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:</p>
<ul>
<li>List comprehensions</li>
<li>Generators</li>
<li>Lambdas</li>
<li>Threading</li>
<li>Many Python <a href="http://docs.python.org/library/functions.html">built-in functions</a>, like <tt>any()</tt> and <tt>all()</tt></li>
<li>Many handy pieces of the Python standard library, like <a href="http://docs.python.org/dev/library/operator.html"><tt>operator.itemgetter()</tt></a></li>
</ul>
<p>I don&#8217;t offer this list as a criticism of the book. The book&#8217;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.</p>
<p><strong>Opinion of the book</strong></p>
<p>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.</p>
<p>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 &#8220;Pythonic&#8221; 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.</p>
<p>The book reads smoothly and quickly. Matt is very careful to keep his explanations succinct and clear, such that you don&#8217;t feel like you&#8217;re reading a college text book or a reference manual. Even still, the book does contain a high information density.</p>
<p>On my iPad, with the default font size, the book is 243 pages in landscape mode and 147 pages in portrait mode.</p>
<p>I finished the book in fewer than a dozen 15-30 minute sittings.</p>
<p><strong>Conclusion</strong></p>
<p>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&#8217;m not a great judge for this audience.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/12/28/book-review-treading-on-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fun Python Solution to Euler Problem 79</title>
		<link>http://thesmithfam.org/blog/2011/12/27/fun-python-solution-to-euler-problem-79/</link>
		<comments>http://thesmithfam.org/blog/2011/12/27/fun-python-solution-to-euler-problem-79/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 05:22:41 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1107</guid>
		<description><![CDATA[Nothing says Merry Christmas like Project Euler. Here&#8217;s a nifty solution to Problem 79 that uses Python and Graphviz. The problem is to identify a user&#8217;s password given a bunch of successful logins (taken from some kind of nefarious keylogger&#8211;those crafty devils). The çatch is that each login is actually a subset of the actual [...]]]></description>
				<content:encoded><![CDATA[<p>Nothing says Merry Christmas like Project Euler.</p>
<p>Here&#8217;s a nifty solution to <a href="http://projecteuler.net/problem=79">Problem 79</a> that uses Python and Graphviz.</p>
<p>The problem is to identify a user&#8217;s password given a bunch of successful logins (taken from some kind of nefarious keylogger&#8211;those crafty devils). The çatch is that each login is actually a <b>subset</b> of the actual password. Of course, they give you <a href="http://projecteuler.net/project/keylog.txt">a sample of 50 successful logins</a>.</p>
<p>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 <a href="http://www.graphviz.org/Gallery.php">Dot file</a> which we turn into an image using the &#8220;dot&#8221; command. I ran this on Mac OS X, but it should work just fine on any Linux box (hint: install the &#8220;graphviz&#8221; package).</p>
<p>Here&#8217;s the Python code:</p>
<p><b>problem79.py:</b></p>
<pre class="brush: python; title: ; notranslate">
digit_precendence = dict()

for line in [line.strip() for line in open(&quot;./keylog.txt&quot;)]:
    for index, char in enumerate(line):
        digits = digit_precendence.setdefault(int(char), set())
        if index &lt; len(line)-1:
            digits.add(int(line[index+1]))

print &quot;digraph problem79 {&quot;
for (digit, subsequent_digits) in digit_precendence.iteritems():
    for subsequent_digit in subsequent_digits:
        print &quot;   %d -&gt; %d;&quot; % (digit, subsequent_digit)
print &quot;}&quot;
</pre>
<p>Save that as <b>problem79.py</b>, download <b>keylog.txt</b> into the same folder, and run the program like this:</p>
<pre class="brush: bash; title: ; notranslate">python problem79.py | dot -Tpng &gt; problem79.png</pre>
<p>Then view <b>problem79.png</b>, and voila! Graphviz just put the answer right in front of your nose: <b>73162890</b>.</p>
<p><img src="/images/problem79.png" /></p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/12/27/fun-python-solution-to-euler-problem-79/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
