<?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>klenwell press</title>
	<atom:link href="http://klenwell.com/press/feed/" rel="self" type="application/rss+xml" />
	<link>http://klenwell.com/press</link>
	<description>A Developer's Broadsheet</description>
	<lastBuildDate>Fri, 13 Jan 2012 14:51:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.2</generator>
		<item>
		<title>California Population Data</title>
		<link>http://klenwell.com/press/2011/10/cal-population-data/</link>
		<comments>http://klenwell.com/press/2011/10/cal-population-data/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 05:19:22 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Datasets]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=238</guid>
		<description><![CDATA[It&#8217;s surprisingly hard to find a simple list of annual population data for the state of California. You can find a chart on Google: But the underlying data must be extracted from several spreadsheets from the census site. So here&#8217;s a simple Python list of the annual data (1950-2010): [(1950, 10677000), (1951, 11134000), (1952, 11635000), [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s surprisingly hard to find a simple list of annual population data for the state of California. You can find a chart on <a href="http://www.google.com/publicdata/explore?ds=kf7tgg1uo9ude_&#038;ctype=l&#038;strail=false&#038;bcs=d&#038;nselm=h&#038;met_y=population&#038;scale_y=lin&#038;ind_y=false&#038;rdim=state&#038;idim=state:06000&#038;ifdim=state&#038;tstart=333270000000&#038;tend=1248418800000&#038;hl=en&#038;dl=en&#038;uniSize=0.035&#038;iconSize=0.5&#038;icfg">Google</a>:</p>
<p><iframe width="400" height="325" frameborder="0" scrolling="no" marginwidth="0" marginheight="0" src="http://www.google.com/publicdata/embed?ds=kf7tgg1uo9ude_&amp;ctype=l&amp;strail=false&amp;bcs=d&amp;nselm=h&amp;met_y=population&amp;scale_y=lin&amp;ind_y=false&amp;rdim=state&amp;idim=state:06000&amp;ifdim=state&amp;tstart=333270000000&amp;tend=1248418800000&amp;hl=en&amp;dl=en&amp;uniSize=0.035&amp;iconSize=0.5&amp;icfg"></iframe></p>
<p>But the underlying data must be extracted from several spreadsheets from the census site.</p>
<p>So here&#8217;s a simple Python list of the annual data (1950-2010):</p>
<pre class="brush: python">
[(1950, 10677000),
 (1951, 11134000),
 (1952, 11635000),
 (1953, 12251000),
 (1954, 12746000),
 (1955, 13133000),
 (1956, 13713000),
 (1957, 14264000),
 (1958, 14880000),
 (1959, 15467000),
 (1960, 15870000),
 (1961, 16497000),
 (1962, 17072000),
 (1963, 17668000),
 (1964, 18151000),
 (1965, 18585000),
 (1966, 18858000),
 (1967, 19176000),
 (1968, 19394000),
 (1969, 19711000),
 (1970, 19971069),
 (1971, 20345939),
 (1972, 20585469),
 (1973, 20868728),
 (1974, 21173865),
 (1975, 21537849),
 (1976, 21935909),
 (1977, 22352396),
 (1978, 22835958),
 (1979, 23256880),
 (1980, 23667902),
 (1981, 24285933),
 (1982, 24820009),
 (1983, 25360026),
 (1984, 25844393),
 (1985, 26441109),
 (1986, 27102237),
 (1987, 27777158),
 (1988, 28464249),
 (1989, 29218164),
 (1990, 29950111),
 (1991, 30414114),
 (1992, 30875920),
 (1993, 31147208),
 (1994, 31317179),
 (1995, 31493525),
 (1996, 31780829),
 (1997, 32217708),
 (1998, 32682794),
 (1999, 33145121),
 (2000, 33987977),
 (2001, 34479458),
 (2002, 34871843),
 (2003, 35253159),
 (2004, 35574576),
 (2005, 35827943),
 (2006, 36021202),
 (2007, 36250311),
 (2008, 36604337),
 (2009, 36961229),
 (2010, 37349363)]
</pre>
<p>And here&#8217;s a list of the raw data and its sources:</p>
<pre class="brush: python">
# raw data: (year range, raw numbers, unit/multiplier, delim, source)
    raw_data = (
        ( range(1950,1955),
          &#039;10,677   11,134   11,635  12,251   12,746&#039;,
          1000,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st5060ts.txt&#039; ),
        ( range(1955,1960),
          &#039;13,133  13,713   14,264   14,880  15,467&#039;,
          1000,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st5060ts.txt&#039; ),
        ( range(1960,1965),
          &#039;15,870   16,497   17,072   17,668   18,151&#039;,
          1000,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st6070ts.txt&#039; ),
        ( range(1965,1970),
          &#039;18,585   18,858   19,176   19,394   19,711&#039;,
          1000,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st6070ts.txt&#039; ),
        ( range(1970,1976),
          &#039;19971069  20345939  20585469  20868728  21173865  21537849&#039;,
          1,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st7080ts.txt&#039; ),
        ( range(1976,1980),
          &#039;21935909  22352396  22835958  23256880&#039;,
          1,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st7080ts.txt&#039; ),
        ( range(1980,1985),
          &#039;23667902  24285933  24820009  25360026  25844393&#039;,
          1,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st8090ts.txt&#039; ),
        ( range(1985,1990),
          &#039;26441109  27102237  27777158  28464249  29218164&#039;,
          1,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1980s/st8090ts.txt&#039; ),
        ( range(1999,1989,-1),
          &#039;33145121  32682794  32217708  31780829  31493525  31317179  31147208  30875920  30414114  29950111&#039;,
          1,
          &#039;\s+&#039;,
          &#039;http://www.census.gov/popest/archives/1990s/ST-99-07.txt&#039; ),
        ( range(2000,2011),
         &#039;&quot;33,987,977&quot;,&quot;34,479,458&quot;,&quot;34,871,843&quot;,&quot;35,253,159&quot;,&quot;35,574,576&quot;,&quot;35,827,943&quot;,&quot;36,021,202&quot;,&quot;36,250,311&quot;,&quot;36,604,337&quot;,&quot;36,961,229&quot;,&quot;37,349,363&quot;&#039;,
          1,
          &#039;,&#039;,
          &#039;http://www.census.gov/popest/intercensal/state/ST-EST00INT-01.csv&#039; ),
    )
</pre>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2011/10/cal-population-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python Timeit</title>
		<link>http://klenwell.com/press/2011/09/timeit/</link>
		<comments>http://klenwell.com/press/2011/09/timeit/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 02:53:34 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=234</guid>
		<description><![CDATA[I&#8217;m working through the lessons in the free online version Allen B. Downey&#8217;s Think Stats.One thing I like to do whenever I write code is test it. So almost as soon as I began the exercises, I added a module called testwell. Since performance is often a consideration with statistical computing, my testing module includes [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working through the lessons in the free online version Allen B. Downey&#8217;s <a href="http://greenteapress.com/thinkstats/">Think Stats</a>.One thing I like to do whenever I write code is test it. So almost as soon as I began the exercises, I added a module called testwell.</p>
<p>Since performance is often a consideration with statistical computing, my testing module includes a basic timing function called timeit. The Python standard library includes a <a href="http://docs.python.org/library/timeit.html#examples">timeit module</a>, but I don&#8217;t find it very friendly, as it creates a new process with its own separate environment. I just want a timing function that can time comparable pieces of code in the current environment. Here&#8217;s my timeit function:</p>
<pre class="brush: python">
def timeit(f, *args, **kw):
    &quot;&quot;&quot;time a function over an n number of trails:

    f1 = lambda a: a * a
    def f2(a, b):
        f1(a) + f1(b)
    def f3():
        f2(10, 20)

    USAGE:
        t1 = timeit(f1, a, n=1000)
        t2 = timeit(f2, a, b, n=1000)
        t3 = timeit(f3, n=1000)
        pprint([t1, t2, t3])
    &quot;&quot;&quot;
    n = kw.get(&#039;n&#039;, 100)
    print &#039;timing %s over %s trials&#039; % (f, n)
    t0 = time.time()
    for i in range(n):
        f(*args)

    total_time = time.time() - t0
    per_trial = total_time / n
    return &#039;%.2f (%s trials at %.6f per trial)&#039; % (total_time, n, per_trial)
</pre>
<p>It takes a function as it&#8217;s first argument, a list of arguments, and an n keyword to specify how many times to run it.</p>
<p>The pattern I like best is to enclose the operation you wish to test in a function, then just pass that with the n keyword:</p>
<pre class="brush: python">
import pprint

num_trials = 100000
f1 = lambda: Percentile(scores, 50)
f2 = lambda: iPercentile(scores, 50)
t1 = timeit(f1, n=num_trials)
t2 = timeit(f2, n=num_trials)
pprint.pprint([t1, t2])

# output
timing &lt;function &lt;lambda&gt; at 0x8950bc4&gt; over 100000 trials
timing &lt;function &lt;lambda&gt; at 0x8950bfc&gt; over 100000 trials
[&#039;0.86 (100000 trials at 0.000009 per trial)&#039;,
 &#039;0.38 (100000 trials at 0.000004 per trial)&#039;]
</pre>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2011/09/timeit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Updating Model Schema in Google App Engine</title>
		<link>http://klenwell.com/press/2011/09/updating-app-engine-model-schema/</link>
		<comments>http://klenwell.com/press/2011/09/updating-app-engine-model-schema/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 00:26:40 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[App Engine]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=228</guid>
		<description><![CDATA[Problem I have an App Engine app that keeps tracks of some tweets (&#8220;status&#8221; in the API). I decided I wanted to store the time the message was originally tweeted. So I need to update the schema of one of my models, TweetDigest, to add the new property (field). But then I also would like [...]]]></description>
			<content:encoded><![CDATA[<h4>Problem</h4>
<p>I have an App Engine app that keeps tracks of some tweets (&#8220;status&#8221; in the API). I decided I wanted to store the time the message was originally tweeted. So I need to update the schema of one of my models, TweetDigest, to add the new property (field). But then I also would like to update any existing records to include the value.</p>
<h4>Solution</h4>
<p>First things first. Let&#8217;s update the model. This is easy enough. Just add the new property to the existing model. The relevant code:</p>
<pre class="brush: python">
from project.models.twitter import TweetDigest

class TweetDigest(db.Model):
    tweet_id        = db.StringProperty(required=True, indexed=True)
    user_id         = db.StringProperty(required=True)
    screen_name     = db.StringProperty(required=True)
    text            = db.StringProperty(required=True, multiline=True)
    stored_at       = db.DateTimeProperty(auto_now_add=True)

    # new property
    tweeted_at      = db.DateTimeProperty(required=True)
</pre>
<p>That&#8217;s the easy part. Any new records will include that property. Existing records, however, will not have the property, at all. Let me emphasize that: it&#8217;s not that the new field is set to null for existing records. Existing records do not have the field at all. A couple queries in the interactive console illustrate:</p>
<pre class="brush: python">
from datetime import datetime
from google.appengine.ext import db
from pprint import pprint

print datetime.now()
count = TweetDigest.all().filter(&#039;user_image&#039;, None).count()
print count

record = TweetDigest.all().get()
pprint(record.__dict__[&#039;_entity&#039;])
</pre>
<p>Output:</p>
<pre class="brush: php">
2011-09-05 00:11:25.657055
0
{u&#039;screen_name&#039;: u&#039;klenwell&#039;,
 u&#039;stored_at&#039;: datetime.datetime(2011, 7, 6, 9, 26, 56, 757862),
 u&#039;text&#039;: u&#039;Premature optimization is the root of all evil.&#039;,
 u&#039;tweet_id&#039;: u&#039;1948390000&#039;,
 u&#039;user_id&#039;: u&#039;1820900&#039;}
</pre>
<p>So how to fix this? Well, in this case, I have to retrieve the created_at value for each status using the Twitter API then update each record. I set up an action in a special controller to do this. It queries the datastore to fetch all the existing records, the creates a task for each that will query the Twitter API, get the created_at value, and update the record in the datastore.</p>
<p>Here&#8217;s the controller code that creates the tasks:</p>
<pre class="brush: python">
def add_tweet_created_at_field(self):
    # queue settings
    queue_name = &#039;tweetdigest-schema-change&#039;
    queue_url_f = &#039;/backend/queue/store_tweet_created_at_value/%s&#039;
    queue_params = {}

    # purge queue
    self.purge_queue(queue_name)
    logging.info(&#039;purged queue: %s&#039; % (queue_name))

    # select all TweetDigest records without image_url and add to queue
    queue_count = 0
    query = TweetDigest.all()
    for digest in query:
        if digest.tweeted_at is None:
            queue_url = queue_url_f % (digest.tweet_id)
            added_task = self.queue_task(queue_url, queue_params, queue_name)
            queue_count += 1

    logging.info(&#039;queued %s TweetDigest records for update&#039; % (queue_count))

    # output
    response = {
        &#039;queued tasks&#039;          : queue_count,
    }
    self.set(&#039;data&#039;, pformat(response))
    self.render(self.default_view)
</pre>
<p>This action is runs within the <a href="http://appswell.appspot.com/">appswell framework</a>. The task code is left as an exercise for the reader.</p>
<h4>References</h4>
<p><a href="http://code.google.com/appengine/articles/update_schema.html">http://code.google.com/appengine/articles/update_schema.html</a><br />
<a href="http://stackoverflow.com/questions/7037269/check-if-a-field-is-present-in-an-entity">http://stackoverflow.com/questions/7037269/check-if-a-field-is-present-in-an-entity</a><br />
<a href="http://appswell.appspot.com/">http://appswell.appspot.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2011/09/updating-app-engine-model-schema/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google App Engine Memcache Limits</title>
		<link>http://klenwell.com/press/2011/06/memcache-limit/</link>
		<comments>http://klenwell.com/press/2011/06/memcache-limit/#comments</comments>
		<pubDate>Mon, 20 Jun 2011 21:46:59 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[App Engine]]></category>
		<category><![CDATA[Code Case]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=222</guid>
		<description><![CDATA[Problem If you attempt to store an object more than approximately 1 MB in size using memcache in the Google App Engine, it will give a ValueError, something like this: ValueError: Values may not be more than 1000000 bytes in length; received 1088171 bytes Solution I&#8217;ve added a library to my Appswell framework that allows [...]]]></description>
			<content:encoded><![CDATA[<h4>Problem</h4>
<p>If you attempt to store an object more than approximately 1 MB in size using memcache in the Google App Engine, it will give a ValueError, something like this:</p>
<p><code>ValueError: Values may not be more than 1000000 bytes in length; received 1088171 bytes</code></p>
<h4>Solution</h4>
<p>I&#8217;ve added a library to my Appswell framework that allows you to get around this limit by serializing an object into multiple strings and storing these along with an index object that stores the key.</p>
<p><strong>Usage Example:</strong></p>
<pre class="brush: python">
import multicache as memcache

# cache params
cache_data = some_large_nested_dict
cache_key = &#039;test_multicache&#039;
cache_len = 60

# save data
memcache.set(cache_key, cache_data, cache_len)

# retrieve data
retrieved_data = memcache.get(cache_key)
</pre>
<p>The module can be easily extracted from the framework. See these links for additional details:</p>
<p>source code: <a href="http://code.google.com/p/appswell/source/browse/appspot/lib/multicache.py">http://code.google.com/p/appswell/source/browse/appspot/lib/multicache.py</a><br />
wiki page: <a href="http://klenwell.com/is/AppengineMulticache">http://klenwell.com/is/AppengineMulticache</a></p>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2011/06/memcache-limit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Julian Day in Python</title>
		<link>http://klenwell.com/press/2011/05/julian-day-in-python/</link>
		<comments>http://klenwell.com/press/2011/05/julian-day-in-python/#comments</comments>
		<pubDate>Wed, 11 May 2011 03:20:58 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=218</guid>
		<description><![CDATA[Needed this today at work. Turned out to be much easier than I anticipated: from datetime import datetime julianday = &#039;%d%03d&#039; % (datetime.now().timetuple().tm_year, datetime.now().timetuple().tm_yday)]]></description>
			<content:encoded><![CDATA[<p>Needed this today at work. Turned out to be much easier than I anticipated:</p>
<pre class="brush: python">
from datetime import datetime
julianday = &#039;%d%03d&#039; % (datetime.now().timetuple().tm_year,
    datetime.now().timetuple().tm_yday)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2011/05/julian-day-in-python/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python Unit Testing Preamble</title>
		<link>http://klenwell.com/press/2011/04/python-unit-testing-preamble/</link>
		<comments>http://klenwell.com/press/2011/04/python-unit-testing-preamble/#comments</comments>
		<pubDate>Sat, 23 Apr 2011 18:18:38 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=214</guid>
		<description><![CDATA[A little trick I just came up with for command line unit test output. It will print the docstring for the module at the beginning of your unit test. Use this code at the bottom of your unit test file: # # MAIN # if __name__ == &#34;__main__&#34;: print sys.modules[globals()[&#039;__name__&#039;]].__doc__ # print module doc suite [...]]]></description>
			<content:encoded><![CDATA[<p>A little trick I just came up with for command line unit test output. It will print the docstring for the module at the beginning of your unit test. Use this code at the bottom of your unit test file:</p>
<pre class="brush: python">
#
# MAIN
#
if __name__ == &quot;__main__&quot;:
    print sys.modules[globals()[&#039;__name__&#039;]].__doc__    # print module doc
    suite = unittest.TestLoader().loadTestsFromTestCase(YourTestClassHere)
    unittest.TextTestRunner(verbosity=2).run(suite)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2011/04/python-unit-testing-preamble/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Forcing /etc/cron.d to Reload on Ubuntu</title>
		<link>http://klenwell.com/press/2010/11/cron-d/</link>
		<comments>http://klenwell.com/press/2010/11/cron-d/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 03:22:53 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Miscellany]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=211</guid>
		<description><![CDATA[There are two options for scheduling a script with cron on linux. Either edit the crontab: $ sudo crontab -e Or link a cron file to /etc/cron.d: $ sudo ln -sv /home/klenwell/crons/my.cron /etc/cron.d/mycron I like option two because it provides a more modular and organized way to enable cron tasks for various projects. The only [...]]]></description>
			<content:encoded><![CDATA[<p>There are two options for scheduling a script with cron on linux. Either edit the crontab:</p>
<pre class="brush: bash">
$ sudo crontab -e
</pre>
<p>Or link a cron file to /etc/cron.d:</p>
<pre class="brush: bash">
$ sudo ln -sv /home/klenwell/crons/my.cron /etc/cron.d/mycron
</pre>
<p>I like option two because it provides a more modular and organized way to enable cron tasks for various projects. The only problem with this method is that, when things go wrong, it&#8217;s been a huge headache trying to figure out what the problem is and how to get the tasks in the linked cron file running again. The cron documentation and Google are frustratingly tight-lipped on the subject of /etc/cron.d. But I think I have figured out a reliable way to configure and trouble /etc/cron.d.</p>
<p>Some rules that will help in using /etc/cron.d:</p>
<ol>
<li>You must specify a user in your cron file.</li>
<li>The script being linked must be owned by root (giving root permission alone doesn&#8217;t seem enough)</li>
<li>To force /etc/cron.d to reload, touch the /etc/cron.d dir: <code>sudo touch /etc/cron.d/</code></li>
</ol>
<p>I was able to confirm these rules by linking a cron file to /etc/cron.d, then changing the owner to myself (klenwell), then checking the /var/log/syslog file.</p>
<p>Cron checks /etc/cron.d minutely, so you have to give it at least 60 seconds to register any changes. I set up my test cron file (/home/klenwell/crons/my.cron) to touch a file in /tmp (/tmp/crontest) every minute. </p>
<p>When the cron file is owned by my user (klenwell), I see this message in the log:</p>
<pre class="brush: bash">
Nov 26 02:55:01 myserver cron[1924]: (*system*mycron) WRONG FILE OWNER (/etc/cron.d/mycron)
</pre>
<p>The linked cron file will not run again until the owner is corrected and the directory touched: </p>
<pre class="brush: bash">
$ sudo chown -v root /home/klenwell/crons/my.cron
$ sudo touch /etc/cron.d/
</pre>
<p>After this, I see this in /var/log/syslog:</p>
<pre class="brush: bash">
Nov 26 02:57:01 myserver CRON[21170]: (klenwell) CMD (   touch /tmp/crontest)
</pre>
<p>Took me a lot of trial and error to figure this out. Hope it saves your an extra headache or two.</p>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2010/11/cron-d/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get for Python Lists</title>
		<link>http://klenwell.com/press/2010/11/get-for-python-lists/</link>
		<comments>http://klenwell.com/press/2010/11/get-for-python-lists/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 04:56:15 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Stupid Lambda Tricks]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=201</guid>
		<description><![CDATA[With python&#8217;s dictionary objects, you have the useful get method: &#62;&#62;&#62; d = {&#039;a&#039;:1, &#039;b&#039;:2, &#039;c&#039;:3} &#62;&#62;&#62; d.get(&#039;a&#039;) 1 &#62;&#62;&#62; d.get(&#039;d&#039;, &#039;not found&#039;) &#039;not found&#039; Sometimes, I find something like this would be useful for lists, using the list&#8217;s index in place of the dict&#8217;s key: &#62;&#62;&#62; l = [0,1,2,3] &#62;&#62;&#62; l.get(2) Traceback (most recent [...]]]></description>
			<content:encoded><![CDATA[<p>With python&#8217;s dictionary objects, you have the useful <a href="http://docs.python.org/release/2.5.2/lib/typesmapping.html">get</a> method:</p>
<pre class="brush: python">
&gt;&gt;&gt; d = {&#039;a&#039;:1, &#039;b&#039;:2, &#039;c&#039;:3}
&gt;&gt;&gt; d.get(&#039;a&#039;)
1
&gt;&gt;&gt; d.get(&#039;d&#039;, &#039;not found&#039;)
&#039;not found&#039;
</pre>
<p>Sometimes, I find something like this would be useful for lists, using the list&#8217;s index in place of the dict&#8217;s key:</p>
<pre class="brush: python">
&gt;&gt;&gt; l = [0,1,2,3]
&gt;&gt;&gt; l.get(2)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
AttributeError: &#039;list&#039; object has no attribute &#039;get&#039;
</pre>
<p>Here&#8217;s a quick lambda that accomplishes that:</p>
<pre class="brush: python">
list_get = lambda l,i,a=False: (len(l) &lt;= i and a) or (len(l) &gt; i and l[i])
</pre>
<p>Usage:</p>
<pre class="brush: python">
&gt;&gt;&gt; list_get = lambda l,i,a=False: (len(l) &lt;= i and a) or (len(l) &gt; i and l[i])
&gt;&gt;&gt; my_list = [0,False,None,3]
&gt;&gt;&gt; list_get(my_list,0)
0
&gt;&gt;&gt; list_get(my_list,1)
False
&gt;&gt;&gt; list_get(my_list,2)  # returns None
&gt;&gt;&gt; list_get(my_list,3)
3
&gt;&gt;&gt; list_get(my_list,4)
False
&gt;&gt;&gt; list_get(my_list,4,0)  # Note: returns False instead of 0
False
&gt;&gt;&gt; list_get(my_list,4,1)
1
</pre>
<p>It&#8217;s not perfect. Be careful with False-equivalent values in the alt parameters as noted above. But otherwise it should work for most practical cases were such usage is desired.</p>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2010/11/get-for-python-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Arcade Fire Website</title>
		<link>http://klenwell.com/press/2010/10/google-arcade-fire/</link>
		<comments>http://klenwell.com/press/2010/10/google-arcade-fire/#comments</comments>
		<pubDate>Sat, 09 Oct 2010 21:24:49 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Code Case]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=193</guid>
		<description><![CDATA[The Google Arcade Fire HTML5 demo is cool, but the code is surprisingly simple: from google import WebApp, Predict, Users, Maps, Html5, NsaProxy user = Users.lookup_by_existing_cookies_and_ip() address = Predict.get_address(&#039;Enter the address where you grew up:&#039;) data_raper = NsaProxy.init(user, address) try: map = Maps.load_data(address) if map.context == &#039;urban&#039;: kid = Html5.load_urban_kid() else: kid = Html5.load_suburban_kid() video [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://thewildernessdowntown.com/">Google Arcade Fire HTML5 demo</a> is cool, but the code is surprisingly simple:</p>
<pre class="brush: python">
from google import WebApp, Predict, Users, Maps, Html5, NsaProxy

user = Users.lookup_by_existing_cookies_and_ip()
address = Predict.get_address(&#039;Enter the address where you grew up:&#039;)
data_raper = NsaProxy.init(user, address)

try:
    map = Maps.load_data(address)

    if map.context == &#039;urban&#039;:
        kid = Html5.load_urban_kid()
    else:
        kid = Html5.load_suburban_kid()

    video = WebApp.play(Html5.load_videos(kid, map))

    while video.playing():
        data_raper.rapes_your_personal_data()

except Html5.MovieOver:
    WebApp.redirect_to_launchpage()
except:
    WebApp.redirect_to_chrome_required_page()
</pre>
<p>Great album, by the way.</p>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2010/10/google-arcade-fire/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Inception</title>
		<link>http://klenwell.com/press/2010/08/inception/</link>
		<comments>http://klenwell.com/press/2010/08/inception/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 02:35:29 +0000</pubDate>
		<dc:creator>klenwell</dc:creator>
				<category><![CDATA[Criticism]]></category>

		<guid isPermaLink="false">http://klenwell.com/press/?p=187</guid>
		<description><![CDATA[That said: WTF? We've got to bring down a company on the verge of being The Most Powerful Corporation in the World. So let's use this highly radical, unproven and improbable, voodoo-science inception approach.]]></description>
			<content:encoded><![CDATA[<p>Saw <em>Inception</em> recently.  First movie I&#8217;ve seen in months.  My micro-review, originally posted on <a href="http://news.ycombinator.com/item?id=1566992">Hacker News</a>:</p>
<blockquote><p>The it&#8217;s-all-a-dream interpretation is the only one that makes sense from a science-fiction point-of-view, however unsatisfying it is from a critical perspective. The slightly wobbling top at the end points, rather overtly, to the real answer: it&#8217;s meant to be ambiguous.</p>
<p>That said: WTF? We&#8217;ve got to bring down a company on the verge of being The Most Powerful Corporation in the World. So let&#8217;s use this highly radical, unproven and improbable, voodoo-science inception approach. Oh, and by the way, we have to plant a mole within the highest ranks of the multinational beast within the next, say, two weeks, so we can get valuable information that is necessary to penetrate and manipulate the fragile psyche of our target.</p>
<p>Cut-scene: it&#8217;s done. This is logic that only makes sense within the context of a dream. The sort of dream Coleridge, or Rube Goldberg, would have.</p>
<p>Science generally favors the application of Occam&#8217;s Razor: buy the airline and crash the damn plane with the kid on it. Or just send in the ninjas. The ensuing infighting among the various executive factions vying for the top spot after junior is out of the picture will ensure that any plans Acme Energy Inc had for world domination are put off course indefinitely.</p>
<p>Inception was entertaining. But Memento was a more interesting film intellectually. That&#8217;s a film that truly merited this kind of philosophical scrutiny. Remember Sammy Jankis.</p></blockquote>
<p>This was in support of the basic premise: <a href="http://blog.samstokes.co.uk/post/890499536/inception-isnt-science-fiction-spoilers">Inception isn’t science fiction</a></p>
]]></content:encoded>
			<wfw:commentRss>http://klenwell.com/press/2010/08/inception/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

