<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>Nurullah Akkaya: an explorer&apos;s log</title><link>http://nakkaya.com</link><description>Random bits and pieces on stuff that I find interesting.</description><item><title>Visualizing Maps Using Incanter</title><link>http://nakkaya.com/2010/03/09/visualizing-maps-using-incanter/</link><description>&lt;p&gt;When I first saw
&lt;a href=&quot;http://en.wikipedia.org/wiki/Mathematica&quot;&gt;Mathematica&lt;/a&gt;&apos;s
&lt;a href=&quot;http://documents.wolfram.com/mathematica/Add-onsLinks/StandardPackages/Miscellaneous/WorldPlot.html&quot;&gt;WorldPlot&lt;/a&gt;
function I was impressed, its a nice way to visualize various forms
of geographical data, for some time I thought this should be a very labor
intensive task, who would go around labeling each pixel. Couple of days
ago I somehow ended up reading the
&lt;a href=&quot;http://en.wikipedia.org/wiki/Processing_(programming_language&quot;&gt;Processing&lt;/a&gt;
article on Wikipedia, it contains an example which shows a map of the
results of the 2008 USA presidential election, turns out using &lt;a href=&quot;http://en.wikipedia.org/wiki/Scalable_Vector_Graphics&quot;&gt;Scalable
Vector Graphics&lt;/a&gt;
implementing WorldPlot functionality is extremely easy.&lt;/p&gt;

&lt;p&gt;We will be plotting how population moved between different regions in
&lt;a href=&quot;http://en.wikipedia.org/wiki/Turkey&quot;&gt;Turkey&lt;/a&gt; (in to and out of a
region). I am using data provided by &lt;a href=&quot;http://en.wikipedia.org/wiki/Turkish_Statistical_Institute&quot;&gt;The Turkish Statistical
Institute&lt;/a&gt;,
you can grab the map I used from Wikipedia
&lt;a href=&quot;http://upload.wikimedia.org/wikipedia/commons/9/9b/MapTurkishProvincesNumbers.svg&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; ;; Data for 2009
 (def pop-taken [{:id 1 :name &quot;Marmara&quot; :population 582771}
                 {:id 2 :name &quot;Iç Anadolu&quot; :population 297919}
                 {:id 3 :name &quot;Ege&quot; :population 164896}
                 {:id 4 :name &quot;Akdeniz&quot; :population 188441}
                 {:id 5 :name &quot;Karadeniz&quot; :population 256654}
                 {:id 6 :name &quot;Güneydoğu Anadolu&quot; :population 171910}
                 {:id 7 :name &quot;Doğu Anadolu&quot; :population 214082}])

 (def pop-given [{:id 1 :name &quot;Marmara&quot; :population 677395}
                 {:id 2 :name &quot;Iç Anadolu&quot; :population 310293}
                 {:id 3 :name &quot;Ege&quot; :population 181459}
                 {:id 4 :name &quot;Akdeniz&quot; :population 193231}
                 {:id 5 :name &quot;Karadeniz&quot; :population 247397}
                 {:id 6 :name &quot;Güneydoğu Anadolu&quot; :population 118611}
                 {:id 7 :name &quot;Doğu Anadolu&quot; :population 148287}])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Turkey is divided in to seven geographical regions, pop-taken represents
