<?xml version="1.0" encoding="UTF-8"?><feed
  xmlns="http://www.w3.org/2005/Atom"
  xmlns:thr="http://purl.org/syndication/thread/1.0"
  xml:lang="en"
  >
  <id>http://livingcode.org/feed/atom</id>
  <updated>2009-11-13T19:33:25Z</updated>
  <title type="text">Living Code</title>
  <subtitle type="text">Programming for the Fun of It</subtitle>
  <link rel="self" type="application/atom+xml" href="http://livingcode.org/feed" />
  <link rel="alternate" href="http://livingcode.org" />
  <rights type="text">Copyright 2009</rights>
  <generator uri="http://wordpress.org/" version="2.8.6">WordPress</generator>
      <entry>
    <id>http://livingcode.org/2009/aspect-oriented-python</id>
    <title type="html"><![CDATA[Aspect-oriented Python]]></title>
    <updated>2009-02-25T06:09:18Z</updated>
    <published>2009-02-25T06:09:18Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/02/24/aspect-oriented-python/feed" thr:count="4"  />
    <link rel="alternate" href="http://livingcode.org/2009/02/24/aspect-oriented-python" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[A friend asked me for an example of AOP in Python.  I started to write up my response, then realized it might be worth sharing more widely.
Briefly, AOP is about separating out Aspects which are are interspersed throughout your code (in AOP lingo, cross-cutting).  The canonical example is logging, but there are others.
For [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/02/24/aspect-oriented-python"><![CDATA[<p>A friend asked me for an example of <abbr title="Aspect-Oriented Programming">AOP</abbr> in Python.  I started to write up my response, then realized it might be worth sharing more widely.</p>
<p>Briefly, <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a> is about separating out <em>Aspects</em> which are are interspersed throughout your code (in AOP lingo, cross-cutting).  The canonical example is logging, but there are others.</p>
<p>For Python, as long as you&#8217;re content with before/after aspects, the situation is good.  In Python 2.5 and up there are two main tactics: decorators and context managers.  Decorators use the @ syntax and context managers are used with the &#8220;with&#8221; keyword.</p>
<h3>Decorators</h3>
<p>Decorators are only usable on functions and methods in 2.4 and 2.5, but in 2.6, 3.0 and beyond they can be used on classes as well.  Essentially they are callables (functions, methods, objects) that accept a function object and return a function object.  They are called when the function is defined, so they get a chance to have their way with it: annotate it, replace it, or wrap it.  The common case is to wrap it.</p>
<p>Quick example:</p>
<p><code>
<pre>
import logging
def before(fn):
    def wrapped(*args, **kws):
        logging.warn('about to call function %s' % fn.func_name)
        return fn(*args, **kws)
    return wrapped

def after(fn):
    def wrapped(*args, **kws):
        retVal = fn(*args, **kws)
        logging.warn('just returned from function %s' % fn.func_name)
        return retVal
    return wrapped
</pre>
<p></code></p>
<p>OK, those are three basic wrappers, you can use them like so:</p>
<p><code>
<pre>
@before
def foo():
    logging.warn('inside foo')

@after
def bar():
    logging.warn('inside bar')

@before
@after
def baz():
    logging.warn('inside baz')

foo()
bar()
baz()
</pre>
<p></code></p>
<p>This will result in the following output:</p>
<p><code>
<pre>
WARNING:root:about to call function foo
WARNING:root:inside foo
WARNING:root:inside bar
WARNING:root:just returned from function bar
WARNING:root:about to call function wrapped
WARNING:root:inside baz
WARNING:root:just returned from function baz
</pre>
<p></code></p>
<p>You will note that when we use two decorators on baz, the name of the function called by <code>before</code> is &#8220;wrapped.&#8221; This is because what <code>before</code> is called on is the result of <code>after</code>.  The <code>functools.update_wrapper</code> function is useful in this case to make a wrapped function look more like the original function.</p>
<p>For more, please see <a href="http://www.python.org/dev/peps/pep-0318/#examples">PEP 318 Decorators for Functions and Methods: Examples</a> and <a href="http://www.python.org/dev/peps/pep-3129/">PEP 3129 Class Decorators</a>. For convenience when creating new decorators, see the standard library functions <a href="http://docs.python.org/library/functools.html#functools.update_wrapper">functools.update_wrapper</a> and <a href="http://docs.python.org/library/functools.html#functools.wraps">functools.wraps</a>.</p>
<h3>Context Managers</h3>
<p>Context Managers are used with the <code>with</code> statement, and are handy for resource aquisition and release.  In Python 2.5 you have to &#8220;from __future__ import with_statement&#8221; to use them, but they are built-in in Python versions later than that. Also, objects such as files and locks are context managers now, so you can use patterns like</p>
<p><code>
<pre>
with open('example.txt') as example:
    for line in example:
        do_something(line)
</pre>
<p></code></p>
<p>This will automatically close the file when leaving the <code>with</code> block. And for locks the pattern is similar:</p>
<p><code>
<pre>
with myThreadingLock:
    do_something_threadsafely()
</pre>
<p></code></p>
<p>It is important to note that the lock will be release properly, or the file closed, even if an exception is thrown inside the <code> with</code> block.</p>
<p>If you want to create your own context managers, you can add two methods to your objects: <code>__enter__(self)</code> and <code>__exit__(self, exception_type, exception_value, traceback)</code>.  The return value from <code>__enter__</code> will be passed to the optional <code>as</code> variable (seen in the file example). The <code>__exit__</code> method will be called with exception info if there was an exception.  If no exception is raised in the <code>with</code> block, then all three arguements will be <code>None</code>.  If <code>__exit__</code> returns <code>True</code> then any exception will be &#8220;swallowed&#8221;, otherwise the exception will be re-raised after any cleanup.</p>
<p>For more info, see <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343 The &#8220;with&#8221; Statement</a>, especially the examples section, and also the helper functions in the standard library <a href="http://docs.python.org/library/contextlib.html">contextlib</a>.</p>
<h3>AOP and 80/20</h3>
<p>Full-on aspect-oriented programming is beyond the scope of this post and involves join-points, code weaving, and other such arcanery.  There are multiple Python libraries which target aspect-oriented coding styles, but for my money, the simplicity of the methods in the standard library, coupled with my impression that they cover at least 80% of the uses of AOP, make me favour these built-in techniques over any of the special purpose tools.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/unit-testing-in-vancouver</id>
    <title type="html"><![CDATA[Unit Testing in Vancouver]]></title>
    <updated>2009-02-02T18:56:41Z</updated>
    <published>2009-02-02T18:55:49Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/02/02/unit-testing-in-vancouver/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2009/02/02/unit-testing-in-vancouver" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[Just a quick reminder: Henry Prêcheur will be presenting Unit Testing in Python at the VanPyZ meeting tomorrow, February 3rd. The meeting will be at Workspace in Gastown (see map on VanPyZ page).  Meetings are from 7-8:30, then we head out for beers afterwards.
Hope to see you there!
]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/02/02/unit-testing-in-vancouver"><![CDATA[<p>Just a quick reminder: Henry Prêcheur will be presenting Unit Testing in Python at the <a href="http://vanpyz.org/">VanPyZ</a> meeting tomorrow, February 3rd. The meeting will be at Workspace in Gastown (see map on VanPyZ page).  Meetings are from 7-8:30, then we head out for beers afterwards.</p>
<p>Hope to see you there!</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/tab-dumping-with-applescript-and-back-to-python</id>
    <title type="html"><![CDATA[Tab Dumping with AppleScript and back to Python]]></title>
    <updated>2009-01-31T20:04:19Z</updated>
    <published>2009-01-31T19:58:31Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/01/31/tab-dumping-with-applescript-and-back-to-python/feed" thr:count="4"  />
    <link rel="alternate" href="http://livingcode.org/2009/01/31/tab-dumping-with-applescript-and-back-to-python" />
    <category scheme="http://livingcode.org" term="Mac" />
    <category scheme="http://livingcode.org" term="Projects" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[
Goal: Iterate through all my (OS X Safari) browser windows and make a list of titles and urls which is then placed in the clipboard ready to be pasted into an email or blog post.
This is an update to Tab Dumping in Safari. That still works well as the basis for extending any Cocoa-based application [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/01/31/tab-dumping-with-applescript-and-back-to-python"><![CDATA[<p><img src='http://livingcode.org/wp-content/uploads/2009/01/rock.jpg' alt='Rock' /></p>
<p><strong>Goal:</strong> Iterate through all my (OS X Safari) browser windows and make a list of titles and urls which is then placed in the clipboard ready to be pasted into an email or blog post.</p>
<p>This is an update to <a href="http://livingcode.org/2006/tab-dumping-in-safari">Tab Dumping in Safari</a>. That still works well as the basis for extending any Cocoa-based application at runtime, but it relies on SIMBL, which while it is a great bit of code, essentially is abusing the InputManager interface.  Some developers and users shun such hacks, and at least one Apple application checks for them at startup and warns you from using them.</p>
<p>I have been running the <a href="http://webkit.org/">WebKit</a> nightlies, which are like Safari, but with newer code and features (most importantly to me right now, a Firebug-like developer toolkit).  WebKit warns at startup that if you&#8217;re running extensions (such as SIMBL plugins) it may make the application less stable.  I was running both <a href="http://haoli.dnsalias.com/">Saft</a> and my own tab dumping plugin, and WebKit was crashing a lot.  So I removed those and the crashes went away.  I miss a handful of the Saft extensions (but not having to update it for every Safari point release), and I found I <em>really</em> miss my little tab-dumping tool.</p>
<p>I toyed with the idea of rewriting it as a service, which would then be available from the services menu, but couldn&#8217;t figure out how to access the application&#8217;s windows and tabs from the service.  So I tried looking at Safari&#8217;s scriptable dictionary, using the AppleScript Script Editor.  Long ago, John Gruber had <a href="http://daringfireball.net/2003/05/safaris_unscriptable_tabs">written</a> about the frustration with Safari&#8217;s tabs not being scriptable, but a glance at the scripting dictionary showed me this was no longer the case (and probably hasn&#8217;t been for years, I haven&#8217;t kept track).</p>
<p>I am a complete n00b at AppleScript.  I find the attempt at English-like syntax just confuses (and irritates) me no end.  But what I wanted looked achievable with it, so I armed myself with some examples from Google searches, and Apple&#8217;s intro pages and managed to get what I wanted working.  It may not be the best possible solution (in fact I suspect the string concatenation may be one of the most pessimal methods), but it Works For Me™.</p>
<p>In Script Editor, paste in the following:</p>
<p><code>
<pre>
set url_list to ""
-- change WebKit to Safari if you are not running nightlies
tell application "WebKit"
  set window_list to windows
  repeat with w in window_list
    try
      set tab_list to tabs of w
      repeat with t in tab_list
        set url_list to url_list &#038; name of t &#038; "\n"
        set url_list to url_list &#038; URL of t &#038; "\n\n"
      end repeat
    on error
      -- not all windows have tabs
    end try
  end repeat
  set the clipboard to url_list
end tell
</pre>
<p></code></p>
<p>I had to use AppleScript Utility to add the script menu to my menu bar.  From there it was easy to create script folders that are specific to both WebKit and Safari and save a copy of the script (with the appropriate substitution, see comment in script) into each folder.  Now I can copy the title and URL of all my open tabs onto the clipboard easily again, without any InputManager hacks.</p>
<p>I had some recollection that is a way to do this from Python, so I looked and found <a href="http://appscript.sourceforge.net/">Appscript</a>.  I was able to install this with a simple <code>easy_install appscript</code> and quickly ported most of the applescript to Python.  The only stumbling block was that I couldn&#8217;t find a way to access the clipboard with appscript, and I didn&#8217;t want to have to pull in the PyObjC framework just to write to the clipboard. So I used <code>subprocess</code> to call the command-line <code>pbcopy</code> utility.</p>
<p><code>
<pre>
#!/usr/local/bin/python
from appscript import app
import subprocess
tab_summaries = []
for window in app('WebKit').windows.get():
    try:
        for tab in window.tabs.get():
            name = tab.name.get().encode('utf-8')
            url = tab.URL.get().encode('utf-8')
            tab_summaries.append('%s\n%s' % (name, url))
    except:
        # not all windows have tabs
        pass
clipboard = subprocess.Popen('pbcopy', stdin=subprocess.PIPE)
clipboard.stdin.write('\n\n'.join(tab_summaries))
</pre>
<p></code></p>
<p>The remaining hurdle was simply to put the Python script I&#8217;d written into the same Scripting folder as my AppleScript version. For me this was <code>~/Library/Scripts/Applications/WebKit/</code>. When run from the scripts folder, your usual environment is not inherited, so the <code>#!</code> line must point to the version of Python you are using (and which has Appscript installed). You should also make the script executable.  Adding <code>.py</code> or any other extension is not necessary.</p>
<p>Overall, while I found AppleScript to be very powerful, and not quite as painful as I remembered, I found the Python version (warts and all) to be easier to work with. Combined with the fact that the script folder will run non-Applescript scripts, this opens up new worlds for me.  I have hesitated in the past to write a lot of SIMBL-based plugins, tempting though it may be, because they are hacks, and they run in <em>every</em> Cocoa-based application.  But adding application-specific (or universal) scripts, in Python, is pure, unadulterated goodness.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/processing-playground</id>
    <title type="html"><![CDATA[Processing Playground]]></title>
    <updated>2008-06-10T14:02:58Z</updated>
    <published>2008-06-10T14:02:57Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/06/10/processing-playground/feed" thr:count="2"  />
    <link rel="alternate" href="http://livingcode.org/2008/06/10/processing-playground" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[
There is a lot of interesting stuff happening in Javascript land these days, even to the point of other languages targetting the browser as a runtime, but running on top of Javascript.  You can run Scheme right in the browser, and by now everyone has probably heard of Objective-J (open-source coming soon), an Objective-C-like [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/06/10/processing-playground"><![CDATA[<p><a href='http://livingcode.org/2008/processing-playground/kudzu-3/' rel='attachment wp-att-93' title='Kudzu 3'><img src='http://livingcode.org/wp-content/uploads/2008/06/kudzu3_forweb.png' alt='Kudzu 3' /></a></p>
<p>There is a lot of interesting stuff happening in Javascript land these days, even to the point of other languages targetting the browser as a runtime, but running on top of Javascript.  You can run <a href="http://www.bluishcoder.co.nz/jsscheme/">Scheme</a> right in the browser, and by now everyone has probably heard of Objective-J (open-source <a href="http://objective-j.org/">coming soon</a>), an Objective-C-like language used by 280 North to create their <a href="http://280slides.com/">280 Slides</a> web application, inspired by Apple&#8217;s Keynote.</p>
<p>Since my last post <a href="http://livingcode.org/2008/processing-critters">about Processing</a>, John Resig managed to port most of Processing to Javascript, so it is easier than ever to get started.  Now instead of having to download the Java-based runtime, you can create Processing animations in your browser, within the limitations that it only targets very recent, beta browsers (Firefox 3, Opera 9.5, WebKit nightlies, no version of IE) and that not all of Processing is supported (no 3D, for instance, and my example from the earlier post does not run).  Still, it is interesting and a lot of fun to play with.  My seven-year-old son is fascinated with computer programming and looking to move beyond <a href="http://scratch.mit.edu/">Scratch</a>, so as part of that I stuck all the basic examples from Mr. Resig&#8217;s site into one page, with a menu to select them, and a button to run them.  And I made them editable.  You can write entirely new code too, of course, but the examples can help for getting started.  I hope folks enjoy it.</p>
<p><a href="http://livingcode.org/project/processing/#sine_wave">Processing Playground</a></p>
<p>Of course, what my kids really want is a version of Scratch that we can extend to add some more features of our own.  Scratch has been open-sourced, so we could possibly extend it, but it is built on Squeak Smalltalk, and I&#8217;ve never been very good at Smalltalk.  Instead, I am porting it to Javascript.  It is still in the early stages, but I&#8217;m making steady progress in my hour or so I have to code each evening, and my kids are eager to use it, so they keep me motivated and focussed.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/meme-du-jour</id>
    <title type="html"><![CDATA[Meme du jour]]></title>
    <updated>2008-04-11T16:05:39Z</updated>
    <published>2008-04-11T04:49:10Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/04/10/meme-du-jour/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2008/04/10/meme-du-jour" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[Just for fun, and because I&#8217;m trying out two things:

Using Ecto for posting again
Blogging more often

Here are my results from the latest craze:



$ history&#124;awk '{a[$2]++} END{for(i in a){printf "%5d\t%s\n",a[i],i}}'&#124;sort -rn&#124;head
139 ls
87 cd
54 python
43 /usr/bin/python
38 less
21 vim
16 clear
12 mate
11 rm
10 ssh



The first python is the one I built from source so I can include it in [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/04/10/meme-du-jour"><![CDATA[<p>Just for fun, and because I&#8217;m trying out two things:</p>
<ol>
<li>Using Ecto for posting again</li>
<li>Blogging more often</li>
</ol>
<p>Here are my results from the latest craze:</p>
<pre>
<code>
<pre>
$ history|awk '{a[$2]++} END{for(i in a){printf "%5d\t%s\n",a[i],i}}'|sort -rn|head
139 ls
87 cd
54 python
43 /usr/bin/python
38 less
21 vim
16 clear
12 mate
11 rm
10 ssh
</pre>
<p></code>
</pre>
<p>The first python is the one I built from source so I can include it in applications packaged with py2app, the second is the built-in python for Leopard. Both are version 2.5. The mate program is used to open files in TextMate from the command line.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/metaprogramming-at-vanpyz</id>
    <title type="html"><![CDATA[MetaProgramming at VanPyZ]]></title>
    <updated>2008-04-01T04:01:59Z</updated>
    <published>2008-04-01T04:01:59Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/03/31/metaprogramming-at-vanpyz/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2008/03/31/metaprogramming-at-vanpyz" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[Just a reminder for Pythonistas in the Vancouver area: The Vancouver Python and Zope user group (VanPyZ) is tomorrow (Tuesday, April 1). Paul Prescod will be talking about metaprogramming in Python. Details and directions are on the VanPyZ site. And, as usual, we&#8217;ll be heading out to the pub afterwards for more discussion.
Hope to see [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/03/31/metaprogramming-at-vanpyz"><![CDATA[<p>Just a reminder for Pythonistas in the Vancouver area: The Vancouver Python and Zope user group (VanPyZ) is tomorrow (Tuesday, April 1). Paul Prescod will be talking about metaprogramming in Python. Details and directions are on the <a href="http://www.vanpyz.org/">VanPyZ site</a>. And, as usual, we&#8217;ll be heading out to the pub afterwards for more discussion.</p>
<p>Hope to see you there!</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/saving-png-from-pygame</id>
    <title type="html"><![CDATA[Saving PNG from PyGame]]></title>
    <updated>2008-04-01T03:21:31Z</updated>
    <published>2008-04-01T03:21:31Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/03/31/saving-png-from-pygame/feed" thr:count="7"  />
    <link rel="alternate" href="http://livingcode.org/2008/03/31/saving-png-from-pygame" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[The latest version, 1.8, of PyGame can save PNGs directly from a Surface: pygame.Image.save(mySurface, 'myimagefile.png').  But what if you want to support an older version of PyGame, such as the one available for the N800 or the XO?  Well, assuming you have access to the Python Image Library, you can use that:


import Image [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/03/31/saving-png-from-pygame"><![CDATA[<p>The latest version, 1.8, of PyGame can save PNGs directly from a Surface: <code>pygame.Image.save(mySurface, 'myimagefile.png')</code>.  But what if you want to support an older version of PyGame, such as the one available for the N800 or the XO?  Well, assuming you have access to the Python Image Library, you can use that:</p>
<blockquote><p><code>
<pre>
import Image # from PIL
import pygame

def pygame_to_pil_img(pg_surface):
    imgstr = pygame.image.tostring(pg_surface, 'RGB')
    return Image.fromstring('RGB', pg_surface.get_size(), imgstr)

def pil_to_pygame_img(pil_img):
    imgstr = pil_img.tostring()
    return pygame.image.fromstring(imgstr, pil_img.size, 'RGB')
</pre>
<p></code>
</p></blockquote>
<p>Once you have a PyGame Image, you can save it to PNG easily: <code>myImage.save('myfilename.png')</code></p>
<p>I&#8217;ve found myself looking for this code snippet more than once, now I can Google for it more readily, and maybe someone else will find it helpful too.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/drawing-hexmaps</id>
    <title type="html"><![CDATA[Drawing Hexmaps]]></title>
    <updated>2008-03-21T05:03:08Z</updated>
    <published>2008-03-21T05:03:08Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/03/20/drawing-hexmaps/feed" thr:count="3"  />
    <link rel="alternate" href="http://livingcode.org/2008/03/20/drawing-hexmaps" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[The other day, Thomas Guest talked about drawing chessboards, and ended with a challenge.  I wanted to answer a different challenge, however.  What if, instead of drawing on a rectangular grid, we wanted to draw on a hexagonal grid? The following is my slapdash answer.  For real-world use I&#8217;d make nice classes [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/03/20/drawing-hexmaps"><![CDATA[<p>The other day, Thomas Guest talked about <a href="http://wordaligned.org/articles/drawing-chessboards">drawing chessboards</a>, and ended with a challenge.  I wanted to answer a different challenge, however.  What if, instead of drawing on a rectangular grid, we wanted to draw on a hexagonal grid? The following is my slapdash answer.  For real-world use I&#8217;d make nice classes and pass more parameters to the methods, but to demonstrate the math I&#8217;m just going to use global constants and functions.</p>
<p>Like Thomas&#8217; article, I will show solutions using several different tools, in this case Apple&#8217;s <a href="http://developer.apple.com/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_python/chapter_17_section_1.html#//apple_ref/doc/uid/TP30001066-CH218-TPXREF101">Core Graphics</a>, <a href="http://pygame.org/docs/">PyGame</a>, <a href="http://www.pythonware.com/library/pil/handbook/index.htm">Python Imaging Library</a> (PIL), and <a href="http://www.w3.org/TR/SVG11/">SVG</a>. All of these solutions will use the same constants and math:</p>
<p><code>
<pre>
# Constants used by each solution

from math import sin, cos, pi, sqrt
THETA = pi / 3.0 # Angle from one point to the next
HEXES_HIGH = 8 # How many rows of hexes
HEXES_WIDE = 5 # How many hexes in a row
RADIUS = 30 # Size of a hex
HALF_RADIUS = RADIUS / 2.0
HALF_HEX_HEIGHT = sqrt(RADIUS ** 2 - HALF_RADIUS ** 2)
IMAGE_WIDTH = int(RADIUS * (HEXES_WIDE * 3 + .5))
IMAGE_HEIGHT = int(HALF_HEX_HEIGHT * (HEXES_HIGH + 1))

# Functions (generators) used by each solution

def hex_points(x,y):
    '''Given x and y of the origin, return the six points around the origin of RADIUS distance'''
    for i in range(6):
        yield cos(THETA * i) * RADIUS + x, sin(THETA * i) * RADIUS + y

def hex_centres():
    for x in range(HEXES_WIDE):
        for y in range(HEXES_HIGH):
            yield (x * 3 + 1) * RADIUS + RADIUS * 1.5 * (y % 2), (y + 1) * HALF_HEX_HEIGHT
</pre>
<p></code></p>
<p>Now, given the above, what does the code look like to draw the hexes?  Because each library handles colours slightly differently, we will need a generator for colours (and we will need more than just black and white as the chessboard used, because each hex borders on six others).  I haven&#8217;t given a lot of thought to optimal colouring schemes: each colour generator simply produces red, yellow, blue, and green in a cycle.  Here is the image produced by the Core Graphics solution, followed by the code:</p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/03/quartz_hexes.png' alt='Hex Image 1' /></p>
<p><code>
<pre>
def quartz_colours():
    while True:
        yield 1,0,0,1 # red
        yield 1,1,0,1 # yellow
        yield 0,0,1,1 # blue
        yield 0,1,0,1 # green

def quartz_hex():
    '''Requires a Mac with OS 10.4 or better and the Developer Tools installed'''
    import CoreGraphics as cg
    colours = quartz_colours()
    cs = cg.CGColorSpaceCreateDeviceRGB()
    c = cg.CGBitmapContextCreateWithColor(IMAGE_WIDTH, IMAGE_HEIGHT, cs, (0,0,0,.2))
    c.saveGState()
    c.setRGBStrokeColor(0,0,0,0)
    c.setLineWidth(0)
    for x,y in hex_centres():
        c.beginPath()
        c.setRGBFillColor(*colours.next())
        points = list(hex_points(x,y))
        c.moveToPoint(*points[-1])
        [c.addLineToPoint(*pt) for pt in points]
        c.drawPath(cg.kCGPathFill)
    c.restoreGState()
    c.writeToFile("quartz_hexes.png", cg.kCGImageFormatPNG)
</pre>
<p></code></p>
<p>Now for some cross-platform examples.  Here is the image generated by PyGame, followed by that code:</p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/03/pygame_hexes.png' alt='Hex Image 2' /></p>
<p><code>
<pre>
def pygame_colours():
    while True:
        yield 255, 0, 0 # red
        yield 255, 255, 0 # yellow
        yield 0, 0, 255 # blue
        yield 0, 255, 0 # green

def pygame_hex():
    '''Requires PyGame 1.8 or better to save as PNG'''
    import pygame
    pygame.init()
    screen = pygame.display.set_mode((IMAGE_WIDTH, IMAGE_HEIGHT))
    colours = pygame_colours()
    for x,y in hex_centres():
        pygame.draw.polygon(screen, colours.next(), list(hex_points(x,y)))
    pygame.image.save(screen, 'pygame_hexes.png')
</pre>
<p></code></p>
<p>When you run the PyGame script, it will actually pop up a window very briefly, draw into the window, save the result, and close the window.  I also didn&#8217;t get the PyGame script to add transparency for the background, although I think it could be added fairly easily.  Now, for the web, here is a solution in SVG, with the image captured by screenshot in Safari, followed by the Python code, and the resulting SVG code:</p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/03/picture-4.png' alt='Hex Image 3' /></p>
<p><code>
<pre>
def svg_colours():
    while True:
        yield 'rgb(255, 0, 0)'
        yield 'rgb(255, 255, 0)'
        yield 'rgb(0, 0, 255)'
        yield 'rgb(0, 255, 0)'

def svg_hex():
    out = open('svg_hexes.svg', 'w')
    print >> out, '''&lt;?xml version="1.0" standalone="no"?>
    &lt;!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    &lt;svg width="%spx" height="%spx" version="1.1" xmlns="http://www.w3.org/2000/svg">''' % (IMAGE_WIDTH, IMAGE_HEIGHT)
    colours = svg_colours()
    for pt in hex_centres():
        print >> out, '&lt;polygon fill="%s" stroke-width="0" points="%s" />' % (colours.next(),  ' '.join(["%s,%s" % (x,y) for (x,y) in hex_points(*pt)]))
    print >> out, '&lt;/svg>'
    out.close()
</pre>
<p></code></p>
<p>And here is the SVG created by the above script: <a href='http://livingcode.org/wp-content/uploads/2008/03/svg_hexes.svg' title='SVG Hexes'>SVG Hexes</a></p>
<p>Finally, one library which overlaps with the ones used by the Chessboard example: Python Imaging Library.</p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/03/pil_hexes.png' alt='Hex Image 4' /></p>
<p><code>
<pre>
pil_colours = pygame_colours  # same format works, so we'll re-use it

def pil_hex():
    import Image, ImageDraw
    image = Image.new("RGBA", (IMAGE_WIDTH,IMAGE_HEIGHT), (0,0,0,0))
    colours = pil_colours()
    draw = ImageDraw.Draw(image)
    for x,y in hex_centres():
        draw.polygon(list(hex_points(x,y)), fill=colours.next())
    image.save('pil_hexes.png', 'PNG')
</pre>
<p></code></p>
<p>That&#8217;s it for my examples.  Thomas ended with a challenge for displaying chess, and for describing the position. To describe the position, I would use a standard chess notation, such as described <a href="http://www.xml.com/pub/a/2004/08/25/tourist.html">here</a>.  For my challenge, what other formats would be useful to create hex maps in?  POVRay?  Flash?  Any other examples out there?</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/the-419-economy</id>
    <title type="html"><![CDATA[The 419 Economy]]></title>
    <updated>2008-03-20T05:25:17Z</updated>
    <published>2008-03-20T05:25:17Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/03/19/the-419-economy/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2008/03/19/the-419-economy" />
    <category scheme="http://livingcode.org" term="Fiction" />
    <category scheme="http://livingcode.org" term="Humor" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[Hello, my name is Sergio Arragones and I am writing to you for assistance in a matter that will be of great economic benefit to us both.
My late father was VICE PRESIDENT of the large American investment bankerage of Bear Stearns and he managed to put aside over two billion US dollars of bailout money [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/03/19/the-419-economy"><![CDATA[<p>Hello, my name is Sergio Arragones and I am writing to you for assistance in a matter that will be of great economic benefit to us both.</p>
<p>My late father was VICE PRESIDENT of the large American investment bankerage of Bear Stearns and he managed to put aside over two billion US dollars of bailout money from the puppet government of Mr. George Bush.</p>
<p>Unfortunately, he was killed in a incident of ROAD RAGE when his bullet-proof Mercedes convertible was driven into the bomb barricade of the New York UN Building by the SUV of an off-duty Police Officer.</p>
<p>While my family is still grieving over his tragic death, and attempting to get the suspicious circumstances investigated, I must act quickly to move these funds to your Nation for safekeeping. As a Citizen of the Monarchy of Canada, you may receive these funds for me until I may cross from New York State to the Province of Quebec, at which time you will transfer the funds over to me, keeping 10% (TEN PERCENT) for yourself, along with my Gratitude.</p>
<p>In order for me to transfer the Fund to you, you will need to create a PayPal account for this purpose.  Do not use an existing PayPal account, as it may already have been compromised by nefarious hackers and BotNets. Also, you will need to download the Python libraries which allow you to code to PayPal directly.  In addition, you will need libraries for Google Checkout the Atom Publishing Protocol.</p>
<p>On a server under your control (the server must be physically located in the Sovereignty of Canada.  THIS IS IMPORTANT) you must set up a WSGI server.  You may use Django or TurboGears for this, or use the reference WSGI implementation.  I recommend you use PYTHON 2.5 or greater as many of the tools you need will be part of the STANDARD LIBRARY. </p>
<p>Once you have the Foundations of a Web2.0 server administered, contact me at the return address of this message and I will give you instructions on how to proceed for the transfer of funds.</p>
<p>My family thanks you.</p>
<p>Sincerly,</p>
<p>Dr. Rev. Sergio Arragones, Esq.<br />
New York, NY<br />
United States of America</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/processing-critters</id>
    <title type="html"><![CDATA[Processing Critters]]></title>
    <updated>2008-03-20T17:49:53Z</updated>
    <published>2008-03-20T05:21:53Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/03/19/processing-critters/feed" thr:count="1"  />
    <link rel="alternate" href="http://livingcode.org/2008/03/19/processing-critters" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[



This browser does not have a Java Plug-in.


Get the latest Java Plug-in here.







Source code: sketch_080314a

I&#8217;ve been playing around some with Processing, this is the result.  As I mentioned in my earlier article, Processing and NodeBox are quite similar. Processing has some more interactivity (better keyboard and mouse handling) built in, and it can do [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/03/19/processing-critters"><![CDATA[<div id="sketch_080314a_container">
<!--[if !IE]> &#8211;><br />
<object classid="java:sketch_080314a.class" type="application/x-java-applet" archive="http://livingcode.org/wp-content/uploads/2008/03/sketch_080314a.jar" width="400" height="400" standby="Loading Processing software..." ><param name="archive" value="http://livingcode.org/wp-content/uploads/2008/03/sketch_080314a.jar" /><param name="mayscript" value="true" /><param name="scriptable" value="true" /><param name="image" value="http://livingcode.org/wp-content/uploads/2008/03/loading.gif" /><param name="boxmessage" value="Loading Processing software..." /><param name="boxbgcolor" value="#FFFFFF" /><param name="test_string" value="outer" /><!--<![endif]--><br />
<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" codebase="http://java.sun.com/update/1.4.2/jinstall-1_4_2_12-windows-i586.cab" width="400" height="400" standby="Loading Processing software..."  ><param name="code" value="sketch_080314a" /><param name="archive" value="http://livingcode.org/wp-content/uploads/2008/03/sketch_080314a.jar" /><param name="mayscript" value="true" /><param name="scriptable" value="true" /><param name="image" value="http://livingcode.org/wp-content/uploads/2008/03/loading.gif" /><param name="boxmessage" value="Loading Processing software..." /><param name="boxbgcolor" value="#FFFFFF" /><param name="test_string" value="inner" /><p>
<strong><br />
This browser does not have a Java Plug-in.<br />
<br />
<a href="http://java.sun.com/products/plugin/downloads/index.html" title="Download Java Plug-in"><br />
Get the latest Java Plug-in here.<br />
</a><br />
</strong>
</p>
<p></object><br />
<!--[if !IE]> &#8211;><br />
</object><br />
<!--<![endif]-->
</div>
</p>
<p>Source code: <a href="http://livingcode.org/wp-content/uploads/2008/03/sketch_080314a.pde">sketch_080314a</a></p>
<p>
I&#8217;ve been playing around some with <a href="http://processing.org/">Processing</a>, this is the result.  As I mentioned in my earlier <a href="http://livingcode.org/2008/the-importance-of-visual-programming">article</a>, Processing and <a href="http://www.nodebox.net/code/index.php/Home">NodeBox</a> are quite similar. Processing has some more interactivity (better keyboard and mouse handling) built in, and it can do basic 3D. NodeBox has better color handling (gradients) and remarkable libraries (WordNet).  But what it really comes down to is that NodeBox is Python (much easier to extend) and Processing is Java (still easier than straight Java, but a lot more code to do basic extensions).  Now all we need is a quick-start programming environment like these for Flash (and before you tell me the Adobe Flash tools are for artists&#8211;I have used the Flash IDE and it is possibly the worst IDE I&#8217;ve ever experienced.  Which is odd, because the Flex IDE is one of the best, better than XCode/Interface Builder in some ways).
</p>
<p>
All of which is the long way to say that I enjoyed making this little animation in Processing, but I&#8217;m ready to go back to working in Python now, thank you.</p>
]]></content>
        </entry>
  </feed>
