<?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>Discretized Continuity</title>
	<atom:link href="http://davidshimel.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://davidshimel.com</link>
	<description>programming by David Shimel</description>
	<lastBuildDate>Sat, 23 Mar 2013 18:41:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>New Consulting Gig</title>
		<link>http://davidshimel.com/new-consulting-gig/</link>
		<comments>http://davidshimel.com/new-consulting-gig/#comments</comments>
		<pubDate>Sat, 23 Mar 2013 18:41:12 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=264</guid>
		<description><![CDATA[I&#8217;m happy to announce that, in part thanks to this blog, I&#8217;ve inked my first freelance software consulting contract! I&#8217;ll be working with Stratbridge LLC doing dynamic pricing for sporting and theatrical events.]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m happy to announce that, in part thanks to this blog, I&#8217;ve inked my first freelance software consulting contract! I&#8217;ll be working with <a href="http://www.stratbridge.com/">Stratbridge LLC</a> doing dynamic pricing for sporting and theatrical events.</p>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/new-consulting-gig/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reverse Engineering OKCupid</title>
		<link>http://davidshimel.com/reverse-engineering-okcupid/</link>
		<comments>http://davidshimel.com/reverse-engineering-okcupid/#comments</comments>
		<pubDate>Mon, 04 Mar 2013 00:12:09 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[http requests]]></category>
		<category><![CDATA[okc]]></category>
		<category><![CDATA[okcupid]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[reverse engineering]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=188</guid>
		<description><![CDATA[If you&#8217;ve ever seen bots on reddit like qkme_transcriber, you may wonder how they&#8217;re able to make posts without human intervention. Well wonder no longer! By examining how OKCupid handles HTTP requests, I&#8217;ll show you how to first deconstruct the undocumented APIs of other sites, then manipulate them with nary a mouse click. Our weapons &#8230; <a href="http://davidshimel.com/reverse-engineering-okcupid/" class="more-link">Continue reading <span class="meta-nav">&#187;</span></a>]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;ve ever seen bots on <a href="http://www.reddit.com/">reddit</a> like <a href="http://www.reddit.com/user/qkme_transcriber">qkme_transcriber</a>, you may wonder how they&#8217;re able to make posts without human intervention. Well wonder no longer! By examining how <a href="http://www.okcupid.com/">OKCupid</a> handles HTTP requests, I&#8217;ll show you how to first deconstruct the undocumented <a href="http://en.wikipedia.org/wiki/Application_programming_interface">APIs</a> of other sites, then manipulate them with nary a mouse click.</p>
<p><span id="more-188"></span></p>
<p>Our weapons of choice will be Python and the debugger in the Chrome web browser. To access the Chrome Debugger, hit F12 or Ctrl+Shift+J. This tool gives you a wealth of information about the interactions between your browser and the sites you visit, but for this task we&#8217;re mainly concerned with what&#8217;s going on in the Network tab. If you&#8217;re more of a Firefox person, you can use an extension called <a href="https://getfirebug.com/">Firebug</a>. Incidentally, the lead developer of Firebug was <a href="https://groups.google.com/forum/#!topic/firebug-working-group/GNCZeL1eWq8">hired by Google</a> to develop the Chrome Debugger. For this post I&#8217;m going to assume you&#8217;re using Chrome.</p>
<p>Since our goal is to programmatically perform actions on the site, you need to make an OKC account (I recommend using a temporary email service like <a href="http://10minutemail.davidxia.com/">this one</a> to avoid spam). The next step is to figure out how to log in using Python. So, turn on the Chrome Debugger, go to the Network tab, log out of OKC, and log in again. You&#8217;ll see a bunch of stuff appear in the debugger, but what we want is all the way at the top, so scroll up there and click the the link named &#8220;login&#8221;. That will bring up a bunch of helpful information about the request we made to OKC&#8217;s servers when we clicked &#8220;Sign in&#8221;.</p>
<div id="attachment_191" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/03/okc_login.png"><img class="size-medium wp-image-191" alt="OKCupid Login in Chrome Debugger" src="http://davidshimel.com/wp-content/uploads/2013/03/okc_login-300x239.png" width="300" height="239" /></a><p class="wp-caption-text">Mmm, data</p></div>
<p>At the top, we can see the Request URL: https://www.okcupid.com/login. Also useful is the Request Method, POST. Under the Request Headers section, there&#8217;s a field called &#8220;Cookie&#8221; which has a bunch of random-looking stuff in it. This tells us that OKC sets a <a href="http://en.wikipedia.org/wiki/HTTP_cookie">cookie</a> on your browser, so we&#8217;ll need to make sure our code uses it. Finally, there&#8217;s another section called &#8220;Form Data&#8221; containing all of the information that our computer sent to the server when we signed in. Specifically, we can see our login credentials, &#8220;username&#8221; and &#8220;password&#8221;, along with something called &#8220;dest&#8221; that has the value &#8220;/home&#8221;. Looking at our browser&#8217;s URL bar, we can deduce that the &#8220;dest&#8221; parameter denotes the path to the resource in the okcupid domain to which our browser will be redirected after the login request is completed.</p>
<p>So how do we log in using Python? It&#8217;s easy using the <a href="http://docs.python-requests.org/en/latest/">Requests library</a>:</p>
<pre class="brush: python; title: ; notranslate">import requests

sesh = requests.Session()

credentials = {'username': 'okc_account_name', 'password': 'account_pword', 'dest': '/home'}
login_resp = sesh.post('https://www.okcupid.com/login', data=credentials)

print login_resp.content
</pre>
<p>We start by instantiating a Session object which will store the cookies necessary for making future requests to OKC that require authentication. Then, we create a dictionary containing the POST data needed for the login request (fill in your own username and password). Last, we make the POST request from within the Session, passing in the login URL and the credentials. If you store the output of <b>print login_resp.content</b> in an HTML file and open it in your browser, you&#8217;ll see the OKC welcome page for your account. Success!</p>
<p>Now let&#8217;s try something a bit trickier: sending a message. Go back to OKCupid with the debugger open and click the Messages tab on the left toolbar. In the Network section of the debugger there will be a request called &#8220;messages&#8221;. If you look at the Headers of that request, you&#8217;ll see that the Request URL is http://www.okcupid.com/messages and the Request Method is GET. Assuming you&#8217;ve run the login code aove, we can replicate this in Python as follows:</p>
<pre class="brush: python; title: ; notranslate">get_messages = sesh.get('http://www.okcupid.com/messages')</pre>
<p>If you haven&#8217;t deleted it, there should be a message from the user &#8220;chriscoyne&#8221; in your Received Messages. Since that account apparently doesn&#8217;t respond to messages, it&#8217;s a good test subject for cracking the OKC API. If you click on his message, you&#8217;ll get another request in your debugger that looks like this:</p>
<div id="attachment_222" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/03/okc_msg_thread.png"><img class="size-medium wp-image-222" alt="Hi Chris!" src="http://davidshimel.com/wp-content/uploads/2013/03/okc_msg_thread-300x65.png" width="300" height="65" /></a><p class="wp-caption-text">Hi Chris!</p></div>
<p>The text following the question mark after &#8220;messages&#8221; is called a <a href="http://en.wikipedia.org/wiki/Query_string">query string</a>, and it allows you to send additional information to an HTTP server. We can set these values in Python in a way similar to our POST request above:</p>
<pre class="brush: python; title: ; notranslate">thread_data = {'readmsg': 'true', 'threadid': 7054982370615456828, 'folder': 1}
get_thread = sesh.get('http://www.okcupid.com/messages', params=thread_data)
</pre>
<p>If you want to avoid manually determining the thread IDs for OKCupid messages, there&#8217;s a great HTML parsing library called <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a>. I&#8217;ll talk more about scraping web pages in a future post.</p>
<p>Now, send a message to chriscoyne and check out what the debugger gives you.</p>
<div id="attachment_228" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/03/okc_send_msg.png"><img class="size-medium wp-image-228" alt="I swear" src="http://davidshimel.com/wp-content/uploads/2013/03/okc_send_msg-300x86.png" width="300" height="86" /></a><p class="wp-caption-text">I swear</p></div>
<p>So, we have to make another POST request. But you know what to do!</p>
<pre class="brush: python; title: ; notranslate">msg_data = {'ajax': 1, 'sendmsg': 1, 'r1': 'chriscoyne', 'body': 'messager? but i hardly know her!',
'threadid': 7054982370615456828,
'authcode': '1,0,1362399999,0xdb8d1bb0ffffffff;aa5242512122943168ddffffffffffffffffffff', 'reply': 1}
send_msg = sesh.post('http://www.okcupid.com/mailbox', data=msg_data)
</pre>
<p>If you go back to the message thread in your browser, you&#8217;ll see the message you just sent from your script. To avoid having to send a test message to figure out what the value for authcode should be, you can right click on the message box in Chrome and select &#8220;Inspect element&#8221; from the drop-down menu. You should see the authcode a few HTML elements above the element for the message box:</p>
<div id="attachment_239" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/03/okc_msg_authcode.png"><img class="size-medium wp-image-239" alt="Not so hidden eh?" src="http://davidshimel.com/wp-content/uploads/2013/03/okc_msg_authcode-300x151.png" width="300" height="151" /></a><p class="wp-caption-text">Not so hidden eh?</p></div>
<p>OKC seems to change the authcode at certain intervals as a security measure, so in a production system you&#8217;d need to dynamically grab the value before you send a message (which you can do with Beautiful Soup).</p>
<p>So there you have it! Hopefully this post has helped you get started reverse engineering other website APIs. If you need help, don&#8217;t hesitate to leave a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/reverse-engineering-okcupid/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Blackjack in jQuery</title>
		<link>http://davidshimel.com/blackjack-in-jquery/</link>
		<comments>http://davidshimel.com/blackjack-in-jquery/#comments</comments>
		<pubDate>Fri, 22 Feb 2013 05:01:52 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[blackjack]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=181</guid>
		<description><![CDATA[Just a quick post, here&#8217;s a version of Blackjack I made using jQuery, HTML, and JavaScript. Codecademy helped me a lot when I started learning JavaScript and jQuery. In the later lessons when the programming challenges get more complicated, their solution verifier gets a bit finicky. But, if you&#8217;re just starting from the beginning it&#8217;s &#8230; <a href="http://davidshimel.com/blackjack-in-jquery/" class="more-link">Continue reading <span class="meta-nav">&#187;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Just a quick post, here&#8217;s a version of Blackjack I made using jQuery, HTML, and JavaScript. <a href="http://www.codecademy.com/">Codecademy</a> helped me a lot when I started learning JavaScript and jQuery. In the later lessons when the programming challenges get more complicated, their solution verifier gets a bit finicky. But, if you&#8217;re just starting from the beginning it&#8217;s a great resource. Now . . .<br />
<a href="http://davidshimel.com/assets/blackjack/blackjack.html">Play Blackjack!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/blackjack-in-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conway&#8217;s Game of Life in Processing.js</title>
		<link>http://davidshimel.com/conways-game-of-life-in-processing-js/</link>
		<comments>http://davidshimel.com/conways-game-of-life-in-processing-js/#comments</comments>
		<pubDate>Tue, 19 Feb 2013 00:23:34 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[conway's game of life]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[processing]]></category>
		<category><![CDATA[processingjs]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=159</guid>
		<description><![CDATA[I first learned about Processing at Maker Faire in 2011. I don&#8217;t consider myself a visual artist, but Processing made it straightforward to create beautiful graphics using code. However, I didn&#8217;t want to go through the hassle of working with the Processing IDE, so I set it aside for a couple years. Recently, I came &#8230; <a href="http://davidshimel.com/conways-game-of-life-in-processing-js/" class="more-link">Continue reading <span class="meta-nav">&#187;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I first learned about <a href="http://processing.org/">Processing</a> at <a href="http://makerfaire.com/">Maker Faire</a> in 2011. I don&#8217;t consider myself a visual artist, but Processing made it straightforward to create beautiful graphics using code. However, I didn&#8217;t want to go through the hassle of working with the Processing IDE, so I set it aside for a couple years.</p>
<p>Recently, I came across <a href="http://processingjs.org/">Processing.js</a> and decided to give it another shot. By porting it to JavaScript, the developers have made it easier to get started and publish to the web (though I would guess that the JavaScript version runs slower than native Processing). All I needed was a project.</p>
<p><span id="more-159"></span></p>
<p>Naturally, I chose to implement <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway&#8217;s Game of Life</a>. First publicized in 1970, it has fascinated many over the years due to the complexity of patterns that it produces based on a few simple rules. YouTube is full of videos depicting this cellular automaton; one of my favorites is <a href="http://www.youtube.com/watch?v=r_vSszwGgEY">this one</a> taken of an installation on the Boston Greenway that I got to see in person. For <em>Inception</em>-level brain melting, there&#8217;s <a href="http://www.youtube.com/watch?v=QtJ77qsLrpw">Game of Life in Game of Life</a>. My favorite among the common patterns that arise is the <a href="http://en.wikipedia.org/wiki/File:Game_of_life_animated_glider.gif">glider</a> since it always seems like it&#8217;s on a mission.</p>
<p>So here it is! You can reset the game by clicking anywhere on it, or you can wait five minutes and it will reset itself. I experimented with some crazier color shifting patterns as I was developing it, but I settled on a subtly undulating rainbow that I think would make for a good screen saver. Besides increasing performance to allow for a grid with more cells, the code could also be improved by adding a method for determining when the game has reached a steady state. One way would be to cache the previous few generations and compare the current generation against them, but computationally that could have a terrible worst-case performance. I&#8217;m open to suggestions! The source code is available <a href="http://davidshimel.com/assets/processing/conway.js">here</a>.</p>
<p><canvas id="conway" data-processing-sources="http://davidshimel.com/assets/processing/conway.js"></canvas></p>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/conways-game-of-life-in-processing-js/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Approximating Pi in Python, Part 2</title>
		<link>http://davidshimel.com/approximating-pi-in-python-part-2/</link>
		<comments>http://davidshimel.com/approximating-pi-in-python-part-2/#comments</comments>
		<pubDate>Mon, 11 Feb 2013 00:42:27 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=99</guid>
		<description><![CDATA[In my last post, I discussed a method for approximating π which I later learned was a Monte Carlo method, thanks to some helpful Redditors. Today I&#8217;ll talk about technique that uses numerical integration (specifically, the rectangle method) to produce a more accurate result in less time. We&#8217;ll again start with a square with an inscribed &#8230; <a href="http://davidshimel.com/approximating-pi-in-python-part-2/" class="more-link">Continue reading <span class="meta-nav">&#187;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://davidshimel.com/approximating-pi-in-python-part-1/">In my last post</a>, I discussed a method for approximating π which I later learned was a <a href="http://en.wikipedia.org/wiki/Monte_Carlo_method">Monte Carlo method</a>, thanks to some helpful Redditors. Today I&#8217;ll talk about technique that uses numerical integration (specifically, the <a href="http://en.wikipedia.org/wiki/Rectangle_method">rectangle method</a>) to produce a more accurate result in less time.<span id="more-99"></span></p>
<p>We&#8217;ll again start with a square with an inscribed quarter circle:</p>
<p><a href="http://davidshimel.com/wp-content/uploads/2013/02/quarter-circle.png"><img class="size-medium wp-image-100 aligncenter" alt="quarter circle" src="http://davidshimel.com/wp-content/uploads/2013/02/quarter-circle-300x289.png" width="300" height="289" /></a></p>
<p>Recall from last time that π = 4<em>A<sub>c</sub></em>/<em>A<sub>sq</sub></em>, where <em>A<sub>c</sub></em> is the area of the quarter circle and <em>A<sub>sq</sub></em> is the area of the square. Rather than randomly place an arbitrary number of points on the figure and then determine the ratio of points inside the circular sector to total points, we can calculate the exact discretized area of the sector (thus approximating the true area of the sector) and divide by the exact area of the square.</p>
<p>To do so, let <em>r</em> be an arbitrarily large integer. A priori, we know that <em>A<sub>sq</sub></em> = <em>r<sup>2</sup></em>. We could then iterate over all <em>r<sup>2</sup></em> points and determine the total number of points that fulfill the inequality <em>x<sup>2</sup></em> + <em>y<sup>2</sup></em> ≤ <em>r<sup>2</sup></em>. But is there a better way? You bet!</p>
<p>If we zoom in on the sector, we can see that the curve of the circle is not perfectly smooth; instead, it moves in discrete steps going down and to the right.</p>
<p><a href="http://davidshimel.com/wp-content/uploads/2013/02/discretized-circle.png"><img class="size-medium wp-image-110 aligncenter" alt="discretized circle" src="http://davidshimel.com/wp-content/uploads/2013/02/discretized-circle-297x300.png" width="297" height="300" /></a></p>
<p><i><br />
</i>So, we can describe the area of the sector as a collection of <em>r</em> rectangles, each with width 1, whose heights are given by <em>y</em> = √(<em>r<sup>2</sup></em> &#8211; <em>x<sup>2</sup></em>), where { <em>x</em> | <em>x</em> ∈ <strong>Z</strong><sup>+</sup>, 0 ≤ <em>x</em> ≤ <em>r</em> }. By summing all values of <em>y</em> generated by this domain, we are essentially using the rectangle method of numerical integration to calculate the sector&#8217;s area. Best of all, this technique is linear in <em>r</em>, making it much faster than examining every single point for membership in the circle.<i><br />
</i></p>
<p>As far as coding goes, we could write the algorithm iteratively . . .</p>
<pre class="brush: python; title: ; notranslate">def outside_circle(x, y, r):
	return x**2 + y**2 &gt; r**2

def circle_area(r): # numerically integrate using the rectangle rule with delta = 1
	x, y = 0, r # start at top of circle
	circle_area = 0
	# if x == r, y (the height) will be 0, so this point will contribute nothing to the circle area
	while x &lt; r: # go 90 degrees around the circle clockwise
		while outside_circle(x, y, r):
			y -= 1
		circle_area += y # add the current slice to the area
		x += 1
	return circle_area</pre>
<p>. . . but that wouldn&#8217;t be very Pythonic. Instead, we can use a <a href="http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions">list comprehension</a> combined with the <a href="http://docs.python.org/2/library/functions.html#sum">sum()</a> function:</p>
<pre class="brush: python; title: ; notranslate">def calculate_height(x, r):
	return math.floor(math.sqrt(r**2 - x**2))

def circle_area(r):
	return sum(calculate_height(x, r) for x in xrange(r))</pre>
<p>How concise! Note the use of <a href="http://docs.python.org/2/library/functions.html#xrange">xrange()</a> rather than <a href="http://docs.python.org/2/library/functions.html#range">range()</a>. Because xrange() yields values of the sequence as needed rather than constructing the entire list up front, the program requires less memory to execute. For example, with <em>r</em> = 3,500,000, range() caused Python to use 137,812 KB of memory. Substituting xrange() lowered memory consumption to 26,280 KB, a decrease of nearly 81%! (I&#8217;m using Python 2.7.3 here. In Python 3, range() <a href="http://stackoverflow.com/a/135114">behaves like an iterator</a>, so you should get similar memory performance to xrange().)</p>
<p>The list comprehension expression of the algorithm also executes much faster than the iterative version. With <em>r</em> = 10,000,000, the iterative program took 83 seconds to complete, while the list comprehension script finished in only 31 seconds, a 63% improvement. This experiment demonstrates the difference between <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative</a> (procedural) and <a href="http://en.wikipedia.org/wiki/Declarative_programming">declarative</a> (functional) programming styles. Python provides good support for either paradigm, but declarative expressions tend to be more idiomatic. With modern programming languages, it&#8217;s generally better to describe the result that you want (using, e.g., a list comprehension) rather than prescribing the exact steps to compute it since the language can usually optimize the computation better than a human.</p>
<p>Finally, let&#8217;s compare this method to our Monte Carlo simulation. With <em>N</em> = 50,000,000, the Monte Carlo script gave π = 3.14153067417 in 65.626 seconds using 4,636 KB of memory. To normalize on running time, we can use <em>r</em> = 21,366,107 for the numerical integration program, yielding π = 3.14159265357 in 65.525 seconds consuming 26,264 KB. Though the Monte Carlo method needed 82% less RAM, it produced an experimental error of 6.19794e-5 (1.972865e-3%) while requiring almost 2.5 times as many operations as numerical integration. Integration was six orders of magnitude more accurate (experimental error of 1.00000e-11 or 3.183099e-12%).</p>
<p>Additionally, the Monte Carlo simulation will produce a different approximation for π every time depending on what points are randomly generated. Numerical integration gives the same answer every time, so one doesn&#8217;t need to employ statistical methods to reason about the convergence of that algorithm.</p>
<p>Here&#8217;s the complete code for the numerical integration solution:</p>
<pre class="brush: python; title: ; notranslate">import sys
import math
from datetime import datetime as dt

def timedelta_to_microseconds(td): # http://stackoverflow.com/a/2416049
	return td.microseconds + (td.seconds + td.days * 86400) * 1000000.0

def calculate_height(x, r):
	# we could use an integer square root algorithm, e.g.
	# http://code.activestate.com/recipes/577821-integer-square-root-function/
	# that method is slower but will work for very large values of r
	return math.floor(math.sqrt(r**2 - x**2))

def circle_area(r): # numerically integrate using the rectangle rule with delta = 1
	return sum(calculate_height(x, r) for x in xrange(r))

def calculate_pi(r):
	return (4.0 * circle_area(r)) / r**2

radius = int(sys.argv[1])

before = dt.now()
pi = calculate_pi(radius)
elapsed = dt.now() - before

print 'pi = ' + str(pi)
print 'time elapsed: ' + str(elapsed)
print 'microseconds per operation: ' + str(timedelta_to_microseconds(elapsed)/(radius))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/approximating-pi-in-python-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Approximating Pi in Python, Part 1</title>
		<link>http://davidshimel.com/approximating-pi-in-python-part-1/</link>
		<comments>http://davidshimel.com/approximating-pi-in-python-part-1/#comments</comments>
		<pubDate>Sun, 03 Feb 2013 00:15:11 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[pi]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=46</guid>
		<description><![CDATA[Consider a square with an inscribed circle of radius r which itself has an inscribed square rotated 45 degrees. If we look at just the first quadrant, then the area of the outermost square Aouter is r2. The area of the circle Acircle is πr2/4, and the area of the inner triangle Atriangle is r2/2. Therefore, we can &#8230; <a href="http://davidshimel.com/approximating-pi-in-python-part-1/" class="more-link">Continue reading <span class="meta-nav">&#187;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Consider a square with an inscribed circle of radius <em>r</em> which itself has an inscribed square rotated 45 degrees. <a href="http://davidshimel.com/wp-content/uploads/2013/02/square-inside-circle-inside-square.png"><img class="size-medium wp-image-47 aligncenter" alt="square inside circle inside square" src="http://davidshimel.com/wp-content/uploads/2013/02/square-inside-circle-inside-square-300x300.png" width="300" height="300" /></a>If we look at just the first quadrant, then the area of the outermost square <em>A<sub>outer</sub></em> is <em>r</em><sup>2</sup>. The area of the circle <em>A<sub>circle</sub></em> is π<em>r</em><sup>2</sup>/4, and the area of the inner triangle <em>A<sub>triangle</sub></em> is <em>r</em><sup>2</sup>/2. Therefore, we can make two equations for π based on the ratios of these areas: π = 4<em>A<sub>circle</sub></em>/<em>A<sub>outer</sub></em> and π = 2<em>A<sub>circle</sub></em>/<em>A<sub>triangle</sub></em>. Notice how neither equation depends on the radius; so, if we can figure out an alternate way to calculate these areas, we can determine the value of π. Python to the rescue!<br />
<span id="more-46"></span></p>
<p>Imagine that you&#8217;re throwing darts at this collection of shapes, and you&#8217;re guaranteed that they&#8217;ll all land in the upper right section (a stretch depending on the quality of your dart game, but bear with me). Some of the darts will land within the inscribed circle, and some of those darts will also land in the inner triangle. By adding up the numbers of darts that land in each section, we can approximate the areas of each of these sections.</p>
<p>For simplicity, let <em>r</em> = 1. Since we&#8217;re restricting ourselves to the first quadrant, the (<em>x</em>, <em>y</em>) coordinates of each dart will be positive real numbers on the interval [0, 1]. We&#8217;ve constrained our system so that every dart thrown lands in the outer square, thus <em>A<sub>outer</sub></em> ≈ <em>N</em>, where <em>N</em> is the total number of darts thrown.</p>
<p>For a dart to land inside the circle, its coordinates must fulfill the equation <em>x</em><sup>2</sup> + <em>y</em><sup>2</sup> ≤ 1 (remembering that <em>r</em> = 1). Darts that land inside in the triangle have coordinates such that <i>x</i> + <em>y</em> ≤ 1 (where we&#8217;ve constrained <em>x</em> and <em>y</em> to be positive). To simulate a dart throw, we can randomly generate two floating-point numbers between 0 and 1 inclusive for the <em>x</em>- and <em>y</em>-coordinates respectively. Then, if they satisfy the circle equation, we increment the number of darts that hit the circle <em>N<sub>circle</sub></em> by 1, and if they satisfy the triangle equation, we increment the number of darts that hit the triangle <em>N<sub>triangle</sub></em> by 1.</p>
<p>Because <em>A<sub>circle</sub></em> ≈ <em>N<sub>circle</sub></em> and <em>A<sub>triangle</sub></em> ≈ <em>N<sub>triangle</sub></em>, we can say that π ≈ 4<em>N<sub>circle</sub></em>/<em>N</em> and π ≈ 2<em>N<sub>circle</sub></em>/<em>N<sub>triangle</sub></em>. Now let&#8217;s code up this simulation!</p>
<pre class="brush: python; title: ; notranslate">import random
import sys

def point_in_circle(x, y):
	return True if x**2 + y**2 &lt;= 1 else False

def point_in_triangle(x, y):
	return True if x + y &lt;= 1 else False # assume x and y are positive

def get_point():
	return random.random(), random.random()

def get_point_in_shapes():
	x, y = get_point()
	in_circle = point_in_circle(x, y)
	in_triangle = False
	if in_circle: # if the point isn't in the circle, we know that it can't be in the triangle
		in_triangle = point_in_triangle(x, y)
	return in_circle, in_triangle

def get_points_in_shapes(N_darts):
	N_circle, N_triangle = 0, 0
	i = 0 # keep track of how many darts we've thrown so far
	while i &lt; N_darts:
		in_circle, in_triangle = get_point_in_shapes()
		if in_circle:
			N_circle += 1
		if in_triangle:
			N_triangle += 1
		i += 1
	return N_circle, N_triangle

def pi_formula(N_darts, N_circle):
	return 4.0 * N_circle / N_darts

def pi_formula2(N_darts, N_circle, N_triangle):
	if 0 == N_triangle: # if no darts landed in the triangle, avoid dividing by zero by falling
			    # back on the equation that doesn't use the area of the triangle
		return pi_formula(N_darts, N_circle)
	# otherwise, average the two approximations
	return N_circle * (2.0 / N_darts + 1.0 / N_triangle)

def calculate_pi(N_darts):
	N_circle, N_triangle = get_points_in_shapes(N_darts)
	return pi_formula2(N_darts, N_circle, N_triangle)

# driver
N_darts = int(sys.argv[1]) # the total number of darts to throw (given by a command-line argument)
print calculate_pi(N_darts)</pre>
<p>(Note how each function is responsible for doing one specific task. This will simplify unit testing, a topic I&#8217;ll discuss in a later post.)</p>
<p>While fun to think about, this method takes a while to produce decent results. For example, I can consistently lock in the first three digits of π by &#8220;throwing&#8221; 10,000,000 darts on my computer, but it takes about 12.3 seconds to run. Additionally, the ability of this method to give a good approximation of π is limited by the precision of Python&#8217;s floating-point numbers. The darts&#8217; positions are effectively quantized because <a href="http://docs.python.org/2/tutorial/floatingpoint.html">Python only uses 53 bits to represent floats</a>. In my next post, I&#8217;ll present a variation on this technique that allows us to take advantage of Python&#8217;s arbitrarily large integers to improve the approximation.</p>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/approximating-pi-in-python-part-1/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Building my first computer</title>
		<link>http://davidshimel.com/building-my-first-computer/</link>
		<comments>http://davidshimel.com/building-my-first-computer/#comments</comments>
		<pubDate>Mon, 28 Jan 2013 03:04:38 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=19</guid>
		<description><![CDATA[Motivation One of my New Year&#8217;s resolutions was to build my own desktop computer. I&#8217;d been getting frustrated with the performance of my laptop, but more importantly I had to do it for the nerd cred. I mainly use my PC for software development, music production, and some gaming. Unfortunately, my laptop couldn&#8217;t run Diablo &#8230; <a href="http://davidshimel.com/building-my-first-computer/" class="more-link">Continue reading <span class="meta-nav">&#187;</span></a>]]></description>
				<content:encoded><![CDATA[<h1>Motivation</h1>
<p>One of my New Year&#8217;s resolutions was to build my own desktop computer. I&#8217;d been getting frustrated with the performance of my laptop, but more importantly I had to do it for the nerd cred.</p>
<p>I mainly use my PC for software development, music production, and some gaming. Unfortunately, my laptop couldn&#8217;t run Diablo III at a decent resolution (forget 1920&#215;1080) with minimal settings at even 25 frames per second. Cranking up the GPU clock speed helped a little, but laptops have enough heating issues without throwing overclocking into the mix. Additionally, when working on a musical composition, I couldn&#8217;t have very many synths, effects, or track automations running in real-time without getting choppy playback. Freezing tracks solved that issue to some extent, but it slowed down my workflow.<span id="more-19"></span></p>
<h1>Choosing the parts</h1>
<p>To get started, a coworker recommended the guide on <a href="http://www.hardware-revolution.com/mainstream-gaming-pc-december-2012/">Hardware Revolution</a>. My budget was around $1,200, so the Tier 5 system provided a useful template which I then customized.</p>
<p>I began by upping the RAM from 8 to 16 GB since RAM is cheap and I like to have 400 tabs open at all times. I initially chose 2&#215;8 sticks, but a friend recommended that 4&#215;4 would perform better. I&#8217;ve since done some research into the differences between the two setups, but haven&#8217;t found much to explain why 4&#215;4 would be faster. Since my motherboard only has four memory slots, upgrading would require getting all new modules. However, by the time 16 GB becomes obsolete, I would probably need to get all new RAM anyway.</p>
<p>For the video card, the guide recommended the GeForce GTX 660 Ti for about $300. Since I&#8217;m not a super hardcore gamer, I didn&#8217;t want to drop that much on a GPU. The standard GTX 660 at $209 seemed like a good deal to me, but another coworker persuaded me to go with the Radeon HD 7870, citing its improved specs and purported ability to better support multiple monitor setups.</p>
<p>I dabble in overclocking, so I wanted to get a CPU cooler to replace the stock one. Liquid cooling a system has become a lot easier in recent years due to the advent of simple-to-install, pre-assembled products. So, after doing some research, I settled on the Corsair H60. However, a friend suggested that, since I wasn&#8217;t doing any &#8220;extreme&#8221; overclocking, an air cooler would be preferable since it couldn&#8217;t leak fluid all my shiny new hardware while still giving improved cooling performance compared to the stock fan. With that advice, I selected the Cooler Master Hyper 212 EVO cooler, which, as an added bonus, was less than half the price of the H60.</p>
<p>Finally, the power supply. <a href="http://pcpartpicker.com/">PC Part Picker</a> will give you an estimated wattage for your system. <a href="http://www.extreme.outervision.com/psucalculatorlite.jsp">eXtreme Outer Vision</a> also has a good calculator. I don&#8217;t intend to run dual graphics cards in CrossFire configuration, so my power needs were a modest 365 W. A friend recommended the Seasonic X Series 560W 80 PLUS Gold on the basis of Seasonic&#8217;s reputation for building solid PSUs. This power supply has the advantage of being modular, resulting in less cable clutter within your case, while also <a href="http://en.wikipedia.org/wiki/80_Plus#Efficiency_level_certifications">providing power efficiently</a>.</p>
<p>Here&#8217;s the <a href="http://pcpartpicker.com/p/zYid">final parts list</a>.</p>
<div id="attachment_21" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/01/01-Boxes-one-third.jpg"><img class="size-medium wp-image-21 " alt="And the parts themselves!" src="http://davidshimel.com/wp-content/uploads/2013/01/01-Boxes-one-third-300x225.jpg" width="300" height="225" /></a><p class="wp-caption-text">And the parts themselves!</p></div>
<h1>Putting everything together</h1>
<p>The parts came in over the next week from both Newegg and Amazon. My girlfriend was upstate for the weekend, so I was able to take over our entire studio for the build.</p>
<p>Since this was my first self-assembled computer, I followed <a href="http://www.youtube.com/watch?v=d_56kyib-Ls">this excellent tutorial</a> from Newegg.</p>
<p>In order to make sure everything worked properly, I began with an external build (as recommended in the video). Here I ran into my first bit of trouble. After slotting the CPU into the motherboard, I tried to close the tension arm, but past a certain point, it wouldn&#8217;t budge. I tried pushing it harder, but it didn&#8217;t go much further, and when I looked at the processor afterwards, it had little marks on the side where the retention piece had rubbed against it. Panicking, I started looking all over for someone who&#8217;d had the same problem. I found <a href="http://www.tomshardware.com/forum/280573-31-help-lowering-socket">a post on Tom&#8217;s Hardware</a> suggesting I just push harder. With this blessing, I gathered my courage and pushed the tension arm even harder, finally locking the CPU in place. With a sigh of relief, I continued by installing the cooler and RAM.</p>
<p>As you can see in this blurry photo, there&#8217;s barely enough clearance for the RAM below the CPU fan.</p>
<div id="attachment_28" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/01/11-RAM-with-Barely-Enough-Clearance-one-third.jpg"><img class="size-medium wp-image-28 " alt="Just a sliver" src="http://davidshimel.com/wp-content/uploads/2013/01/11-RAM-with-Barely-Enough-Clearance-one-third-300x225.jpg" width="300" height="225" /></a><p class="wp-caption-text">Just a sliver</p></div>
<p>Originally, I ordered <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16820233143">this memory</a>. After it shipped, I got last-minute advice from a friend who told me to get the low-clearance version of the RAM instead. A noob mistake for sure, but the <a href="http://en.wikipedia.org/wiki/Return_merchandise_authorization">RMA</a> should finish processing any day now. =) I could also have used 2&#215;8 GB sticks, slotting them further away from the CPU fan, or for added fun, filed down the edges of the module closest to the fan with a Dremel.</p>
<p>I slotted in the video card, then broke out the power supply. Since the PSU is modular, I had to try to figure out exactly which cables I needed. Picking the ones to power the motherboard and CPU was easy enough, but when it came time to power the video card, things got confusing. A number of them looked promising, but they either had an extra 2-pin connector dangling off of the 6-pin segment or they required a Molex adapter. After calling up a few coworkers, I learned that power supply cabling is fairly forgiving, so I just did whatever required the fewest adapters.</p>
<p>With that, the external build was complete! I considered leaving it like this for improved airflow, but I didn&#8217;t have any room on my desk to set my coffee mug.</p>
<div id="attachment_31" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/01/17-Successful-External-Build-one-third.jpg"><img class="size-medium wp-image-31 " alt="IT LIVES!!" src="http://davidshimel.com/wp-content/uploads/2013/01/17-Successful-External-Build-one-third-300x225.jpg" width="300" height="225" /></a><p class="wp-caption-text">IT LIVES!!</p></div>
<h1>The internal build</h1>
<p>Without opening the manual for the case, I started screwing in the power supply, optical drive, and motherboard. I tried mounting the mobo a couple times, but it wouldn&#8217;t sit quite right. After reading the case manual, I realized I&#8217;d been using the wrong screws for pretty much everything up until that point. Like Icarus, my hubris got the better of me. After amending the screwed-up (ha!) situation, I began wiring everything up (carefully referencing the motherboard manual along the way).</p>
<p>(As a side note, next time I&#8217;ll skip the external build and install the motherboard into the case before attaching the CPU cooler. The fan made it hard to access a couple of the rear motherboard mounting points.)</p>
<p>The last little bit of difficulty arose when installing the video and sound cards. The Gigabyte Radeon HD 7870 is quite sizable with its three fans, so maneuvering it around the cables in the case proved to be a bit tricky. But this minor speed bump did not hold me back for long.</p>
<div id="attachment_32" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/01/46-Assembled-Case-Bright-one-third.jpg"><img class="size-medium wp-image-32" alt="Cable jungle" src="http://davidshimel.com/wp-content/uploads/2013/01/46-Assembled-Case-Bright-one-third-300x225.jpg" width="300" height="225" /></a><p class="wp-caption-text">Cable jungle</p></div>
<p>With bated breath, I powered everything up . . . and it still booted! Total build time: five hours. Time to boot Windows: five seconds (thanks, solid-state technology!).</p>
<div id="attachment_33" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/01/48-Successful-Internal-Boot-Screen-with-Case.jpg"><img class="size-medium wp-image-33 " alt="The laptop watches jealously from the corner" src="http://davidshimel.com/wp-content/uploads/2013/01/48-Successful-Internal-Boot-Screen-with-Case-300x225.jpg" width="300" height="225" /></a><p class="wp-caption-text">The laptop watches jealously from the corner</p></div>
<p><span style="font-size: 2em;">Final thoughts</span></p>
<p>Building my own PC was a really fun experience. I learned a lot about computer hardware in the process, and I take pleasure in knowing exactly what is in my case and how it&#8217;s connected. I no longer fear configuration modifications like installing a second hard drive. Best of all, there&#8217;s no annoying bloatware pre-installed on my system that I have to clean out. As far as performance goes, Diablo III feels like a completely different game at 60 FPS with maxed settings, and I can use as many soft synths as I want with nary a hiccup.</p>
<p>I have three upgrades in mind:</p>
<ol>
<li><span style="line-height: 13px;">A second hard drive. While my 3 TB external drive does a good job of holding all my data, I&#8217;d like to be able to dual-boot Linux without sacrificing any of the remaining 30 GB on my SSD to a second partition.</span></li>
<li>An internal case light. I&#8217;d like to be able to look down into the grille at the top of my case and see all of my beautiful hardware.</li>
<li>A third monitor. My graphics card supports up to four monitors, but I really only have space on my desk for two at the moment. So first I need to go to Ikea. Unless I build vertically. Hmm . . .</li>
</ol>
<p>I heartily recommend that, if you&#8217;re in the market for a new PC, you consider building your own. There are tons of free resources out there to help you if you get stuck. You&#8217;ll end up with more machine for your money as well as a sense of pride in your accomplishment. And finally, you&#8217;ll always have something to talk about when you run into a fellow computer nerd. =)</p>
<div id="attachment_35" class="wp-caption aligncenter" style="width: 310px"><a href="http://davidshimel.com/wp-content/uploads/2013/01/final-setup-one-third.jpg"><img class="size-medium wp-image-35" alt="Where the magic happens" src="http://davidshimel.com/wp-content/uploads/2013/01/final-setup-one-third-300x225.jpg" width="300" height="225" /></a><p class="wp-caption-text">Where the magic happens</p></div>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/building-my-first-computer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>console.log(&#8216;Hello, World!&#8217;);</title>
		<link>http://davidshimel.com/console-loghello-world/</link>
		<comments>http://davidshimel.com/console-loghello-world/#comments</comments>
		<pubDate>Sun, 27 Jan 2013 02:03:22 +0000</pubDate>
		<dc:creator>David Shimel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://davidshimel.com/?p=9</guid>
		<description><![CDATA[Welcome to my blog! Here, I&#8217;ll be cataloging my explorations into the world of coding in order to crystallize my own understanding of these topics, improve my writing skills, and converse with my fellow software engineers. With that . . . sys.exit(0)]]></description>
				<content:encoded><![CDATA[<p>Welcome to my blog! Here, I&#8217;ll be cataloging my explorations into the world of coding in order to crystallize my own understanding of these topics, improve my writing skills, and converse with my fellow software engineers. With that . . .</p>
<pre>sys.exit(0)</pre>
]]></content:encoded>
			<wfw:commentRss>http://davidshimel.com/console-loghello-world/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
