<?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>eriksmartt.com/blog &#187; code</title>
	<atom:link href="http://www.eriksmartt.com/blog/archives/tag/code/feed" rel="self" type="application/rss+xml" />
	<link>http://www.eriksmartt.com/blog</link>
	<description>my little chunk of bandwidth</description>
	<lastBuildDate>Thu, 30 Jun 2011 15:17:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-alpha-19854</generator>
		<item>
		<title>&#8220;Fun example of programming language sc&#8230;</title>
		<link>http://www.eriksmartt.com/blog/archives/1380</link>
		<comments>http://www.eriksmartt.com/blog/archives/1380#comments</comments>
		<pubDate>Wed, 11 Aug 2010 03:55:40 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=1380</guid>
		<description><![CDATA[&#8220;Fun example of programming language scope&#8221; is only &#8220;fun&#8221; for a certain type of geek; But I like programming examples that help explain how your code is interpreted, particularly if the lesson can help prevent a certain class of bug. Now that you&#8217;re expecting a scope puzzle, what will the following JavaScript print? (Ignoring the [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Fun example of programming language scope&#8221; is only &#8220;fun&#8221; for a certain type of geek; But I like programming examples that help explain how your code is interpreted, particularly if the lesson can help prevent a certain class of bug.</p>
<p>Now that you&#8217;re expecting a scope puzzle, what will the following JavaScript print? (Ignoring the line numbers, of course, which are here to aid in discussion.)</p>
<pre><code>
 1:  var foo = 1;
 2:
 3:  function bar1() {
 4:   print("A: " + foo );
 5:  }
 6:
 7:  function bar2() {
 8:   print("B: " + foo );
 9:   var foo = 2;
10:   print("C: " + foo );
11:  }
12:
13:  function bar3() {
14:    print("D: " + foo );
15:    eval("var foo = 2;")
16:    print("E: " + foo );
17:  }
18:
19:  bar1();
20:  bar2();
21:  bar3();
</code></pre>
<p>&nbsp;<br />&nbsp;</p>
<p>No peeking&#8230;</p>
<p>&nbsp;<br />&nbsp;</p>
<hr />
Answer</p>
<hr />
<pre>
A: 1
B: undefined
C: 2
D: 1
E: 2
</pre>
<p>&nbsp;</p>
<p>&#8220;A&#8221; is easy.  Since <code>foo</code> is a &#8220;free variable&#8221; (i.e., not defined within function <code>bar1</code>), the interpreter goes up the scope chain, and finds the global <code>foo</code>, defined on line 1.</p>
<p>For <code>bar2</code>, &#8220;C: 2&#8243; is obvious &#8212; it&#8217;s &#8220;B: undefined&#8221; that lets you in on the magic under the hood. You sort of expect to see &#8220;B: 1&#8243; (or a compiler error.) However, JavaScript interpreters scan-ahead, searching for variable definitions (e.g., <code>var</code> statements) when parsing a code block.  The interpreter sees/re-writes <code>bar2</code> like this:</p>
<pre><code>
 1:  function bar2() {
 2:    var foo;
 3:    print("B: " + foo );
 4:    foo = 2;
 5:    print("C: " + foo );
 6:  }
</code></pre>
<p>With that definition, &#8220;B: undefined&#8221; makes perfect sense.</p>
<p>To short-circuit the magic, <code>bar3</code> uses <code>eval()</code> to do it&#8217;s trickery.  At line 14, <code>foo</code> still points to the global <code>foo</code>, much like in <code>bar1</code>; However, the <code>eval</code> statement on line 15 modifies the local scope, introducing a new, local <code>foo</code>.  By line 16, &#8220;E: 2&#8243; is using the newly introduced <code>foo</code>.</p>
<p>&nbsp;</p>
<p><b>The lesson:</b> Even though JavaScript allows you to declare variables at any point within a block, putting your <code>var</code> statements at the beginning of the block can help eliminate scope confusion around whether an inner- or outer-closure contains the correct value.</p>
<p>&nbsp;<br />&nbsp;</p>
<hr />
<b>Bonus Question</b></p>
<p>Is JavaScript&#8217;s <code>var</code> a <code>let</code> or <code>let*</code>?  It&#8217;s easy to find out using the following:</p>
<pre><code>
 1:  var x = 2, y = 3, z = x + y;
 2:  print(z);
</code></pre>
<p>Is this legal?  Will it print &#8217;5&#8242;?</p>
<hr />
[Update: 2010/09/21: If you liked this, you'll also enjoy "<a href="http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting">JavaScript Scoping and Hoisting</a>".]</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/1380/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jsmacro 0.2.3</title>
		<link>http://www.eriksmartt.com/blog/archives/1274</link>
		<comments>http://www.eriksmartt.com/blog/archives/1274#comments</comments>
		<pubDate>Sat, 20 Feb 2010 02:02:29 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jsmacro]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=1274</guid>
		<description><![CDATA[The latest jsmacro (v0.2.3) adds support for &#8220;else&#8221; clauses to &#8220;if&#8221;, &#8220;ifdef&#8221;, and &#8220;ifndef&#8221; statements. Combine this with the command-line variable definition support and you can now do fun things like this: //@ifdef IE6_BUILD ...custom IE6 code here //@else ...code for other browsers here //@end Of course, this goes against the idea that your JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p>The latest <a href="http://github.com/smartt/jsmacro">jsmacro</a> (v0.2.3) adds support for &#8220;else&#8221; clauses to &#8220;if&#8221;, &#8220;ifdef&#8221;, and &#8220;ifndef&#8221; statements.  Combine this with the command-line variable definition support and you can now do fun things like this:</p>
<pre><code>
//@ifdef IE6_BUILD
 ...custom IE6 code here
//@else
 ...code for other browsers here
//@end
</code></pre>
<p>Of course, this goes against the idea that your JavaScript would remain usable for development without needing to be processed, but it&#8217;s just an example.  Longer term, I hope to have a different approach available that will allow conditional code substitution so that browser specific optimizations won&#8217;t get in the way of an easy development/test/debug process.</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/1274/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jsmacro 0.2.2</title>
		<link>http://www.eriksmartt.com/blog/archives/1262</link>
		<comments>http://www.eriksmartt.com/blog/archives/1262#comments</comments>
		<pubDate>Thu, 04 Feb 2010 15:48:20 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jsmacro]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=1262</guid>
		<description><![CDATA[jsmacro 0.2 was a full rewrite (because version 0.2&#8242;s are always a full rewrite.) It&#8217;s now a little closer to what I was originally thinking. Instead of a line-by-line state machine, the parser now uses regex, and dynamically calls macro-handling methods based on the name of the macro. That&#8217;s a little vague, but in practice [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://github.com/smartt/jsmacro">jsmacro</a> 0.2 was a full rewrite (because version 0.2&#8242;s are always a full rewrite.)  It&#8217;s now a little closer to what I was originally thinking.  Instead of a line-by-line state machine, the parser now uses regex, and dynamically calls macro-handling methods based on the name of the macro.  That&#8217;s a little vague, but in practice it means that extending the macro language is easier, and it may be possible to do it on-the-fly (as in, writing new macro implementations within the JavaScript source file that&#8217;s being parsed &#8212; which is a geeky goal I&#8217;m going for.)</p>
<p>Other new additions:</p>
<ul>
<li>Test files are now picked-up automatically when named correctly.  This makes it painless to add more tests.</li>
<li>Added support for setting DEFINE flags from the command-line.  Handy if you automate builds for different environments (like IE6 vs. the rest of the world.)</li>
<li>Added support for #ifdef and #ifndef</li>
</ul>
<p>The next big hurdles will be how to handle <code>else</code> statements, and coming up with a reason to implement some type of #inline capability.</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/1262/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jsmacro &#8212; an oddly named JavaScript preprocessor</title>
		<link>http://www.eriksmartt.com/blog/archives/1254</link>
		<comments>http://www.eriksmartt.com/blog/archives/1254#comments</comments>
		<pubDate>Tue, 26 Jan 2010 01:38:55 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jsmacro]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=1254</guid>
		<description><![CDATA[For awhile now I&#8217;ve wanted a JavaScript preprocessor to conditionally include debug and testing code when needed. It&#8217;s always registered as merely a &#8220;nice to have&#8221;, so I hadn&#8217;t sought one out. However, I had a little time over the weekend and wanted to play with the idea, so here it is: jsmacro (on GitHub.) [...]]]></description>
			<content:encoded><![CDATA[<p>For awhile now I&#8217;ve wanted a JavaScript preprocessor to conditionally include debug and testing code when needed.  It&#8217;s always registered as merely a &#8220;nice to have&#8221;, so I hadn&#8217;t sought one out.  However, I had a little time over the weekend and wanted to play with the idea, so here it is: <a href="http://github.com/smartt/jsmacro">jsmacro</a> (on GitHub.)</p>
<p>[Note that before writing this I did seek out existing implementations, and found <a href="http://www.bramstein.com/projects/preprocess/">js-preprocess</a> to be the most interesting; However, I needed something that would work as part of an existing build chain, so authoring the tool in Python instead of JavaScript made more sense.]</p>
<p>Currently, jsmacro is poorly named, as I didn&#8217;t write the macro system that was in my head.  Instead, it&#8217;s currently a basic preprocessor supporting only DEFINE and IF statements, which happened to be all I needed at the time.  Usage works like this:</p>
<h3>Input JavaScript</h3>
<pre><code>
  //@define DEBUG 0

  var foo = function() {
    //@if DEBUG
    alert('This.');
    alert('That.');
    //@end

    print "Hi";
  };
</code></pre>
<p>Pass the above JavaScript through jsmacro from the command line like this: <code>./jsmacro.py -f infile.js &gt; outfile.js</code> (assuming the files are all in the same directory), and you get the following:</p>
<h3>Output JavaScript</h3>
<pre><code>
  var foo = function() {

    print "Hi";
  };
</code></pre>
<p>The tool has registered the variable &#8216;DEBUG&#8217;as 0 (i.e., false), so the conditional include statements omit the alert() calls.  If DEBUG had been set to 1 (i.e., true), the alert() statements would remain (though all jsmacro instructions would be removed either way.)</p>
<p>One of the tricky things about doing macros or preprocessing in JavaScript is that I wanted the code to be valid JavaScript before the tool is run (which is why C-preprocessors won&#8217;t work.)  The idea is that you develop as you normally would, but wrap your debug and testing code in conditional jsmacro statements so that they are automatically removed as part of your build process.</p>
<p>There&#8217;s nothing fancy about the current implementation (it&#8217;s a crude state machine that scans line-by-line, top-to-bottom looking for regex patterns and deciding whether to output the line of not.)  Crude as it may be though, it completely solved a problem for me, and hopefully it will help you out as well.</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/1254/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Detecting whether your code is running on App Engine servers, or in development</title>
		<link>http://www.eriksmartt.com/blog/archives/904</link>
		<comments>http://www.eriksmartt.com/blog/archives/904#comments</comments>
		<pubDate>Mon, 25 May 2009 18:06:56 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[appengine]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=904</guid>
		<description><![CDATA[For one of my projects running on Google App Engine, I&#8217;m using Google Analytics to track traffic, but I didn&#8217;t want the tracking code showing up in my local development environment. Fortunately, detecting where your code is running is easy. Take a look at this sample: import os try: is_dev = os.environ['SERVER_SOFTWARE'].startswith('Dev') except: is_dev = [...]]]></description>
			<content:encoded><![CDATA[<p>For one of my projects running on Google App Engine, I&#8217;m using Google Analytics to track traffic, but I didn&#8217;t want the tracking code showing up in my local development environment.  Fortunately, detecting where your code is running is easy.</p>
<p>Take a look at this sample:</p>
<pre><code>
import os

try:
  is_dev = os.environ['SERVER_SOFTWARE'].startswith('Dev')
except:
  is_dev = False

is_prod = not(is_dev)
</code></pre>
<p>If the <code>is_dev</code> and <code>is_prod</code> variables are exposed to your templates, you can do something like this:</p>
<pre><code>
{% if is_prod %}
 {% include "analytics.html" %}
{% endif %}
</code></pre>
<p>Hope this helps!</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/904/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How-To: Dynamic WWW-Authentication (.htaccess style) on Google App Engine</title>
		<link>http://www.eriksmartt.com/blog/archives/882</link>
		<comments>http://www.eriksmartt.com/blog/archives/882#comments</comments>
		<pubDate>Sat, 16 May 2009 23:15:13 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[appengine]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=882</guid>
		<description><![CDATA[Sometimes classic Basic Access Authentication is the right approach to password protecting a webpage. It&#8217;s not secure from sniffing, but functional if you&#8217;re just trying to ward off the casual surfer in the wrong spot. (For example, restricting access to your cat pictures, not your missile silo codes.) Basic authentication is often added to sites [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes classic <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic Access Authentication</a> is the right approach to password protecting a webpage.  It&#8217;s not secure from sniffing, but functional if you&#8217;re just trying to ward off the casual surfer in the wrong spot.  (For example, restricting access to your cat pictures, not your missile silo codes.)</p>
<p>Basic authentication is often added to sites (or directories) using a .htaccess file and something like this:</p>
<p><code>
<pre>
AuthUserFile /home/foo/.htpasswd
AuthName "Private Area"
AuthType Basic

&lt;Limit GET&gt;
require valid-user
&lt;/Limit&gt;
</pre>
<p></code></p>
<p>&#8230;but you can also do basic authentication on-the-fly by reading/writing HTTP Headers.  To ask the browser for a user/password, you can raise a 401 error, and write a &#8220;www-Authenticate&#8221; header containing something like &#8216;Basic realm=&#8221;Secure Area&#8221;&#8216;.  To read the user/password, look for an Authorization header, grab it&#8217;s value, Base 64 decode it, and you should have a string in the form of &#8220;user:password&#8221;.</p>
<p>Here&#8217;s how you might handle it with Google App Engine.  (Well, really you might use a decorator.. but this example is easier to explain.)</p>
<p><code>
<pre>
class AuthTest(webapp.RequestHandler):
  def get(self):

    # Wrapping in a huge try/except isn't the best approach. This is just
    # an example for how you might do this.
    try:
      # Parse the header to extract a user/password combo.
      # We're expecting something like "Basic XZxgZRTpbjpvcGVuIHYlc4FkZQ=="
      auth_header = self.request.headers['Authorization']

      # Isolate the encoded user/passwd and decode it
      auth_parts = auth_header.split(' ')
      user_pass_parts = base64.b64decode(auth_parts[1]).split(':')
      user_arg = user_pass_parts[0]
      pass_arg = user_pass_parts[1]

      checkAuth(user_arg, pass_arg) # have this call raise an exception if it fails

      self.response.out.write(template.render('templates/foo.html', {}))

    except Exception, e:
      logging.debug("AuthTest Exception: %s" % (e))

      # Here's how you set the headers requesting the browser to prompt
      # for a user/password:
      self.response.set_status(401, message="Authorization Required")
      self.response.headers['WWW-Authenticate'] = 'Basic realm="Secure Area"'

      # Rendering a 401 Error page is a good way to go...
      self.response.out.write(template.render('templates/error/401.html', {}))
</pre>
<p></code></p>
<p>That&#8217;s all there is to it.</p>
<p>If you want to programatically write an Authorization header (as in, sending authentication credentials to another site, like the Twitter API&#8217;s, for example) you&#8217;ll do something like this:</p>
<p><code>
<pre>
request = urllib2.Request(url)
request.add_header('Authorization', "Basic %s" % (base64.b64encode("%s:%s" % (user, password))))
</pre>
<p></code></p>
<p>Enjoy!</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/882/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Conway&#8217;s Game of Life in Nodebox</title>
		<link>http://www.eriksmartt.com/blog/archives/771</link>
		<comments>http://www.eriksmartt.com/blog/archives/771#comments</comments>
		<pubDate>Wed, 25 Feb 2009 17:31:05 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[art]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=771</guid>
		<description><![CDATA[I was reading Ben Fry&#8216;s thesis, Organic Information Design yesterday, came across the section on Conway&#8217;s Game of Life, and thought it would make a nice NodeBox demo. Here it is: conway-life.py There&#8217;s not much to it, but it does show a software pattern I&#8217;ve been using frequently with NodeBox. Many of the NodeBox examples [...]]]></description>
			<content:encoded><![CDATA[<p>I was reading <a href="http://benfry.com/">Ben Fry</a>&#8216;s thesis, <a href="http://benfry.com/organic/">Organic Information Design</a> yesterday, came across the section on <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway&#8217;s Game of Life</a>, and thought it would make a nice <a href="http://nodebox.net/">NodeBox</a> demo.</p>
<p>Here it is: <a href="http://www.eriksmartt.com/blog/wp-content/uploads/2009/02/conway-life.py">conway-life.py</a></p>
<p><img src="http://www.eriksmartt.com/blog/wp-content/uploads/2009/02/conway-in-nodebox.jpg" width="500"  alt="Nodebox screenshot" /><br />
<br clear="all" /></p>
<p>There&#8217;s not much to it, but it does show a software pattern I&#8217;ve been using frequently with NodeBox.  Many of the NodeBox examples make heavy use of non-namespaced, global variables.  I suppose it makes simple code easy to read for those new to programming, but it&#8217;s a habit you&#8217;ll want to break before your code starts getting more complex.</p>
<p>What I&#8217;ve found helpful is to create a World/Universe/Controller/Stage object that drives the rendering.  Instead of using multiple globals in <code>draw()</code>, the controller object keeps the main parameters as local properties, and instantiates any needed objects in it&#8217;s <code>__init__()</code>.  This approach prevents global variables names from clashing, and allows for creative reuse of rendering components.</p>
<p>Enjoy!</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/771/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using pymunk (physics engine) in NodeBox</title>
		<link>http://www.eriksmartt.com/blog/archives/747</link>
		<comments>http://www.eriksmartt.com/blog/archives/747#comments</comments>
		<pubDate>Mon, 23 Feb 2009 16:32:37 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=747</guid>
		<description><![CDATA[NodeBox makes a great environment for data visualizations and generative art. It&#8217;s easy to get started in, and you get basic drawing, type, and image manipulation. When you&#8217;re ready for more, it&#8217;s not too difficult to bring in external Python libraries to connect NodeBox to other systems, or add physics and particle simulation to spice [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nodebox.net/">NodeBox</a> makes a great environment for data visualizations and generative art.  It&#8217;s easy to get started in, and you get basic drawing, type, and image manipulation.  When you&#8217;re ready for more, it&#8217;s not too difficult to bring in external Python libraries to connect NodeBox to other systems, or add physics and particle simulation to spice up your visuals.</p>
<p>For those unfamiliar with NodeBox,</p>
<blockquote><p>&#8220;NodeBox is a Mac OS X application that lets you create 2D visuals (static, animated or interactive) using Python programming code and export them as a PDF or a QuickTime movie.&#8221;</p></blockquote>
<p>It uses <a href="http://pyobjc.sourceforge.net/">PyObjC</a> to embed a <a href="http://python.org/">Python</a> runtime into an OS X native application, and fits into the same toolbox as <a href="http://processing.org/">Processing</a> and <a href="http://openframeworks.cc/">openFrameworks</a>.  It&#8217;s a bit slower to run complex animations in, but you&#8217;re coding in Python, you get the gorgeous fonts and anti-aliasing you&#8217;d expect on OS X, and it provides easy access to some OS X native libraries, like Core Image.  For a quick look at what it can do, check out the <a href="http://nodebox.net/code/index.php/Gallery">NodeBox gallery</a>.</p>
<p>NodeBox includes it&#8217;s own Python build, which is nice for portability and reliability, but it uses a custom <code>sys.path</code> that doesn&#8217;t look for Python packages you might already have installed on your system.  There are a few ways to deal with this:</p>
<ol>
<li>You can install your packages into NodeBox&#8217;s path, ie., <code>~/Library/Application\ Support/NodeBox/</code> &#8212; meaning that you can use them from NodeBox, but not from other scripts&#8230;</li>
<li>You can <code>import sys</code> in your NodeBox code and manually modify the <code>sys.path</code> value to add your existing packages&#8230;</li>
<li>You can install packages into your system site-packages directory, and sym-link them from NodeBox&#8217;s directory&#8230;</li>
<li>You can make NodeBox use your system packages instead of it&#8217;s own by sym-linking <code>~/Library/Application\ Support/NodeBox</code> to your site-packages directory of choice (ex., <code>/Library/Python/2.5/site-packages</code>)</li>
</ol>
<p>For this exercise, I&#8217;ll be adding <a href="http://code.google.com/p/pymunk/">pymunk</a> (Python bindings for the <a href="http://wiki.slembcke.net/main/published/Chipmunk">Chipmonk</a> physics library) to NodeBox using option #3: Installing pymunk globally, and sym-linking from NodeBox&#8217;s package directory.  This allows me to run the pymunk examples from the command-line (which use PyGame and Pyglet), but still use pymunk from NodeBox.  This may not always be the best solution, so you&#8217;ll have to pick what&#8217;s right for your needs.</p>
<p>Let&#8217;s get started.</p>
<p>Pymunk (at the time of writing) includes it&#8217;s own copy of the Chipmunk source code, making this whole process rather easy.  Once you&#8217;ve downloaded and uncompressed the pymunk source, <code>cd</code> into it&#8217;s directory and build chipmunk using:</p>
<p><code>&gt; python setup.py build_chipmunk</code></p>
<p>Now you can build and install pymunk:</p>
<p><code>&gt; python setup.py install</code></p>
<p>This will install an egg (which I normally hate dealing with, but that&#8217;s another story.)  If you don&#8217;t want the egg, just copy the <code>pymunk</code> directory into your site-packages.</p>
<p>Now we&#8217;ll add pymunk to NodeBox&#8217;s path.  My pymunk is in <code>/Library/Python/2.5/site-packages/</code>, so I&#8217;ll:</p>
<p><code>&gt; cd ~/Library/Application\ Support/NodeBox</code></p>
<p><code>&gt; ln -s /Library/Python/2.5/site-packages/pymunk-0.8.1-py2.5.egg/pymunk .</code></p>
<p>Finally, NodeBox needs access to libchipmunk.  I used this approach:</p>
<p><code>&gt; cd /Applications/NodeBox/NodeBox.app/Contents/MacOS/</code></p>
<p><code>&gt; ln -s ~/Library/Application\ Support/NodeBox/pymunk/libchipmunk.dylib .</code></p>
<p>We should be done!  Fire up NodeBox and try an <code>include pymunk</code> to see if it loads.  If you don&#8217;t see any error messages, you&#8217;re good to go.</p>
<p>If you&#8217;re new to pymunk (as I was until this week), head over to the <a href="http://code.google.com/p/pymunk/wiki/SlideAndPinJointsExample">Slide and Pin Joint tutorial</a> to see how it works.  The example is written for <a href="http://pygame.org/">PyGame</a>, so you&#8217;ll be doing a little rewriting to bring it into NodeBox.</p>
<p>The following screenshot shows the Slide and Pin Joint demo within NodeBox using my take on porting it.  I&#8217;m having a little trouble with the slide joint, but you can check out my code if you&#8217;re curious: <a href="http://www.eriksmartt.com/blog/wp-content/uploads/2009/02/slide_and_pinjoint_example.py">slide_and_pinjoint_example.py</a></p>
<p><img src="http://www.eriksmartt.com/blog/wp-content/uploads/2009/02/pymunk_in_nodebox.jpg" width="550"  border="0" alt="pymunk in nodebox screenshot" /><br />
<br clear="all" /></p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/747/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Ubiquity command to expand hyperlinks</title>
		<link>http://www.eriksmartt.com/blog/archives/588</link>
		<comments>http://www.eriksmartt.com/blog/archives/588#comments</comments>
		<pubDate>Tue, 07 Oct 2008 15:58:51 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=588</guid>
		<description><![CDATA[Another simple Ubiquity command for the morning&#8230; This one, called &#8216;expandlinks&#8217;, finds all links on the current page and adds the link&#8217;s URL (as a hyperlink itself) next to each existing link label. This is particularly handy if you&#8217;re going to print an HTML page for later reference. CmdUtils.CreateCommand({ name: "expandlinks", homepage: "http://eriksmartt.com/blog/", author: { [...]]]></description>
			<content:encoded><![CDATA[<p>Another simple <a href="https://wiki.mozilla.org/Labs/Ubiquity">Ubiquity</a> command for the morning&#8230; This one, called &#8216;expandlinks&#8217;, finds all links on the current page and adds the link&#8217;s URL (as a hyperlink itself) next to each existing link label.  This is particularly handy if you&#8217;re going to print an HTML page for later reference.</p>
<pre><code>
CmdUtils.CreateCommand({
  name: "expandlinks",
  homepage: "http://eriksmartt.com/blog/",
  author: { name: "Erik Smartt"},
  license: "MPL",
  preview: "Expands all hyperlinks, showing link locations.",
  execute: function() {
    var doc =  Application.activeWindow.activeTab.document;
    jQuery(doc.body).find("a").each(function(i) {
        jQuery(this).after(" &amp;lt;&lt;a href='" + this.href + "'&gt;" + this.href + "&lt;/a&gt;&amp;gt;");
    });
  }
})
</code></pre>
<p>And yes, it will be much easier to subscribe to these commands once I gather them into a JS file for Ubiquity.  For now, you can copy/paste into the command editor if you&#8217;re interested in trying it out.</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/588/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Even simpler then my last Ubiquity examp&#8230;</title>
		<link>http://www.eriksmartt.com/blog/archives/547</link>
		<comments>http://www.eriksmartt.com/blog/archives/547#comments</comments>
		<pubDate>Wed, 27 Aug 2008 20:21:39 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=547</guid>
		<description><![CDATA[Even simpler then my last Ubiquity example, this one came about from an actual project need to verify a custom character-length based text truncation filter. Select the text in the browser, invoke Ubiquity, and type: charcount CmdUtils.CreateCommand({ name: "charcount", takes: {"text to count chars in": noun_arb_text}, preview: function( pblock, argText ) { pblock.innerHTML = argText.text.length; [...]]]></description>
			<content:encoded><![CDATA[<p>Even simpler then my last <a href="https://wiki.mozilla.org/Labs/Ubiquity">Ubiquity</a> example, this one came about from an actual project need to verify a custom character-length based text truncation filter.  Select the text in the browser, invoke Ubiquity, and type: charcount</p>
<p><code>
<pre>
CmdUtils.CreateCommand({
  name: "charcount",
  takes: {"text to count chars in": noun_arb_text},
  preview: function( pblock, argText ) {
    pblock.innerHTML = argText.text.length;
  }
})
</pre>
<p></code></p>
<p><b>Update</b>: See comments below for Ubiquity 0.5 compatibility updates</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/547/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Extending Mozilla Ubiquity &#8212; stock charts and Google Finance lookup</title>
		<link>http://www.eriksmartt.com/blog/archives/543</link>
		<comments>http://www.eriksmartt.com/blog/archives/543#comments</comments>
		<pubDate>Wed, 27 Aug 2008 20:08:24 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/?p=543</guid>
		<description><![CDATA[Mozilla Ubiquity was released this week, and the functionality was so inspiring that I couldn&#8217;t help playing with it. For those that haven&#8217;t checked it out yet, think &#8220;Quicksilver inside Firefox&#8221;&#8230; or perhaps, &#8220;a contextually-aware command-line for your web browser.&#8221; If that still doesn&#8217;t mean anything to you&#8230; well, you&#8217;ll have to watch the intro [...]]]></description>
			<content:encoded><![CDATA[<p><a href="https://wiki.mozilla.org/Labs/Ubiquity">Mozilla Ubiquity</a> was released this week, and the functionality was so inspiring that I couldn&#8217;t help playing with it.  For those that haven&#8217;t checked it out yet, think &#8220;Quicksilver inside Firefox&#8221;&#8230; or perhaps, &#8220;a contextually-aware command-line for your web browser.&#8221;  If that still doesn&#8217;t mean anything to you&#8230; well, you&#8217;ll have to <a href="http://labs.mozilla.com/2008/08/introducing-ubiquity/">watch the intro video</a> ;-)</p>
<p>Extending Ubiquity&#8217;s vocabulary is done via JavaScript, and <a href="https://wiki.mozilla.org/Labs/Ubiquity/Ubiquity_0.1_Author_Tutorial">the developer docs</a> are pretty straight forward.</p>
<p>The docs cover Hello World, so I figured that the next best intro test would be a way to lookup stock charts and quotes.  Here&#8217;s the result of a few minutes hacking on it:</p>
<p><code>
<pre>
CmdUtils.CreateCommand({
  name: "tik",
  takes: {"stock ticker symbol": noun_arb_text},
  preview: function( pblock, argText ) {
    var charturl = "http://chart.finance.yahoo.com/c/1y/a/" + argText.text;
    pblock.innerHTML = "<img src='" + charturl + "' />";
  },
  execute: function( argText ) {
    var windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                      .getService(Components.interfaces.nsIWindowMediator);
    var browserWindow = windowManager.getMostRecentWindow("navigator:browser");
    var browser = browserWindow.getBrowser();
    var url = "http://finance.google.com/finance?q=" + argText.text;
    browser.loadOneTab(url, null, null, null, false, false);
  }
})
</pre>
<p></code></p>
<p>This command introduces a &#8216;tik&#8217;keyword, which loads 1-year stock symbol charts (from Yahoo) into the preview pane, and allows click-through to open a new tab for the Google Finance page of said symbol.  Note that the preview-pane doesn&#8217;t always resize correctly for the chart to fit (though you can generally make it happen by typing a space after the stock symbol.)  I guess there&#8217;s still some work to do there.</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/543/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A simple shell script for grabbing the current temperature from the command line</title>
		<link>http://www.eriksmartt.com/blog/archives/405</link>
		<comments>http://www.eriksmartt.com/blog/archives/405#comments</comments>
		<pubDate>Fri, 16 Nov 2007 18:21:42 +0000</pubDate>
		<dc:creator>erik</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[lifehack]]></category>

		<guid isPermaLink="false">http://www.eriksmartt.com/blog/archives/405</guid>
		<description><![CDATA[In case someone else needs it, here&#8217;s a simple shell script I use for grabbing the current weather conditions by U.S. zipcode using the Yahoo APIs: function weather { zipcode=$1 if [ -n "$zipcode" ]; then lynx -dump "http://weather.yahooapis.com/forecastrss?p=$zipcode" &#124; grep -i condition &#124; awk -F' ' '{print $4 $5 $6}' &#124; awk -F'< ' [...]]]></description>
			<content:encoded><![CDATA[<p>In case someone else needs it, here&#8217;s a simple shell script I use for grabbing the current weather conditions by U.S. zipcode using the Yahoo APIs:</p>
<p><code>
<pre>
function weather {
  zipcode=$1
  if [ -n "$zipcode" ]; then
    lynx -dump "http://weather.yahooapis.com/forecastrss?p=$zipcode" | grep -i condition | awk -F' ' '{print $4 $5 $6}' | awk -F'< ' '{print $1}' | sed 's/,/ /'
  else
    echo 'USAGE: weather &lt;zipcode&gt;'
  fi
}
</pre>
</pre>
<p></code></p>
<p>The script uses lynx to grab the Yahoo RSS feed, piping the output to grep, which extracts the line containing the word &#8216;condition&#8217;.  awk then pulls out some specific fields (delimited by spaces, then later by &#8216;&lt;&#8217;), and sed converts the commas to spaces for prettier output.  Obviously, the whole thing is fairly fragile, and changes to the RSS format (which happened maybe a month back) break the code.  Checking the weather in Austin with the command: `weather 78701`, currently outputs: &#8220;Fair 67F&#8221;.</p>]]></content:encoded>
			<wfw:commentRss>http://www.eriksmartt.com/blog/archives/405/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

