<?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>Brett TerpstraCode - Brett Terpstra</title>
	<atom:link href="http://brettterpstra.com/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://brettterpstra.com</link>
	<description>Elegant solutions to complex problems.</description>
	<lastBuildDate>Fri, 03 Feb 2012 03:11:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>App Review: CodeRunner</title>
		<link>http://brettterpstra.com/app-review-coderunner/</link>
		<comments>http://brettterpstra.com/app-review-coderunner/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 00:16:48 +0000</pubDate>
		<dc:creator>Brett</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[appreview]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[osx]]></category>

		<guid isPermaLink="false">http://brettterpstra.com/app-review-coderunner/</guid>
		<description><![CDATA[<p>One for the coders: I discovered CodeRunner by Nikolai Krill a few months back, and it’s proven to be very, very useful in the kind of work that I do. It allows you to test blocks of code and see the results quickly and easily. It has syntax highlighting and autocompletion, as well as the ability to handle a wide&#8230;</p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/app-review-coderunner/">App Review: CodeRunner</a></p>]]></description>
			<content:encoded><![CDATA[<p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://cdn2.brettterpstra.com/wp-content/uploads/2011/10/coderunnerscreenshot.jpg?9d7bd4" alt="CodeRunner Screenshot" height="279" width="300" class="alignright shadow colorbox-3024"></p>

<p>One for the coders: I discovered <a href="http://itunes.apple.com/us/app/coderunner/id433335799?mt=12">CodeRunner</a> by Nikolai Krill a few months back, and it’s proven to be very, very useful in the kind of work that I do. It allows you to test blocks of code and see the results quickly and easily. It has syntax highlighting and autocompletion, as well as the ability to handle a wide variety of languages.</p>

<p>CodeRunner handles AppleScript, C, C++, Java, JavaScript (Node.js), Objective-C, Perl, PHP, Python, Ruby and shell scripts. You can add your own languages, compilers/processors and syntaxes, too. The autocomplete libraries for each language are quite good (and very handy), and there are a good number of themes available for syntax highlighting (including my favorite, Twilight). It has auto-pairing and commands for wrapping code in a variety of paired characters, as well as a great set of code-editing tools. You can even pick between indenting with spaces or tabs and set the tab/space width, making it easy to match the code indentation to the settings of the main app you’re coding in.</p>

<p>CodeRunner can also handle code that requires input at runtime, providing a field for passing parameters and input to your functions as needed. In short, it does just about everything I could ask a code-testing application to do.</p>

<p>There are free apps for testing code, but very few that can handle multiple languages and none that I know of which can handle everything that CodeRunner does. If you code in more than one language, CodeRunner is worth every bit of its $4.99 price. <a href="http://itunes.apple.com/us/app/coderunner/id433335799?mt=12">Go get it.</a></p>

<p>Nikolai also has a regular expression testing app in the Mac App Store called <a href="http://itunes.apple.com/us/app/patterns-the-regex-app/id429449079?mt=12">Patterns</a>. I highly recommend it as well. The only issue I have with Patterns is that it doesn’t handle highlighting sub-matches, but for 90% of what I need it to do, it’s excellent.</p>
<p>Related posts:<ol>
<li><a href='http://brettterpstra.com/app-review-livereload/' rel='bookmark' title='App Review: LiveReload'>App Review: LiveReload</a></li>
<li><a href='http://brettterpstra.com/ios-app-review-reading-list/' rel='bookmark' title='iOS App Review: Reading List'>iOS App Review: Reading List</a></li>
<li><a href='http://brettterpstra.com/ios-review-listary/' rel='bookmark' title='iOS app review: Listary'>iOS app review: Listary</a></li>
</ol></p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/app-review-coderunner/">App Review: CodeRunner</a></p>]]></content:encoded>
			<wfw:commentRss>http://brettterpstra.com/app-review-coderunner/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Quick Tip: throttling parallel batch processes in Terminal</title>
		<link>http://brettterpstra.com/quick-tip-throttling-parallel-batch-processes-in-terminal/</link>
		<comments>http://brettterpstra.com/quick-tip-throttling-parallel-batch-processes-in-terminal/#comments</comments>
		<pubDate>Fri, 20 May 2011 08:47:12 +0000</pubDate>
		<dc:creator>Brett</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[quicktip]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[terminal]]></category>

		<guid isPermaLink="false">http://brettterpstra.com/?p=2334</guid>
		<description><![CDATA[<p>Quick tips are random posts regarding something I discovered on my way to something bigger. They usually get longer than “quick” would imply, for which I refuse to apologize. It starts out with mdfind and all of the creative scripting you can do with it. You start finding batches of files with something in common and you do things with&#8230;</p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/quick-tip-throttling-parallel-batch-processes-in-terminal/">Quick Tip: throttling parallel batch processes in Terminal</a></p>]]></description>
			<content:encoded><![CDATA[<p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://cdn2.brettterpstra.com/wp-content/uploads/2011/05/parallel_clipart.jpg?9d7bd4" class="alignright shadow colorbox-2334" alt="Parallel Planes ClipartIt" /><em><a href="http://brettterpstra.com/tag/quicktip/">Quick tips</a> are random posts regarding something I discovered on my way to something bigger. They usually get longer than “quick” would imply, for which I refuse to apologize.</em></p>

<p>It starts out with <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/mdfind.1.html">mdfind</a> and all of the <a href="http://www.tuaw.com/2008/02/15/terminal-tips-creating-a-spotlight-based-gallery/">creative scripting</a> you can do with it. You start finding batches of files with something in common and you do things with them or to them. It sounds genocidal; it’s not. It’s very productive after the initial script setup.</p>

<p>Take, for example, a little script I run to add thumbnails to weblocs I have laying around. It looks something like this:</p>


<div class="wp_syntax"><div class="code"><pre class="bash">mdfind <span class="re5">-onlyin</span> ~<span class="sy0">/</span>Dropbox<span class="sy0">/</span>Sync<span class="sy0">/</span>Bookmark<span class="sy0">/</span> \
<span class="st_h">'(! ( ((kMDItemOMUserTags == &quot;*donotthumbnail*&quot;cd) \
|| (kOMUserTags == &quot;*donotthumbnail*&quot;cd) ) ) \
&amp;&amp; (kMDItemFSHasCustomIcon = &quot;0&quot;) \
&amp;&amp; (kMDItemContentType == &quot;*webloc*&quot;cd))'</span> <span class="sy0">|</span> <span class="kw1">while</span> <span class="kw2">read</span> <span class="kw2">file</span>; \
<span class="kw1">do</span> <span class="sy0">/</span>usr<span class="sy0">/</span>local<span class="sy0">/</span>bin<span class="sy0">/</span>setWeblocThumb <span class="st0">&quot;<span class="es2">$file</span>&quot;</span> ; <span class="kw1">done</span></pre></div></div>


<p>It’s a one-liner, you’d want to reassemble it to run it (remove the backslashes at the line ends and join them all together), but it uses mdfind to search my shared bookmarks folder for recent items which don’t already have a custom thumbnail, passes them to <a href="http://hasseg.org/setWeblocThumb/">setWeblocThumb</a> and processes them… one at a time. I know my machine and my bandwidth can handle more than that, but if the list is 50+ long, that’s a lot of processes doing some relatively intensive labor. It would grind my machine to a halt. Yes, I tried it just to be sure.</p>

<p>So I needed a way to throttle the number of simultaneous processes, and I know that someone out there must have long beat me to the solution. There it was: <a href="http://pebblesinthesand.wordpress.com/2008/05/22/a-srcipt-for-running-processes-in-parallel-in-bash/">parallel</a>. It’s a script you can download and make executable in your path, and then run it with a few parameters and a batch of files or arguments. It will keep your defined number of processes going until the job is done, but won’t let things get out of hand. You can add <code>nice</code> (<a href="http://man.cx/nice">man page</a>) in each process if you need more cpu control over the process.</p>

<p>My new command looks like:</p>


<div class="wp_syntax"><div class="code"><pre class="bash">mdfind <span class="re5">-onlyin</span> <span class="sy0">/</span>Users<span class="sy0">/</span>ttscoff<span class="sy0">/</span>Dropbox<span class="sy0">/</span>Sync<span class="sy0">/</span>Bookmark<span class="sy0">/</span> \
<span class="st_h">'(! ( ((kMDItemOMUserTags == &quot;*donotthumbnail*&quot;cd) \
|| (kOMUserTags == &quot;*donotthumbnail*&quot;cd) ) ) \
&amp;&amp; (kMDItemFSHasCustomIcon = &quot;0&quot;) \
&amp;&amp; (kMDItemContentType == &quot;*webloc*&quot;cd))'</span><span class="sy0">|</span> parallel <span class="re5">-j</span> <span class="nu0">8</span> <span class="re5">-r</span> <span class="st0">&quot;/usr/local/bin/setWeblocThumb&quot;</span></pre></div></div>


<p>Seriously, if you’re doing anything in batch you should <a href="http://pebblesinthesand.wordpress.com/2008/05/22/a-srcipt-for-running-processes-in-parallel-in-bash/">check Parallel out</a>, or show me an even better one. Parallel made my morning, and by keeping CPU from maxing I actually got through some batches even faster. I’m sure there are other elegant ways of handling this. Let ‘em rip.</p>
<p>Related posts:<ol>
<li><a href='http://brettterpstra.com/geeklet-top-ram-processes/' rel='bookmark' title='Geeklet: Top RAM Processes'>Geeklet: Top RAM Processes</a></li>
<li><a href='http://brettterpstra.com/geeklet-top-cpu-processes/' rel='bookmark' title='Geeklet: Top CPU processes'>Geeklet: Top CPU processes</a></li>
<li><a href='http://brettterpstra.com/a-bash-function-for-markdown-bloggers/' rel='bookmark' title='A Bash function for Markdown bloggers'>A Bash function for Markdown bloggers</a></li>
</ol></p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/quick-tip-throttling-parallel-batch-processes-in-terminal/">Quick Tip: throttling parallel batch processes in Terminal</a></p>]]></content:encoded>
			<wfw:commentRss>http://brettterpstra.com/quick-tip-throttling-parallel-batch-processes-in-terminal/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A better System Service for Evernote clipping — with MultiMarkdown</title>
		<link>http://brettterpstra.com/a-better-os-x-system-service-for-evernote-notes-with-multimarkdown/</link>
		<comments>http://brettterpstra.com/a-better-os-x-system-service-for-evernote-notes-with-multimarkdown/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 00:02:09 +0000</pubDate>
		<dc:creator>Brett</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[evernote]]></category>
		<category><![CDATA[markdown]]></category>
		<category><![CDATA[multimarkdown]]></category>
		<category><![CDATA[os x]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[snow leopard]]></category>

		<guid isPermaLink="false">http://brettterpstra.com/?p=302</guid>
		<description><![CDATA[<p>Update: If you’re looking for a Markdown -&#62; Evernote, check this out. Another post, quickly and with less explanation… The fact that Evernote processes HTML so much better than it does plain or rich text got me thinking and tinkering. I use Markdown (actually, MultiMarkdown) constantly, and it does a great job of turning plain text into valid markup. With&#8230;</p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/a-better-os-x-system-service-for-evernote-notes-with-multimarkdown/">A better System Service for Evernote clipping — with MultiMarkdown</a></p>]]></description>
			<content:encoded><![CDATA[<p><strong>Update:</strong> If you’re looking for a Markdown -&gt; Evernote, <a href="http://brettterpstra.com/taking-the-markdown-to-evernote-service-further/">check this out</a>.</p>

<p>Another post, quickly and with less explanation…</p>

<p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://cdn2.brettterpstra.com/wp-content/uploads/2010/03/EvernoteIcon-300x300.png?9d7bd4" alt="Evernote Icon" title="EvernoteIcon" width="300" height="300" class="alignright size-medium wp-image-305 colorbox-302" />The fact that Evernote processes HTML so much better than it does plain or rich text got me thinking and tinkering. I use <a href="http://daringfireball.net/projects/markdown/">Markdown</a> (actually, <a href="http://fletcherpenney.net/multimarkdown/">MultiMarkdown</a>) constantly, and it does a great job of turning plain text into valid markup. With (Multi)Markdown, even plain text becomes HTML that–when imported into Evernote–retains most of its formatting. To answer your question, no, I’m not obsessed with Evernote, I’m obsessed with problems I think I could solve. It’s unhealthy.</p>

<p><strong><em>Please note</em></strong>, this requires that you have <a href="http://fletcherpenney.net/">Fletcher Penney’s</a> MultiMarkdown installed in <code>~/Library/Application Support/MultiMarkdown</code>, and that the Perl files (MultiMarkdown.pl and SmartyPants.pl) are located in a ‘bin’ subdirectory (which is the default install). If you don’t have MultiMarkdown, you should get it anyway (all the cool kids have it), so head over to the <a href="http://fletcher.github.com/MultiMarkdown/">download page</a> and grab a copy. Now, on with the show.</p>

<p>I set this up originally as a <a href="http://macromates.com/">TextMate</a> command, intending just to be able to clip code snippets and free-form text to Evernote without thinking too much about it. That worked well, so I modified it to work as a System Service. Specifically, a Snow Leopard service, but I’m providing the Ruby script here and it can be modified for any Mac setup you want.</p>

<p>While it will work just fine on plain text with no markup, it does have a couple of “special” features. If you start a line with a <code>#</code> and a space (e.g.: # This is my header), which is a <a href="http://daringfireball.net/projects/markdown/syntax#header">Markdown convention</a> for a first-level heading, it will use that as the title for the note and strip it out of the text in processing. It only uses the first one it finds, but it will strip out any first-level headers in the selection. I’ll probably modify that later, or just have it leave them in. Also, a line that begins with “tags:” followed by a space and a comma-separated list of words will be split up and used to tag the new note. This is also stripped before processing. It handles spaces in multi-word tags, and odd marks at the beginning or end of a tag, <em>but only one punctuation character, and only at the beginning or end of a tag</em>. The code follows…</p>

<p><span id="more-302"></span></p>

<p>Here’s the Ruby code, messy as it may be:</p>

<div markdown=0>
<pre><code>
    #!/usr/bin/env ruby -rjcode -Ku
    # requires that MultiMarkdown be installed in ~/Library/Application Support/MultiMarkdown
    # That, or edit the script to point to yours :)

    ARGF.each do |f|
    input = f
    contents = &#x27;&#x27;
    tags = &#x27;&#x27;
    title = nil

    def e_as(str)
        str.to_s.gsub(/(?=[&quot;\\])/, &#x27;\\&#x27;)
    end
    input.each_line { |line| 
      if line =~ /^# (.*?)/
        title = line[2..-1]
        break
      end
    }
    title = %x{date &#x27;+Clipped note: %A, %B %d, %Y at %l:%M %p&#x27;|tr -s &quot; &quot;} if title.nil?

    input.each_line { |line| 
      if line =~ /^[Tt]ags: /
        tags = line[5..-1].split(&#x27;,&#x27;).map {|tag| tag = tag.strip.gsub(/^(.)?\b|\b(.)?$/,&quot;\\2\&quot;\\1&quot;) }
        break
      end
    }

    IO.popen(&#x27;&quot;$HOME/Library/Application Support/MultiMarkdown/bin/MultiMarkdown.pl&quot;|&quot;$HOME/Library/Application Support/MultiMarkdown/bin/SmartyPants.pl&quot;&#x27;, &quot;r+&quot;) do |io|
     input.each_line { |line| 
        io &lt;&lt; line unless line =~ /^# |[Tt]ags\: /
     }; io.close_write
     io.each_line do |line|
       contents &lt;&lt; line
     end
    end
    tags = &quot; tags {#{tags.join(&quot;,&quot;)}}&quot; unless tags.empty?
    %x{osascript -e &#x27;tell application &quot;Evernote&quot; to create note with html &quot;#{e_as contents}&quot; title &quot;#{title}&quot; notebook &quot;Unfiled&quot;#{tags}&#x27;}
    end
</code></pre>
</div>

<p>You can create a System Service in Automator with it, set up a command in TextMate, or do whatever else you can think of. If you just want to download the service and try it out, I’ve made it <a href="http://brettterpstra.com/downloads/MarkdownToEvernote.zip?9d7bd4">available here</a>. Unzip and copy it to ~/Library/Services (in your home folder). If you set it up as a System Service, assign a shortcut key in the Keyboard pane of System Preferences.</p>

<p>It does choke once in a while, apparently on Markdown-generated code snippets, but I haven’t quite narrowed down why, yet. I’ll update the code if I figure that one out. Overall, though, it makes pretty clippings and allows you to use some Markdown syntax to spice up your text without having to touch the (regrettably abominable) Evernote editor.</p>

<hr />

<div class="download_desc"><p class="download-icon"><a href="http://brettterpstra.com/downloads/MarkdownToEvernote.zip?9d7bd4" title="Download Markdown To Evernote Service (390)"><img class="colorbox-302"  src="http://brettterpstra.com/wp-content/images/serviceicon.jpg?9d7bd4" alt="download image for Markdown To Evernote Service" width="64" /></a><br /><a href="http://brettterpstra.com/downloads/MarkdownToEvernote.zip?9d7bd4" title="Download Markdown To Evernote Service (390)" class="download-button">Download</a></p><p class="desc"><a href="http://brettterpstra.com/downloads/MarkdownToEvernote.zip?9d7bd4" title="Download Markdown To Evernote Service (390)">Markdown To Evernote Service</a> — A Snow Leopard System Service that grabs selected text, processes it with MultiMarkdown and clips the resulting HTML to Evernote, creating a nicely formatted note. Uses the first (and hopefully only) Markdown first-level heading (# My headline) as the title for the note, and will look for a line starting with “tags: ” followed by a comma-separated list of tags as well.

Requires that MultiMarkdown be installed in ~/Library/Application Support/MultiMarkdown. <a href="http://brettterpstra.com/2010/03/06/a-better-os-x-system-service-for-evernote-notes-with-multimarkdown/">More Info</a></p></div>
<p>Related posts:<ol>
<li><a href='http://brettterpstra.com/taking-the-markdown-to-evernote-service-further/' rel='bookmark' title='Taking the Markdown to Evernote service further'>Taking the Markdown to Evernote service further</a></li>
<li><a href='http://brettterpstra.com/evernote-site-memory-tagger-for-wordpress/' rel='bookmark' title='Evernote Site Memory tagger for WordPress'>Evernote Site Memory tagger for WordPress</a></li>
<li><a href='http://brettterpstra.com/a-service-for-writing-multimarkdown-footnotes-inline/' rel='bookmark' title='A Service for writing MultiMarkdown footnotes inline'>A Service for writing MultiMarkdown footnotes inline</a></li>
</ol></p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/a-better-os-x-system-service-for-evernote-notes-with-multimarkdown/">A better System Service for Evernote clipping — with MultiMarkdown</a></p>]]></content:encoded>
			<wfw:commentRss>http://brettterpstra.com/a-better-os-x-system-service-for-evernote-notes-with-multimarkdown/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A (fairly) simple equation evaluation service for Snow Leopard</title>
		<link>http://brettterpstra.com/equation-evaluation-service-for-snow-leopard/</link>
		<comments>http://brettterpstra.com/equation-evaluation-service-for-snow-leopard/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 14:33:05 +0000</pubDate>
		<dc:creator>Brett</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[snow leopard]]></category>

		<guid isPermaLink="false">http://brettterpstra.com/?p=215</guid>
		<description><![CDATA[<p>Download the Evaluate Expression Snow Leopard service: EvaluateExpressionService.zip This is a stripped down version of a command I have in the TextMate bundle we use at TUAW. It allows you to select any basic numeric equation and evaluate it, replacing the selected text with the results. It will ignore your text if it contains anything but numbers and basic mathematical&#8230;</p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/equation-evaluation-service-for-snow-leopard/">A (fairly) simple equation evaluation service for Snow Leopard</a></p>]]></description>
			<content:encoded><![CDATA[<p><img style=' float: left; padding: 4px; margin: 0 7px 2px 0; display:none'  src="http://cdn2.brettterpstra.com/wp-content/uploads/2009/12/equationevalheader.jpg?9d7bd4" alt="Expressionevalheader" height="187" width="650" class="alignleft headerimg colorbox-215" />Download the Evaluate Expression Snow Leopard service: <a href="http://brettterpstra.com/share/EvaluateExpressionService.zip?9d7bd4">EvaluateExpressionService.zip</a></p>

<p>This is a stripped down version of a command I have in the <a href="http://macromates.com/">TextMate</a> bundle we use at <a href="http://www.tuaw.com/">TUAW</a>. It allows you to select any basic numeric equation and evaluate it, replacing the selected text with the results. It will ignore your text if it contains anything but numbers and basic mathematical symbols. Sure, there are plenty of ways to do calculations in OS X (<a href="http://www.mactropolis.com/how-tos/leopard-tip-spotlight-calculator/">Spotlight</a>, <a href="http://www.obdev.at/products/launchbar/index.html">Launchbar</a>, <a href="http://www.blacktree.com/">Quicksilver</a>), but I’ve had more and more incidents lately where I just wanted to do quick calculations inline, so I whipped this up. A little explanation…</p>

<p><span id="more-215"></span>
The service is built for Snow Leopard only, but I’m including the code here because it could be wrapped up in <a href="http://wafflesoftware.net/thisservice/">ThisService</a> or <a href="http://www.xendai.com/">Bellhop</a> pretty quickly for Leopard. It’s built in Ruby and uses the eval function to process text such as <code>20*(3.5/2)</code> and return the result. It will add commas to numbers longer than 3 digits, but I stripped out the part of the original command that trimmed decimal places; I figured the accuracy might be important and the results are easy to edit manually in this case. I also added a silly feature that I actually find quite useful: it evaluates +/- percentage strings, such as <code>23.99-15%</code>, which I find most useful for calculating savings during sales or quickly handling markup or tax on services and goods. It can’t get too complex, but for most everyday purposes, it does a good job.</p>

<h3>The code:</h3>

<div markdown="0">
<pre><code>
def ts( st )
  # Adds commas to longer numbers
  # Removes .00 left over from % calculations
  mynum = st.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
  dec = mynum.split('.')
  return dec[0] if dec[1].to_i == 0
  mynum
end

ARGF.each do |f|
    # check if the text passed is actually an equation
    if f.match(/^[\%\$\d\*\/\+\-,\. \(\)]+$/)
        # add a preceding 0 to decimals passed for floating point calculation
        num = f.gsub(/(^|[^\d])(\.\d+)/,'\10\2')
        # convert basic percentage equations for eval
        num = num.gsub(/([\d\.]+)(?:\s+?)?([+-])(?:\s+?)?([\d\.]+)%([^\d]|$)/,'\1\2(\1*(\3.to_f * 0.01))\4')
        # process the result to add commas, trim unnecessary decimal places
        print ts(eval(num).to_s)
    # if it's not an equation, return the input (no effect)
    else
        print f
    end
end
</code></pre>
</div>

<p>You can <a href="http://brettterpstra.com/downloads/EvaluateExpressionService.zip?9d7bd4">download a ready-to-go Snow Leopard service</a>, or build your own with the code above. Don’t forget to use the Keyboard preference panel to assign a keyboard shortcut to it (I’m using Control-Shift-=). I’d love to hear back if you find it useful!</p>
<p>Related posts:<ol>
<li><a href='http://brettterpstra.com/clippable-to-evernote-snow-leopard-service/' rel='bookmark' title='Clippable to Evernote Snow Leopard Service'>Clippable to Evernote Snow Leopard Service</a></li>
<li><a href='http://brettterpstra.com/updated-songza-lucky-link-service/' rel='bookmark' title='Updated: Songza Lucky Link Service'>Updated: Songza Lucky Link Service</a></li>
<li><a href='http://brettterpstra.com/sms-from-the-command-line-with-google-voice/' rel='bookmark' title='SMS from the command line with Google Voice'>SMS from the command line with Google Voice</a></li>
</ol></p><p>Originally posted on <a href="http://brettterpstra.com" title="BrettTerpstra.com">BrettTerpstra.com</a> at <a href="http://brettterpstra.com/equation-evaluation-service-for-snow-leopard/">A (fairly) simple equation evaluation service for Snow Leopard</a></p>]]></content:encoded>
			<wfw:commentRss>http://brettterpstra.com/equation-evaluation-service-for-snow-leopard/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic (Feed is rejected)
Page Caching using disk: enhanced
Database Caching 13/60 queries in 0.368 seconds using xcache
Object Caching 1638/1691 objects using xcache
Content Delivery Network via cdn2.brettterpstra.com

Served from: brettterpstra.com @ 2012-02-04 09:13:59 -->