how many people moved in to that particular region and pop-given
represents how many people moved out of that region during 2009.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn region-color [val min max]
   (lerp-color (color 0xffd120) (color 0x920903) (norm val min max)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to paint the map like a heat map, we need to assign colors
using the amount of people moved in or out of a region, given a min, max
and a value in between norm will normalize a value to exist between 0
and 1, lerp-color on the other hand will calculate a color between the
given range using the normalized value. So our map will go from yellow
to dark red depending on the people moved.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn map-region-color [regions]
   (let [min (apply min (map #(:population %) regions))
         max (apply max (map #(:population %) regions))]
     (map #(vector (:id %) (region-color (:population %) min max)) regions)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now all we need to do is calculate min and max values in the data set,
iterate over the data set and return a sequence of [id color] pairs.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn sktch [regions]
   (sketch
    (setup [])
    (draw 
     []
     (let [tr-map (load-shape this &quot;MapTurkishProvincesNumbers.svg&quot;)]
       (.shape this tr-map 0 0)
       (doseq [region (map-region-color regions)]
         (let [[id color] region
               child (.getChild tr-map (str id))]
           (.disableStyle child)
           (.fill this color)
           (.noStroke this)
           (.shape this child 0 0)
           no-loop))))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using incanter-processing library, we can load and access parts of the
SVG map. Processing sketches are made up of the functions setup and
draw, in setup as its name suggests you setup your stuff frame rate,
stroke properties etc. Draw will be called once or multiple times
depending on your frame rate, we load the map as a shape then paint it
on the canvas, then we iterate over the data set, using getChild method
of the &lt;a href=&quot;http://processing.org/reference/PShape.html&quot;&gt;PShape&lt;/a&gt; class we
can access parts of the image, the map we are using has 7 children named
1 through 7 corresponding to the geographical regions of the country, we
get the child then paint it using the color we calculated on to the
canvas. One thing to note, sketch macro just returns a PApplet so for
any function not implemented in incanter, you can access them just like
any other Java function. Now lets see the results,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(view (sktch pop-given) :size [1052 744])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;/images/post/incanter-pop-given.png&quot; alt=&quot;incanter processing map&quot; /&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(view (sktch pop-taken) :size [1052 744])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;/images/post/incanter-pop-taken.png&quot; alt=&quot;incanter processing map&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;/code/clojure/worldplot.clj&quot;&gt;worldplot.clj&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://upload.wikimedia.org/wikipedia/commons/9/9b/MapTurkishProvincesNumbers.svg&quot;&gt;MapTurkishProvincesNumbers.svg&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description></item><item><title>WebDAV + SSL on Debian</title><link>http://nakkaya.com/2010/03/05/webdav-ssl-on-debian/</link><description>&lt;p&gt;I was looking for a way to easily share documents between machines,
since WebDAV shares can be accessed by Windows, Linux or Mac machines out
of the box, I choose WebDAV over SSL. I don&apos;t use SSL for anything so
WebDAV is served from DocumentRoot. I&apos;ve been using it for a few days,
so far it beats carrying USB sticks around.&lt;/p&gt;

&lt;p&gt;Enable relevant Apache modules,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;a2enmod ssl
a2enmod dav_fs
a2enmod dav
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Create SSL certificate,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; mkdir /etc/apache2/ssl
 openssl req $@ -new -x509 -days 365 -nodes -out /etc/apache2/ssl/apache.pem \
     -keyout /etc/apache2/ssl/apache.pem
 chmod 600 /etc/apache2/ssl/apache.pem
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Create your WebDAV directory and create a password file,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mkdir /path/to/webdav/
chown www-data /path/to/webdav/
htpasswd -c /path/to/passwd.dav user
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Edit and add the following snippet to the configuration for the host you
want to enable WebDAV,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; &amp;lt;VirtualHost *:443&amp;gt;
         ServerAdmin user@host.com
         DocumentRoot /path/to/webdav

         SSLEngine on
         SSLCertificateFile /etc/apache2/ssl/apache.pem

         &amp;lt;Directory /path/to/webdav/&amp;gt;
            DAV On
            AuthType Basic
            AuthName &quot;webdav&quot;
            AuthUserFile /path/to/passwd.dav
            Require valid-user
        &amp;lt;/Directory&amp;gt;

         ErrorLog  /path/to/webdav/error.log
         CustomLog /path/to/webdav/access.log combined
 &amp;lt;/VirtualHost&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Reload Apache configuration,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/etc/init.d/apache2 reload
&lt;/code&gt;&lt;/pre&gt;
</description></item><item><title>Analytics with Incanter</title><link>http://nakkaya.com/2010/03/02/analytics-with-incanter/</link><description>&lt;p&gt;These past few days I&apos;ve been playing with
&lt;a href=&quot;http://incanter.org/&quot;&gt;Incanter&lt;/a&gt;, which is a Clojure-based, R-like
platform for statistical computing and graphics. This post covers the
basic steps of using Clojure to access your Google Analytics Data with
the Google Analytics Data Export API and visualize, filter the data
returned using Incanter.&lt;/p&gt;

&lt;p&gt;Google provides a Java library to simplify use of any Google Data API
with Java, to access Analytics you need to grab the following list of
Jars from
&lt;a href=&quot;http://code.google.com/p/gdata-java-client/downloads/list&quot;&gt;gdata-java-client&lt;/a&gt;
and
&lt;a href=&quot;http://code.google.com/p/google-collections/&quot;&gt;google-collections&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;gdata-client-1.0.jar&lt;/li&gt;
&lt;li&gt;gdata-client-meta-1.0.jar&lt;/li&gt;
&lt;li&gt;gdata-core-1.0.jar&lt;/li&gt;
&lt;li&gt;gdata-analytics-2.1.jar&lt;/li&gt;
&lt;li&gt;gdata-analytics-meta-2.1.jar&lt;/li&gt;
&lt;li&gt;google-collect-1.0.jar&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After running &quot;lein deps&quot; add them to the lib/ subdirectory.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn service [username pass]
   (doto (AnalyticsService. &quot;Clojure_Incanter_Sample&quot;)
     (.setUserCredentials username pass)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to retrieve data we need a service object which handles all
interaction between our application and Analytics Data Export API.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn account-feed [service &amp;amp; args]
   (let [url (URL. (str &quot;https://www.google.com/analytics/&quot;
                        &quot;feeds/accounts/default?max-results=50&quot;))
         feed (.getFeed service url (get-class &quot;AccountFeed&quot;))
         accs (reduce #(assoc %1 
                         (-&amp;gt; %2 .getTitle .getPlainText)
                         (-&amp;gt; %2 .getTableId .getValue)) 
                      {} (.getEntries feed))]
     (if (nil? args) accs (accs (first args)))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To retrieve data for a profile, we need its table id. Asking service for
an account feed, returns a list of entries containing title, table id and
profile id but we are only interested in title and table id.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn data-feed [service &amp;amp; args]
   (let [args (apply hash-map args)
         feed (.getFeed service (.getUrl (query args)) (get-class &quot;DataFeed&quot;))
         cols (map #(str &quot;ga&quot; %) (concat (:dimensions args) (:metrics args)))]
     (map (fn [e]
            (map #(.stringValueOf e %) cols))
          (.getEntries feed))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As with the account feed, first thing we need to do is build a feed
request URL, query function handles that nothing fancy, it just calls a
bunch of setters for dimensions, metrics etc. Querying analytics service
with a data feed URL returns a list of entries, data-feed maps over them
and returns a sequence containing dimensions and metrics we requested.&lt;/p&gt;

&lt;p&gt;Now that we have some data to play with, we can start off by doing
fairly standard things, like which pages got the most visits for the
past month,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;   (def analytics (service &quot;username&quot; &quot;password&quot;))
   (def acc-nakkaya (account-feed analytics &quot;nakkaya.com&quot;))

   (def pageview (data-feed analytics 
                            :date [&quot;2010-01-26&quot; &quot;2010-02-25&quot;]
                            :dimensions [:pageTitle :pagePath]
                            :metrics [:pageviews]
                            :sort [:pageviews]
                            :num-result 10
                            :id acc-nakkaya))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is where incanter makes things fun, as long as you have a sequence
of rows, in this case what data-feed returns you can call view to
visualize the data, &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(view pageview)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;/images/post/analytics_incanter_1.png&quot; alt=&quot;incanter dataset&quot; /&gt;&lt;/p&gt;

&lt;p&gt;or we can filter the data leaving only portions of it which we are
interested, such as pages with views more than 200 and lower than 800,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;   (with-data (col-names (map (fn [[x y z]] [x y (BigInteger. z)]) pageview)
                         [:title :path :views])
     (view ($where {:views {:$gt 200 :$lt 800}})))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Alternatively you can filter the data in Clojure, requesting top 10
keywords people used to find your website and filtering the ones that
contain &quot;clojure&quot; or &quot;java&quot; in them,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;   (def keywords (data-feed analytics 
                            :date [&quot;2010-01-26&quot; &quot;2010-02-25&quot;]
                            :dimensions [:keyword]
                            :metrics [:visits]
                            :sort [:visits]
                            :num-result 10
                            :id acc-nakkaya))

    (let [words [&quot;clojure&quot; &quot;java&quot;]] 
      (reduce (fn[h v]
                (if (some true? (map #(.contains (first v) %) words))
                  (conj h v) h)) [] keywords))

 analytics.core=&amp;gt; [(&quot;clojure xml&quot; &quot;62&quot;) (&quot;clojure turtle graphics&quot; &quot;31&quot;)
                   (&quot;clojure opencv&quot; &quot;26&quot;) (&quot;detect faces from webcam+java&quot; &quot;26&quot;)]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Besides visualizing stuff using tables, we can plot graphs containing
the information we are intrested,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;   (def browsers (data-feed analytics 
                            :date [&quot;2010-01-26&quot;]
                            :dimensions [:browser]
                            :metrics [:visits]
                            :sort [:visits]
                            :num-result 10
                            :id acc-nakkaya))

   (view (bar-chart (take 4 (map first browsers))
                    (take 4 (map #(BigInteger. (last %)) browsers))
                    :title &quot;Browser/Visits&quot;
                    :x-label &quot;Browsers&quot;
                    :y-label &quot;Visits&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;/images/post/analytics_incanter_2.png&quot; alt=&quot;incanter bar-chart plot&quot; /&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;   (def view-date (data-feed analytics 
                             :date [&quot;2009-11-26&quot; &quot;2010-02-25&quot;]
                             :dimensions [:date]
                             :metrics [:visitors]
                             :sort [:visitors]
                             :num-result 10
                             :id acc-nakkaya))

   (view (line-chart (map first view-date)
                     (map #(BigInteger. (last %)) view-date)
                     :title &quot;Visits&quot;
                     :x-label &quot;Date&quot;
                     :y-label &quot;Visits&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;/images/post/analytics_incanter_3.png&quot; alt=&quot;incanter line-chart plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/code/clojure/analytics.clj&quot;&gt;analytics.clj&lt;/a&gt;&lt;/p&gt;
</description></item><item><title>Writing Leiningen Plugins 101</title><link>http://nakkaya.com/2010/02/25/writing-leiningen-plugins-101/</link><description>&lt;p&gt;I&apos;m trying to switch, building my projects using
&lt;a href=&quot;http://ant.apache.org/&quot;&gt;Ant&lt;/a&gt; to
&lt;a href=&quot;http://github.com/technomancy/leiningen&quot;&gt;leiningen&lt;/a&gt;. Almost all of them
requires customs tasks such as building native executables, move files
around etc. Which requires I have to come up with a lein plugin for each
ant task, unfortunately not much documentation exists about writing
lein plugins, this post collects bits and pieces of information I
gathered over the web.&lt;/p&gt;

&lt;p&gt;To begin with lein tasks are functions named &quot;your-task&quot; defined in the
namespace &quot;leiningen.your-task&quot;. They take a project argument containing
information defined in defproject and command-line arguments. For simple
tasks or quickly testing something, you can simply define them in
project.clj after the defproject definition,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (ns leiningen.foo)
 (defn foo [project &amp;amp; args] (println &quot;Hello Foo!!&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now lein should have a new task named foo, running it should print
&quot;Hello Foo!!&quot;. Of course for longer tasks, you are not going to want it
cluttering your project.clj, they can be placed under leiningen/ folder
&lt;strong&gt;not&lt;/strong&gt; src/leiningen/. Since tasks are just functions, making a task
depend on another task is as easy as calling depencies on top of the
function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; ;;leiningen/bar.clj
 (ns leiningen.bar)

 (defn bar [projects &amp;amp; args] 
   (apply leiningen.foo/foo projects args)
   (println &quot;Hello Bar!!&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now running bar task should give you, &quot;Hello Foo!!&quot; and &quot;Hello
Bar!!&quot;. For sharing plugins across projects create a separate lein
project for the plugin, after creating a Jar with &quot;lein jar&quot; you have two
options, you can either push it to clojars and add your plugin as a
dev-dependency for your project or just move the jar to the lib folder
of the project, either way lein will pick it up.&lt;/p&gt;
</description></item><item><title>Applescript with Clojure</title><link>http://nakkaya.com/2010/02/21/applescript-with-clojure/</link><description>&lt;p&gt;Today I was experimenting with
&lt;a href=&quot;http://en.wikipedia.org/wiki/AppleScript&quot;&gt;AppleScript&lt;/a&gt; engine thats
included with Java 1.6. It makes it much easier to interact with OS X
then executing osascript using Runtime.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (let [mngr (javax.script.ScriptEngineManager.)
       engine (.getEngineByName mngr &quot;AppleScript&quot;)] 
   (.eval engine &quot;say \&quot;Hello World!\&quot;&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For simple stuff, it is as simple as asking engine manager for the
AppleScript engine and running eval on it with your script.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (def tracks (str &quot;tell application \&quot;iTunes\&quot;\n&quot;
                  &quot;get count of tracks of (get view of front window)\n&quot;
                  &quot;end tell\n&quot;))

 (let [mngr (javax.script.ScriptEngineManager.)
       engine (.getEngineByName mngr &quot;AppleScript&quot;)] 
   (.eval engine tracks))

user=&amp;gt; 5229
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When eval returns, numbers, strings, and dates are coerced into
java.lang.Double, java.lang.String, and java.util.Calendar. Collections
like lists and properties are recursively converted into
java.util.Lists, and java.util.Maps. Unknown types are usually described
as a string.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (def play (str &quot;on playNamedList(thisName)\n&quot;
                &quot;tell application \&quot;iTunes\&quot;\n&quot;
                &quot;play playlist thisName\n&quot;
                &quot;end tell\n&quot;
                &quot;end playNamedList\n&quot;))

 (let [mngr (javax.script.ScriptEngineManager.)
       engine (.getEngineByName mngr &quot;AppleScript&quot;)
       context (.getContext engine)
       bindings (.getBindings context javax.script.ScriptContext/ENGINE_SCOPE)]
   (.put bindings &quot;javax_script_function&quot;, &quot;playNamedList&quot;)
   (.put bindings javax.script.ScriptEngine/ARGV &quot;chill&quot;)
   (.eval engine play))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to invoke calls that expects arguments to be set, we need to
invoke the AppleScript method using &quot;javax_script_function&quot; engine
binding. Overall it beats running osascript and parsing return values,
but it still needs more documentation.&lt;/p&gt;
</description></item><item><title>net-eval - Dead Simple Distributed Computing for Clojure</title><link>http://nakkaya.com/2010/02/16/net-eval-dead-simple-distributed-computing-for-clojure/</link><description>&lt;p&gt;&lt;a href=&quot;http://newlisp.org&quot;&gt;newlisp&lt;/a&gt; has this function called net-eval which
allows you to distribute work across a bunch of remote nodes. Over the
weekend I have put together a small &lt;a href=&quot;/net-eval.markdown&quot;&gt;library&lt;/a&gt;, which
more or less works the same way. The idea behind net-eval is simple, you
fire up a REPL server on the remote nodes, expressions are transferred
through a socket evaluated and results returned.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (deftask ping []
   (str &quot;Pong: &quot; (System/getProperty &quot;os.name&quot;)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We begin by defining tasks for code we want to evaluate on the remote
nodes, deftask macro takes the body, defines a function and adds body of
the task as a list to the functions meta data. You can treat tasks as
functions, call them debug them just like any other Clojure function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (let [response (net-eval [[&quot;127.0.0.1&quot; 9999 #&apos;ping]
                           [&quot;10.211.55.3&quot; 9999 #&apos;ping]])]
   (println (map deref response)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;net-eval does all the housekeeping required to connect to remote nodes,
transfer functions to execute, and collect the results. net-eval takes a
sequence of vectors containing host, port and a task to execute if there
are arguments to be passed, they are appended to the end. net-eval will
return a sequence of future objects, each containing response from one
of the nodes.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(Pong: Mac OS X Pong: Windows 2000)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, care must be taken. It is not a good idea to have a REPL server
listening on a public IP, you are basically giving away unrestricted
shell access to anyone. I advise using net-eval behind a firewall or on
a segregated network. If you really really need to run commands across
the internet tunnel the connection through SSH.&lt;/p&gt;

&lt;p&gt;A more useful example other than playing ping-pong with the remotes
would be implementing poor man&apos;s
&lt;a href=&quot;http://en.wikipedia.org/wiki/MapReduce&quot;&gt;MapReduce&lt;/a&gt;. Following snippet
defines a task that will download a file, split it into words and count
them, it maps a bunch of nodes to a bunch of documents and sends
documents for processing, when all nodes return we sum the word count
print total numbers words across documents.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (def docs [;; A Comedy of Masks - Ernest Dowson and Arthur Moore, 547KB
            &quot;http://www.gutenberg.org/files/16703/16703.txt&quot;
            ;; The Adventures of Sherlock Holmes - Conan Doyle, 576KB
            &quot;http://www.gutenberg.org/dirs/etext99/advsh12.txt&quot;
            ;; The tale of Beowulf - anonymous, 219KB
            &quot;http://www.gutenberg.org/files/20431/20431-8.txt&quot;])

 (def nodes [[&quot;127.0.0.1&quot; 9999]
             [&quot;127.0.0.1&quot; 9999] 
             [&quot;10.211.55.3&quot; 9999]])

 (deftask word-count [doc]
   (with-open 
       [stream (.openStream (java.net.URL. doc))]
       (let [buf (java.io.BufferedReader. 
                  (java.io.InputStreamReader. stream))]
         (count (re-seq #&quot;\w+&quot; (.toLowerCase (apply str (line-seq buf))))))))

 (defn map-jobs []
    (map #(conj (first %) #&apos;word-count (second %))
         (partition 2 (interleave nodes docs))))

 (let [response (map deref (net-eval (map-jobs)))]
   (println &quot;Total: &quot; (apply + response)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For processing large files, you can use compojure to transfer files
across machines, if you build the library using lein, transferring
uberjar to remote nodes is all thats needed, running uberjar will
automatically start a REPL server.&lt;/p&gt;
</description></item><item><title>A Simple Clojure IRC Client</title><link>http://nakkaya.com/2010/02/10/a-simple-clojure-irc-client/</link><description>&lt;p&gt;The other night I was toying with the following script, I was going to
thrash it but figured it may help someone or me later on so I am dumping
it here. It doesn&apos;t do anything other then to sit idle in a channel,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (ns irc
   (:import (java.net Socket)
            (java.io PrintWriter InputStreamReader BufferedReader)))

 (def freenode {:name &quot;irc.freenode.net&quot; :port 6667})
 (def user {:name &quot;Nurullah Akkaya&quot; :nick &quot;nakkaya&quot;})

 (declare conn-handler)

 (defn connect [server]
   (let [socket (Socket. (:name server) (:port server))
         in (BufferedReader. (InputStreamReader. (.getInputStream socket)))
         out (PrintWriter. (.getOutputStream socket))
         conn (ref {:in in :out out})]
     (doto (Thread. #(conn-handler conn)) (.start))
     conn))

 (defn write [conn msg]
   (doto (:out @conn)
     (.println (str msg &quot;\r&quot;))
     (.flush)))

 (defn conn-handler [conn]
   (while 
    (nil? (:exit @conn))
    (let [msg (.readLine (:in @conn))]
      (println msg)
      (cond 
       (re-find #&quot;^ERROR :Closing Link:&quot; msg) 
       (dosync (alter conn merge {:exit true}))
       (re-find #&quot;^PING&quot; msg)
       (write conn (str &quot;PONG &quot;  (re-find #&quot;:.*&quot; msg)))))))

 (defn login [conn user]
   (write conn (str &quot;NICK &quot; (:nick user)))
   (write conn (str &quot;USER &quot; (:nick user) &quot; 0 * :&quot; (:name user))))

 ;;(def irc (connect freenode))
 ;;(login irc user)
 ;;(write irc &quot;JOIN #clojure&quot;)
 ;;(write irc &quot;QUIT&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Lots of this code should be self-explanatory, calling connect will open
a socket to the server, it will return a ref containing a reader and a
writer associated with the socket, it will also spawn a new thread that
will handle incoming messages from the server.&lt;/p&gt;

&lt;p&gt;conn-handler will keep reading and printing from the socket until exit
key in the conn ref is set which happens when we receive a &quot;Closing
Link&quot; message from the server, every once in a while server will ping us
with &quot;PING :randomstring&quot; we need to reply &quot;PONG :randomstring&quot; else we
get disconnected. Thats all there is to it, as I said it doesn&apos;t do
anything but with a few regexes you can turn it in to client or a bot.&lt;/p&gt;
</description></item><item><title>Using Multiple Lisps with Inferior Lisp</title><link>http://nakkaya.com/2010/02/07/using-multiple-lisps-with-inferior-lisp/</link><description>&lt;p&gt;I was reading &lt;a href=&quot;http://www.paulgraham.com/onlisp.html&quot;&gt;On Lisp&lt;/a&gt; which
uses &lt;a href=&quot;http://en.wikipedia.org/wiki/Common_Lisp&quot;&gt;Common Lisp&lt;/a&gt; through out
the book, so I needed a quick way to switch between lisps, following is
a quick hack to switch between different lisp programs. When you call
na-run-lisp without any prefix it will run the first item in
lisp-programs, when called with a prefix you can select which lisp to
run.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (setq lisp-programs 
       (list (list &quot;clojure&quot; clojure-command)
             (list &quot;sbcl&quot; &quot;/opt/local/bin/sbcl&quot;)))

 (defun na-run-lisp (arg)
   (interactive &quot;P&quot;)
   (if (null arg)
       (run-lisp (second (first lisp-programs)))
     (let (choice) 
       (setq choice (completing-read &quot;Lisp: &quot; (mapcar &apos;first lisp-programs)))
       (dolist (l lisp-programs)
         (if (string= (first l) choice)
             (run-lisp (second l)))))))
&lt;/code&gt;&lt;/pre&gt;
</description></item><item><title>Etch A Sketch</title><link>http://nakkaya.com/2010/02/02/etch-a-sketch/</link><description>&lt;p&gt;&lt;img src=&quot;http://farm5.static.flickr.com/4052/4322207526_3384ff2e84.jpg&quot; alt=&quot;clodiuno etch a sketch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A small Sunday hack inspired by the classical children&apos;s toy, for this
project you need two potentiometers, connected to analog pins 0 and 1,
you can grab the fritzing file &lt;a href=&quot;/code/clodiuno/sketch/sketch.fz&quot;&gt;here&lt;/a&gt;,&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://farm5.static.flickr.com/4011/4322207530_259a12f8e2_o.png&quot; alt=&quot;etch a sketch clodiuno&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Idea behind the project is simple, we read potentiometers, turn the
values read into x and y coordinates for the turtle then command turtle
to go to that coordinate.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; ;;WMath.cpp
 (defn map-range [x in-min in-max out-min out-max]
   (+ (/ (* (- x in-min) (- out-max out-min)) (- in-max in-min)) out-min))

 (defn read-knobs [board]
   (let [potx (analog-read board potx-pin)
         poty (analog-read board poty-pin)
         x (int (map-range 
                 potx 0 1024 (- (/ sketch-width 2)) (/ sketch-width 2)))
         y (int (map-range 
                 poty 0 1024 (- (/ sketch-height 2)) (/ sketch-height 2)))]
     {:x x :y y}))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Potentiometers returns values between 0 and 1024, assuming our image is
600 by 400, we need to map these values between -300 to 300 on the x
axis and -200 to 200 on the y axis, 0,0 being the center of the image.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn panel [board turtle]
   (proxy [JPanel ActionListener] []
     (paintComponent
      [g]
      (doto g
        (.setColor Color/red)
        (.fill (RoundRectangle2D$Double.
                0 0 window-width window-height 60 60))
        (.setColor Color/black)
        (.drawImage (:image @turtle) pad pad this)
        (.setColor Color/white)
        (.fill (Ellipse2D$Double. pad 430 40 40))
        (.fill (Ellipse2D$Double. (- sketch-width pad) 430 40 40))))
     (actionPerformed 
      [e] 
      (let [knobs (read-knobs board)]
        (go turtle (:x knobs) (:y knobs)))
      (.repaint this))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With every tick of the timer, we&apos;ll read the potentiometers, then
command the turtle to goto that position and repaint the panel to
reflect changes.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn key-listener [board frame timer]
   (proxy [KeyAdapter] [] 
     (keyReleased 
      [e]
      (.stop timer)
      (close board)
      (.setVisible frame false))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the sketch window receives a key event, we stop the timer,
disconnect arduino and hide the window.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn init-arduino []
   (let [board (arduino &quot;/dev/tty.usbserial-A6008nhh&quot;)]
     (Thread/sleep 5000)
     (enable-pin board :analog potx-pin)
     (enable-pin board :analog poty-pin)
     board))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By default pins aren&apos;t read, you need to tell arduino which ports you
are interested, in this case we are interested in analog 0 and analog
1.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn init-turtle [board turtle]
   (let [knobs (read-knobs board)]
     (doto turtle
       (pen-up)
       (go (:x knobs) (:y knobs))
       (pen-down))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since we don&apos;t know the position of potentiometers when the application
starts, we need to read the values once and position the turtle
accordingly. When all the functions wired and timer started, you should
have your Etch A Sketch.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn sketch []
   (let [board  (init-arduino)
         turtle (turtle sketch-width sketch-height)
         panel  (panel board turtle)
         timer  (Timer. 50 panel)
         window (JFrame.)]
     (doto window
       (.add panel)
       (.addKeyListener (key-listener board window timer))
       (.setBackground (Color. 0 0 0 0))
       (.setUndecorated true)
       (.setAlwaysOnTop true)
       (.setSize (java.awt.Dimension. window-width (+ 25 window-height)))
       (.setVisible true))
     (init-turtle board turtle)
     (.start timer)))
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;/code/clodiuno/sketch/sketch.clj&quot;&gt;sketch.clj&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;/code/clodiuno/sketch/sketch.fz&quot;&gt;sketch.fz&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;/code/clojure/turtle.clj&quot;&gt;turtle.clj&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description></item><item><title>GZIP Output Compression in Compojure</title><link>http://nakkaya.com/2010/01/29/gzip-output-compression-in-compojure/</link><description>&lt;p&gt;Compression can be handled by the server, jetty or apache but I prefer
my applications handling most of their operations, so I settled on using a
middleware function to add compression to parts of my
application. Compojure uses middleware to selectively add functionality
to handlers such as sessions. middleware functions takes handlers, after
your handler completes processing the request, middleware gets a chance to
transform the response, giving you a tool for abstracting common
functionality.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn with-gzip [handler]
   (fn [request]
     (let [response (handler request)
           out (java.io.ByteArrayOutputStream.)
           accept-encoding (.get (:headers request) &quot;accept-encoding&quot;)]

       (if (and (not (nil? accept-encoding))
                (re-find #&quot;gzip&quot; accept-encoding))
         (do
           (doto (java.io.BufferedOutputStream.
                  (java.util.zip.GZIPOutputStream. out))
             (.write (.getBytes (:body response)))
             (.close))

           {:status (:status response)
            :headers (assoc (:headers response)
                       &quot;Content-Type&quot; &quot;text/html&quot;
                       &quot;Content-Encoding&quot; &quot;gzip&quot;)
            :body (java.io.ByteArrayInputStream. (.toByteArray out))})
         response))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;with-gzip handler first checks the client request, if the client
supports gzip compression, it uses GZIPOutputStream to compress the
response, add the header telling the client that it contains compressed
content. If client doesn&apos;t support gzip encoding response is not
compressed.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; (defn hello-world [request]
   {:status  200
    :headers {}
    :body    &quot;Hello, World!!&quot;})

 (decorate hello-world
   (with-gzip))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;decorate macro takes care of applying middleware to handler.&lt;/p&gt;
</description></item></channel></rss>
