<?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/?p=179</id>
    <title type="html"><![CDATA[Go Language and Functional Programming]]></title>
    <updated>2009-11-13T19:33:25Z</updated>
    <published>2009-11-13T19:33:25Z</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/11/13/go-language-and-functional-programming/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2009/11/13/go-language-and-functional-programming" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[There is a cool new language on the block, coming from The Google courtesy of (among others) Rob Pike and Ken Thompson. The language is called Go (and the debugger is called Ogle, so put &#8216;em together for a secret message) and it attempts to be both a low-level, type-safe, compiled language, like C, while [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/11/13/go-language-and-functional-programming"><![CDATA[<p>There is a cool new language on the block, coming from The Google courtesy of (among others) Rob Pike and Ken Thompson. The language is called <a href="http://golang.org/">Go</a> (and the debugger is called Ogle, so put &#8216;em together for a secret message) and it attempts to be both a low-level, type-safe, compiled language, like C, while being garbage-collected, concise, with high-level structures and idioms like Python and Javascript. There are a lot of things to like in it, and I am exploring what it can and cannot do.  My first question was whether you could use it for functional programming, i.e., are functions first-class objects that can be passed to other functions, returned from functions, stored in variables, etc. This wasn&#8217;t in the <a href="http://golang.org/doc/go_faq.html">FAQ</a> or the <a href="http://golang.org/doc/go_lang_faq.html">Language Design FAQ</a>, but there were some hints of it in the description of channels, so I went ahead and wrote my own tests to see if it would work.</p>
<p><code><br />
    package main</p>
<p>    import fmt "fmt"</p>
<p>    type Stringy func() string</p>
<p>    func foo() string{<br />
         return "Stringy function"<br />
    }</p>
<p>    func takesAFunction(foo Stringy){<br />
        fmt.Printf("takesAFunction: %v\n", foo())<br />
    }</p>
<p>    func returnsAFunction()Stringy{<br />
        return func()string{<br />
            fmt.Printf("Inner stringy function\n");<br />
            return "bar" // have to return a string to be stringy<br />
        }<br />
    }</p>
<p>    func main(){<br />
        takesAFunction(foo);<br />
        var f Stringy = returnsAFunction();<br />
        f();<br />
        var baz Stringy = func()string{<br />
            return "anonymous stringy\n"<br />
        };<br />
        fmt.Printf(baz());<br />
    }<br />
</code></p>
<p>This compiled and ran, giving the right output, so it looks to me like functional programming is indeed possible in Go, and on the <a href="http://golang.org/doc/effective_go.html">Effective Go</a> page we learn, &#8220;In Go, function literals are closures: the implementation makes sure the variables referred to by the function survive as long as they are active.&#8221; So that&#8217;s kind of cool.</p>
<p>Go also has rich, high-level concurrency support similar to <a href="http://erlang.org/">Erlang</a>, several features that prevent random memory from being read or written, and both strings and maps (dictionaries, hash tables) are built-in datatypes. It has a small, but powerful standard library.</p>
<p>One puzzle down, several to go. I still want to explore how I can talk to <a href="http://developer.apple.com/cocoa/">Cocoa</a> from Go (for GUIs), how to wrap libraries such as <a href="http://xmlsoft.org/">libxml2</a> and <a href="http://www.cairographics.org/">cairo</a> for Go, and basically how to map more Python/Javascript library goodness into Go&#8217;s world. </p>
<p>I have smaller questions too: can I add methods to existing types? How do I load the contents of a URL? It&#8217;s looking good so far! Tune in next time for more exploration.</p>
]]></content>
        </entry>
    <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/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/drawing-with-opacity</id>
    <title type="html"><![CDATA[Drawing with opacity]]></title>
    <updated>2009-01-03T19:58:55Z</updated>
    <published>2008-12-14T18:46:20Z</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/12/14/drawing-with-opacity/feed" thr:count="4"  />
    <link rel="alternate" href="http://livingcode.org/2008/12/14/drawing-with-opacity" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[This is something of a followup to earlier posts Drawing Hexmaps and Saving PNG from PyGame.  A recent comment from Roger Aisling on the second of those posts asked about drawing with opacity in the Python Image Library (PIL).  A check of the PIL API didn&#8217;t turn up anything, but there is an [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/12/14/drawing-with-opacity"><![CDATA[<p>This is something of a followup to earlier posts <a href="http://livingcode.org/2008/drawing-hexmaps">Drawing Hexmaps</a> and <a href="http://livingcode.org/2008/saving-png-from-pygame">Saving PNG from PyGame</a>.  A recent comment from <a href="http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/">Roger Aisling</a> on the second of those posts asked about drawing with opacity in the <a href="http://www.pythonware.com/library/pil/handbook/index.htm">Python Image Library</a> (PIL).  A check of the PIL API didn&#8217;t turn up anything, but there is an optional add-on to the PIL called <a href="http://effbot.org/zone/pythondoc-aggdraw.htm">aggdraw</a>, which is based on <a href="http://www.antigrain.com/">Anti-Grain Geometry</a> (AGG), a graphics library that seems to cover similar ground to <a href="http://www.cairographics.org/">Cairo</a>.  I&#8217;ve been meaning to play with both of these, but don&#8217;t know enough about either project to know what is better about one vs. the other.  I know Cairo is used by Mozilla, GTX+, Mono, Inkscape, and WebKit (under GTX+).  I wasn&#8217;t able to find much about where AGG is used.</p>
<p>Anyway, here are some examples showing how to draw polygons with variable opacity (or alpha).  I&#8217;ve got examples for <a href="http://nodebox.net/code/index.php/Home">NodeBox</a>, aggdraw, and pycairo.  I was going to do some for the browser canvas, <a href="http://processing.org/">Processing</a>, PyObjC, and SVG, but a) I wanted to get this post out, and b) PyCairo can already output to SVG and Cocoa (and Processing will be very similar to NodeBox).  So if there is any interest in those examples, or others I may have forgotten, let me know in the comments.</p>
<p>While the images below look identical (at least they do to me), each was drawn with its respective library.</p>
<p>For each library I will present the drawing function and the main function that sets things up and drives it.  At the end I will present the utility functions used which were the same for all libraries.  No optimizations here, just the simplest thing I could do that worked.</p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/12/nodebox_example.png' alt='NodeBox Example Image'  title="NodeBox Example"/></p>
<p><strong>NodeBox</strong></p>
<p>I began with NodeBox, because it is so easy work with.  In Processing they call programs &#8220;sketches&#8221; and in NodeBox that is very much what it feels like.  The first thing I worked up was a way to draw &#8220;random&#8221; polygons in the same way for each libary. I could seed the random with a set value, but decided to use random to generate starting values, then just re-use those initial values.  To get 50 different polygons, I used a list of primes, chose from the list at random, then used those selected values to increment each polygon vertex and color value (red, green, blue, and alpha).  All of which was probably more work than was strictly necessary, but should be stable across different versions of Python and different operating systems.</p>
<p>The drawing routines all have the same signature.  They take a tuple of point tuples (x,y) and a tuple of colors (r,g,b,a) as ints between 0 and 255.</p>
<p><code>
<pre>
def nodebox_poly(pts, clr):
    fill(*ints2floats(clr)) # convert ints in range 0-255 into floats between 0.0 and 1.0
    beginpath()             # every time we want to change colours or linewidth we need to start a new path
    moveto(*pts[-1])     # start and end at the last point in the list
    for pt in pts:
        lineto(*pt)
    endpath()

def nodebox_main():
    size(WIDTH, HEIGHT) # nodebox wants to know how big a canvas you are working with
    draw_all(nodebox_poly) # No additional setup needed
</pre>
<p></code></p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/12/cairo_example.png' alt='Cairo Example Image' title="Cairo Example" /></p>
<p><b>PyCairo</b></p>
<p>The lines in cairo_main where we create the surface and where we save it are all we would have to change if we wanted to generate a Cocoa view, an SVG document, a PDF document, etc.  Two of the main differences between this and the NodeBox example are that there is a bit more setup (Cairo doesn&#8217;t default to a white background) and we need to have a reference to the context for drawing, where NodeBox has an implicit drawing context.</p>
<p><code>
<pre>
def cairo_poly(pts, clr):
    ctx.set_source_rgba(*ints2floats(clr))
    ctx.move_to(*pts[-1])
    for pt in pts:
        ctx.line_to(*pt)
    ctx.close_path()
    ctx.fill()

def cairo_main():
    # Setup Cairo
    import cairo
    global ctx
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
    ctx = cairo.Context(surface)
    # fill background white
    cairo_poly(((0,0),(WIDTH,0),(WIDTH,HEIGHT),(0,HEIGHT)),(255,255,255,255))
    draw_all(cairo_poly)
    surface.write_to_png('cairo_example.png')
</pre>
<p></code></p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/12/aggdraw_example.png' alt='Aggdraw Example Image'  title="Aggdraw Example" /></p>
<p><b>aggdraw</b></p>
<p>The aggdraw example is very similar to Cairo.  In fact, if I&#8217;d done either of these first, I would have passed the context object around and simply ignored it in NodeBox to eliminate a global variable.  Aggdraw can draw in memory without using PIL, but doesn&#8217;t appear to have a way to write to a PNG image that way, so we draw to a PIL image (which requires us to flush all drawing operations before writing the file).</p>
<p><code>
<pre>
def aggdraw_poly(pts, clr):
    import aggdraw
    global ctx
    b = aggdraw.Brush(clr, clr[-1])
    pts2 = []
    for p in pts:
        pts2.extend(p)
    ctx.polygon(pts2, b)

def aggdraw_main():
    import aggdraw, Image
    global ctx
    img = Image.new('RGBA', (WIDTH, HEIGHT), "white")
    ctx = aggdraw.Draw(img)
    draw_all(aggdraw_poly)
    ctx.flush()
    img.save('aggdraw_example.png')
</pre>
<p></code></p>
<p><b>Utilites</b></p>
<p>These were the same for all of the examples.  If you put it all in one file (or use mine, linked below) you can choose what library to use by switching which main function is called.</p>
<p><code>
<pre>
MIN_ALPHA = 50
MAX_ALPHA = 100

WIDTH = 500
HEIGHT = 250

#
#   Utilities
#
def hex2tuple(hex_color):
    return tuple([int(hex_color[i:i+2], 16) for i in range(1,9,2)])

def tuple2hex(tuple_color):
    return "#%0.2X%0.2X%0.2X%0.2X" % tuple_color

def ints2floats(tuple_color):
    return tuple([c / 255.0 for c in tuple_color])

def inc_point(p, dp):
    return (p[0] + dp[0]) % WIDTH, (p[1] + dp[1]) % HEIGHT

def inc_triangle(t, dt):
    return tuple([inc_point(t[i], dt[i]) for i in range(3)])

def inc_color(c, dc):
    new_c = [(c[i] + dc[i]) % 256 for i in range(3)]
    new_a = (c[3] + dc[3]) % MAX_ALPHA
    if new_a < MIN_ALPHA: new_a += MIN_ALPHA
    new_c.append(new_a)
    return tuple(new_c)

def draw_all(draw_fn):
    triangle = start_t
    color = start_c
    for i in range(50):
        triangle = inc_triangle(triangle, dt)
        color = inc_color(color, dc)
        draw_fn(triangle, color)

#
#   Starting and incrementing values
#
start_c = hex2tuple('#0xE6A20644')
start_t = (127, 132), (341, 171), (434, 125)
dt = (107, 23), (47, 73), (13, 97)
dc = 61, 113, 109, 41
</pre>
<p></code></p>
<p>As you can see, these libraries are all quite capable of producing nice vector-based, anti-aliased polygons with alpha blending. I have heard anecdotal evidence that AGG is faster than Cairo, but Cairo appears to be more widely used.  Aside from that I don't know why one would be preferred over the other (unless you want to get into language wars: AGG is written in C++, Cairo is written in C).  Both have bindings in a number of languages besides Python, if that's your thing.  NodeBox is still my favourite tool for noodling around in with graphics programming.  All of these are great fun, easy to use, and handy to have in your bag of tricks.</p>
<p>I tested this under OS X (required for NodeBox), using pycairo installed via fink (using fink's Python 2.5) and aggdraw installed via easy_install (using the builtin in Python 2.5).</p>
<p>Here is my test file containing all of the code above: <a href='http://livingcode.org/wp-content/uploads/2009/01/alpha_polygonspy.zip' title='Alpha polygons example code'>Alpha polygons example code</a></p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2005/is-that-a-banana-in-your-email-or-are-you-happy-to-see-me</id>
    <title type="html"><![CDATA[Is that a banana in your email, or are you happy to see me?]]></title>
    <updated>2005-02-09T21:35:05Z</updated>
    <published>2005-02-09T21:35:05Z</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/2005/02/09/is-that-a-banana-in-your-email-or-are-you-happy-to-see-me/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2005/02/09/is-that-a-banana-in-your-email-or-are-you-happy-to-see-me" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[I&#8217;ve gotten a couple of messages asking why there are strange attachments in my email which may or may not prompt you to open your security settings if you try to open them. Fear not, these are not viruses! Rather, it&#8217;s the basis of email itself if we ever want to move beyond the ocean [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2005/02/09/is-that-a-banana-in-your-email-or-are-you-happy-to-see-me"><![CDATA[<p>I&#8217;ve gotten a couple of messages asking why there are strange attachments in my email which may or may not prompt you to open your security settings if you try to open them. Fear not, these are not viruses! Rather, it&#8217;s the basis of email itself if we ever want to move beyond the ocean of spam we currently swim in.</p>
<p>First some background. When you send an email, by default there are three things which do not occur. The first is Authorization, i.e., there is no guarantee that the person you are sending the mail to is able to read it. The second is Encryption, which ensures that other people are not able to read it. The third is Authentication, proving that the mail which appears to be from me, actually is from me. None of these are present in normal email.</p>
<p>In fact, sending an email without these is like putting all of your standard (snail) mail on postcards, then having the postcards travel through the houses of random strangers until they (possibly) end up at their destination. Adding authentication, authorization, and encryption is like putting your email in an envelope.</p>
<p>So that is what the obscure attachment is in my email, it&#8217;s a digital signature, which provides some form of authentication (better than nothing). I recieved this certificate from a company called Thawte, for free, and installed it in my primary email application, Mail.app. There are very good instructions for doing this at <a href="http://www.joar.com/certificates/">http://www.joar.com/certificates/</a>. Once you have installed the certificate, signing your mail happens authomatically and transparently. The process of getting the certificate could be easier, but it&#8217;s certainly not difficult.</p>
<p>The real benefit happens when more people start doing this. See, if I have received mail from someone who also uses digital signatures, then Mail.app remembers this, and when I respond it uses their signature and my signature in combination to get the rest of the picture: Authorization and Encryption. If we can get to the point where the standard is to put messages in an envelope instead of postcards, it makes much better tools for eliminating spam available&#8211;don&#8217;t accept mail unless it is from a verifiable source. It&#8217;s not perfect, but a big improvement over the situation we have today.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2005/extending-nsbezierpath</id>
    <title type="html"><![CDATA[Extending NSBezierPath]]></title>
    <updated>2008-01-25T21:42:49Z</updated>
    <published>2005-01-29T21:36:43Z</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/2005/01/29/extending-nsbezierpath/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2005/01/29/extending-nsbezierpath" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[Yesterday I wrote about how to extend NSImage so it can save to a file. Today we&#8217;ll tackle NSBezierPath. NSBezierPath is pretty cool for drawing, but it doesn&#8217;t support arbitrary regular polygons, just rects and ovals (and lines and arcs). And there&#8217;s not an easy way to extract the points that make up a path. [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2005/01/29/extending-nsbezierpath"><![CDATA[<p>Yesterday I wrote about how to extend NSImage so it can save to a file. Today we&#8217;ll tackle NSBezierPath. NSBezierPath is pretty cool for drawing, but it doesn&#8217;t support arbitrary regular polygons, just rects and ovals (and lines and arcs). And there&#8217;s not an easy way to extract the points that make up a path. And if you could extract the points, there isn&#8217;t a way to draw dots for the points instead of stroking or filling the path. OK, enough already, let&#8217;s look at some code.</p>
<p>First thing in the code, we&#8217;ll define some basic trigonometry routines to calculate the points for a polygon. Then we&#8217;ll create the class itself.</p>
<pre class="code">from objc import Category</pre>
<pre class="code">from AppKit import NSBezierPath</pre>
<pre class="code">import math</pre>
<pre class="code">
def poly_point(center, r, degrees):</pre>
<pre class="code">    x = r * math.cos(degrees) + center[0]</pre>
<pre class="code">    y = r * math.sin(degrees) + center[1]</pre>
<pre class="code">    return x,y</pre>
<pre class="code">def polypoints(center, r, numPoints, degreesRotation=0):</pre>
<pre class="code">    if numPoints &lt; 3:</pre>
<pre class="code">        raise ValueError, 'Must have at least 3 points in a polygon'</pre>
<pre class="code">    rotation = math.radians(degreesRotation)</pre>
<pre class="code">    theta = (math.pi * 2) / numPoints</pre>
<pre class="code">    return [poly_point(center, r, i*theta+rotation)</pre>
<pre class="code">        for i in range(numPoints)]</pre>
<pre class="code">class NSBezierPath(Category(NSBezierPath)):</pre>
<pre class="code">    def points(self):</pre>
<pre class="code">        points = []</pre>
<pre class="code">        for i in range(self.elementCount()):</pre>
<pre class="code">        elem, pts = self.elementAtIndex_associatedPoints_(i)</pre>
<pre class="code">        points += pts</pre>
<pre class="code">        return points</pre>
<pre class="code">
def appendBezierPathWithPolygonWithCenter_radius_numberOfPoints_(self, center, radius, numberOfPoints):</pre>
<pre class="code">	''' Creates a regular polygon '''</pre>
<pre class="code">	pts = polypoints(center, radius, numberOfPoints) self.moveToPoint_(pts[0])</pre>
<pre class="code">	for pt in pts[1:]:</pre>
<pre class="code">		self.lineToPoint_(pt)</pre>
<pre class="code">	self.closePath()</pre>
<pre class="code">
    def dot(self):</pre>
<pre class="code">        '''</pre>
<pre class="code">        Similar to stroke: and fill:, but draws dots for each point in the</pre>
<pre class="code">        path. Dot size is based on linewidth. Not as efficient, because it</pre>
<pre class="code">        creates a separate NSBezierPath each time it is called.</pre>
<pre class="code">        '''</pre>
<pre class="code">        tmp_path = NSBezierPath.alloc().init()</pre>
<pre class="code">        width = self.lineWidth()</pre>
<pre class="code">        offset = width / 2</pre>
<pre class="code">        for point in self.points():</pre>
<pre class="code">            rect = (point[0] - offset, point[1] - offset),(width, width)</pre>
<pre class="code">            tmp_path.appendBezierPathWithOvalInRect_(rect)</pre>
<pre class="code">        tmp_path.fill()</pre>
<p>OK, hopefully the above is reasonably clear. You can follow along with any calls which are unfamiliar by firing up AppKiDo or the Apple documentation for NSBezierPath. If you&#8217;re going to use the dot: method a lot you might want to cache the path so you&#8217;re not creating a new NSBezierPath every time, it depends on what you need.</p>
<p>Here&#8217;s a short script you can run on the command line to create a hexagon and demonstrate fill:, stroke: and dot:</p>
<pre><span class="code">from AppKit import NSApplication, NSBezierPath, NSColor, NSImage</span></pre>
<pre><span class="code">from Foundation import NSInsetRect, NSMakeRect</span></pre>
<pre><span class="code">import image_ext, bezier_path_ext</span></pre>
<pre></pre>
<pre><span class="code">app = NSApplication.sharedApplication()</span></pre>
<pre><span class="code">image = NSImage.alloc().initWithSize_((64,64))</span></pre>
<pre><span class="code">image.fillWithColor_(NSColor.clearColor())</span></pre>
<pre><span class="code">image.lockFocus()</span></pre>
<pre><span class="code">hex = NSBezierPath.alloc().init()</span></pre>
<pre><span class="code">hex.appendBezierPathWithPolygonWithCenter_radius_numberOfPoints_((32,32), 26, 6)</span></pre>
<pre><span class="code">NSColor.greenColor().set()</span></pre>
<pre><span class="code">hex.fill()</span></pre>
<pre><span class="code">hex.setLineWidth_(2)</span></pre>
<pre><span class="code">NSColor.blueColor().set()</span></pre>
<pre><span class="code">hex.stroke()</span></pre>
<pre><span class="code">hex.setLineWidth_(8)</span></pre>
<pre><span class="code">NSColor.redColor().set()</span></pre>
<pre><span class="code">hex.dot()</span></pre>
<pre><span class="code">image.unlockFocus()</span></pre>
<pre><span class="code">image.writeToFilePath_('hex.png')</span></pre>
<p>Which results in this:  <img src="http://livingcode.org/images/hex1.png" height="64" width="64" /></p>
<p>Why am I so interested in points and dots? Well, they let me visualize control points for arcs for one thing. Perhaps tomorrow we can explore more along those lines.</p>
]]></content>
        </entry>
  </feed>
