<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>jcla1.com</title>
    <link>http://jcla1.com/</link>
    <atom:link href="http://jcla1.com/rss.xml" rel="self" type="application/rss+xml" />
    <description>A blog about tech.</description>
    <language>en-us</language>
    <pubDate>Mon, 19 Aug 2019 18:09:25 +0000</pubDate>
    <lastBuildDate>Mon, 19 Aug 2019 18:09:25 +0000</lastBuildDate>

    
    <item>
      <title>The Baby Emulator</title>
      <link>http://jcla1.com/blog/baby-emulator</link>
      <pubDate>Thu, 07 Aug 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/baby-emulator</guid>
      <description>&lt;p&gt;The &lt;a href=&quot;http://en.wikipedia.org/wiki/Manchester_Small-Scale_Experimental_Machine&quot;&gt;Manchester Small-Scale Experimental Machine (SSEM)&lt;/a&gt; aka: &quot;the Baby&quot; lay the foundations for all modern computing, being the first stored-program computer, and built to demonstrate the viability of the &lt;a href=&quot;http://en.wikipedia.org/wiki/Williams_tube&quot;&gt;Williams-Kilburn&lt;/a&gt; tube.&lt;/p&gt;
&lt;p&gt;Despite being a breakthrough computer during its lifetime, it had a very limited instruction set and store. Presenting only 32 words of memory (that's 1024 bits) to store both &lt;em&gt;program &amp; data&lt;/em&gt; and only 7 instructions to program in, it was still Turing complete and ran its &lt;a href=&quot;https://github.com/jcla1/gobaby/blob/b840eae8016ea30b0c98398d9c243015b163c22f/examples/factor.asm&quot;&gt;first program&lt;/a&gt; on June 21, 1948.&lt;/p&gt;
&lt;p&gt;Seeing it as a valuable history lesson (and because the &lt;a href=&quot;http://www.davidsharp.com/baby/applet.html&quot;&gt;other emulator&lt;/a&gt;, a Java applet, is very cumbersome to use), I decided to write a nice (and fast) emulator that can be used from the command line. And &lt;a href=&quot;https://github.com/jcla1/gobaby&quot;&gt;here&lt;/a&gt; it is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# It's on Github, of course: &lt;a href=&quot;https://github.com/jcla1/gobaby&quot;&gt;https://github.com/jcla1/gobaby&lt;/a&gt;
$ gobaby -t -l 27 -p=f examples/factor.asm
Execution took: 14.160445ms
Value at location #27: 131072&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This trivial program (finding the largest factor of 2^18, by going through each number down, starting with 2^18-1) was the first to be run on the Baby and it took ~52 minutes to get the answer back then.&lt;/p&gt;
&lt;p&gt;The emulator also supports printing out the memory contents as their equivalent assembly mnemonics (which is the default behaviour after execution), which makes it particularly useful when having to keep re-running programs, like this &lt;a href=&quot;https://github.com/jcla1/gobaby/blob/b840eae8016ea30b0c98398d9c243015b163c22f/examples/primegen.asm&quot;&gt;sucessive prime generator&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gobaby examples/primegen.asm | gobaby | gobaby -l 21 -p=f
Value at location #21: 5&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running this will give you the 3rd prime, and for all the ones following that, you've just got to keep on adding successive calls to &lt;code&gt;gobaby&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;So that's all there is to say about the emulator, to find out more about the Baby you should read David Sharp's &lt;a href=&quot;http://www.davidsharp.com/baby/NeilCroft-TechnicalIntroductionToProgrammingTheBabyv4.0.pdf&quot;&gt;Technical Introduction To Programming The Baby&lt;/a&gt; and of course its &lt;a href=&quot;http://en.wikipedia.org/wiki/Manchester_Small-Scale_Experimental_Machine&quot;&gt;Wikipedia article&lt;/a&gt;.

&lt;p&gt;Share and enjoy!&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Experiencing Haskell</title>
      <link>http://jcla1.com/blog/experiencing-haskell</link>
      <pubDate>Mon, 07 Jul 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/experiencing-haskell</guid>
      <description>&lt;p&gt;There seems to be a growing interest in (purely) functional languages these days. I've looked at lots of different languages in the past (such as Go, Python, Ruby and others) but never a (purely) functional one. So recently I decided to dig into Haskell, with a view to discovering some of the fundamental differences. I wanted to share some of my findings with you in this post.&lt;/p&gt;

&lt;h2&gt;The Type System&lt;/h2&gt;

&lt;p&gt;This is one of the things Haskell is exceptionally good at: types! It has a very strong static type system which is based on Hindley-Milner type inference, that allows the compiler to infer most if not all of the types at compile time. So only in edge cases, or for optimization purposes is the programmer forced to give type annotations. Another great feature of Haskell's type system is its support for type variables. It's Haskell's equivalent of C++ templates, and a feature Go is still missing. They allow for expressive type signatures and contraint based generic typing, i.e.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sort :: Ord a =&gt; [a] -&gt; [a]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This says that there's a function, called &lt;code&gt;sort&lt;/code&gt;, that takes a list with values of any type, &lt;em&gt;contrained by the typeclass &lt;code&gt;Ord&lt;/code&gt;&lt;/em&gt;, and then returns a value of the same type. Here the &lt;code&gt;Ord&lt;/code&gt; typeclass signifies that the values in the list have to be orderable. Now the &lt;code&gt;a&lt;/code&gt; could have also been any other string. But the point is, that just from the type signature it's immediately obvious what transformation the function applies to its arguments.&lt;/p&gt;

&lt;p&gt;Because of this expressiveness, there's a separate &lt;a href=&quot;http://www.haskell.org/hoogle/&quot;&gt;search engine&lt;/a&gt; that will search for functions with a given type signature (regardless of the variables used).&lt;/p&gt;

&lt;h2&gt;Algebraic Data Types&lt;/h2&gt;

&lt;p&gt;Another one of Haskell's interesting properties is its support for algebraic data types (ADTs). Think of an ADT as a type-safe version of a union in C. They let you describe data structures in terms of the possible values a variable of this type can have.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;data Tree a = Empty
          | Leaf a
          | Node (Tree a) (Tree a)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example we describe what a variable of type &lt;code&gt;Tree&lt;/code&gt; can be. A Tree is either Empty, or it's a Leaf, or it's a Node (where each node again, contains a tree itself). But that wasn't all, the &lt;em&gt;&lt;code&gt;a&lt;/code&gt;&lt;/em&gt; is a type variable for the ADT &lt;code&gt;Tree&lt;/code&gt;, so this is the implementation of a &lt;b&gt;generic&lt;/b&gt; tree-structure.&lt;/p&gt;

&lt;p&gt;These ADTs combined with Haskell's powerful pattern matching, allows for articulate function definitions. For example, the following function takes another function and returns a new tree with the same structure as the original one, but with all the values replaced with the output of the function, when passed the original value:&lt;/p&gt;

&lt;aside&gt;In a &lt;em&gt;real&lt;/em&gt; implementation you would consider the tree to be a functor, implement the &lt;code&gt;Functor&lt;/code&gt; typeclass and use &lt;code&gt;fmap&lt;/code&gt; instead, but that's a subject for another post.&lt;/aside&gt;

&lt;pre&gt;&lt;code&gt;mapTree :: (a -&gt; b) -&gt; Tree a -&gt; Tree b
mapTree _ Empty = Empty
mapTree f (Leaf x) = Leaf (f x)
mapTree f (Node l r) = Node (mapTree f l) (mapTree f r)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you see, we define the function in terms of the &quot;shape&quot; of its arguments. Mapping an empty tree, &lt;em&gt;is&lt;/em&gt; an empty tree, mapping a Leaf, is also a Leaf, but with the function applied, etc.&lt;/p&gt;

&lt;p&gt;Be careful though! Algebraic Data Types are not the solution to all problems. Sometimes they make implementing even the simplest data structures, like a doubly linked-list, near impossible.&lt;/p&gt;

&lt;h2&gt;Code Length &amp;amp; Execution Time&lt;/h2&gt;
&lt;p&gt;I was quite surprised about this, but from what I've found my Haskell programs are about the same length or even longer as equivalent versions in Python and I take a lot longer to write them, though that is probably due to my inexperience with Haskell's style of programming. But this chart from the &lt;a href=&quot;http://benchmarksgame.alioth.debian.org/u32q/benchmark.php?test=all&amp;lang=ghc&amp;lang2=python3&amp;data=u32q&quot;&gt;Computer Language Benchmarks Game&lt;/a&gt; shows that I'm not alone:&lt;/p&gt;

&lt;img src=&quot;http://benchmarksgame.alioth.debian.org/u32q/chartvs.php?r=eNodjskRAEEIAlNCFI8ozD%2BbHfdlYUGDT7dzo5KmjRlYrdMgW6ws4U9bkTyNCT4byu%2B0PN8zmqF1n6T%2FJrD6dNgfIo4mKGd%2B6LPb6wL8KpFTK8E6Njx0c4iKPnLlI9kEdEkXZR%2FUACdY&amp;m=eNozMFHwKs1RMDIwNFEoNTYqVMgDACljBJA%3D&amp;w=eNpLz0j2L6gsycjPMwYAGqEEVw%3D%3D&quot;&gt;

&lt;p&gt;Regarding execution time, my results don't match up with the above image. I found (when running a test with a simple log processing script) that the &lt;a href=&quot;https://gist.github.com/jcla1/addb4ab8a20aef2fb862#file-activitylog-hs&quot;&gt;Haskell version&lt;/a&gt; performs significantly slower (&gt;200x slower) than the &lt;a href=&quot;https://github.com/jcla1/quantified_self/blob/e8b7e64931161c116b2e37400e3b0d866acfa9da/collectors/activity.py&quot;&gt;Python version&lt;/a&gt;. From what I've heard though, Haskell's built-in list, which is used extensively in the example, is notoriously slow. I should've instead used a faster list data structure like: &lt;a href=&quot;http://www.haskell.org/ghc/docs/latest/html/libraries/containers-0.5.5.1/Data-Sequence.html#t:Seq&quot;&gt;Data.Sequence.Seq&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Wrapping Up&lt;/h2&gt;

&lt;p&gt;So you can see, Haskell has quite a few interesting features, that when using them, it feels like you're learning to program for the first time again. Nevertheless you should absolutely try it out and have your mind reprogrammed!&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Optimizing page timings for Google Analytics</title>
      <link>http://jcla1.com/blog/optimizing-google-analytics</link>
      <pubDate>Sat, 07 Jun 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/optimizing-google-analytics</guid>
      <description>&lt;p&gt;Many of you will have one of those recreational text pads where you jot down some notes you wanted to share with others. Like a blog. Sometimes, or in fact very often, you might want to track just &lt;em&gt;how&lt;/em&gt; successful these quick notes are. Well you'll probably already know about Google Analytics.&lt;/p&gt;
&lt;p&gt;It's one of those tools that everyone uses, it's free, it's easy, but it doesn't solve the problem completely. What I'm talking about is that Google Analytics' page timings are just plain bad when it comes to blogs.&lt;/p&gt;
&lt;p&gt;Let's consider the situation : Someone visits your blog from a link aggregator, via an RSS reader or from lumpa-land. What will happen is, the visitor reads your article, hopefully likes it, and then leaves your site. Now this is the ideal situation for showcasing where Google Analytics is lacking somewhat.&lt;/p&gt;
&lt;p&gt;This legitimite visitor, that may have even liked your blog post! will be recorded. Of course, you've got Google Analytics installed, that's why, but he will be saved as a bounce off of your site with zero pageview time. So the Google Analytics dashboard will tell you something like this: &lt;/p&gt;
&lt;img src=&quot;/public/img/low-page-time.jpg&quot;&gt;
&lt;aside&gt;Don't be fooled by the Avg. session duration graph, it only looks spikey, most values there are in fact less than one minute.&lt;/aside&gt;
&lt;p&gt;&lt;q&gt;Now this surely can't be right, it's impossible to read my blog posts in just 44 seconds&lt;/q&gt;, you may think. Well, often you're correct, it's Google Analytics' fault that the average session duration is &lt;em&gt;so&lt;/em&gt; low. But instead of complaining about this, let's fix it!&lt;/p&gt;

&lt;h2&gt;1st attempt&lt;/h2&gt;

&lt;p&gt;Now let's consider why Google Analytics' page timings are incorrect. Well the root of the cause is that the way Google Analytics measures the time spent on a page, they calculate it by taking the difference in time between visiting different pages.&lt;/p&gt;
&lt;p&gt;Ah, see here's the problem! On a blog, like in our scenario, a visitor will only be visiting the one blog post he navigated to in the first place. So there's no opportunity for Google Analytics to calculate a proper page timing! We can easily fix that.&lt;/p&gt;
&lt;p&gt;Because Google Analytics will also consider events as pageviews when it comes to calculating the session duration. All we need to do is send off an event at the appropriate time... but when is the appropriate time?&lt;/p&gt;
&lt;p&gt;This is a tough question and it's very hard to answer, so let's send one every ten seconds, just to make sure. Here's the adjusted Google Analytics snippet:&lt;/p&gt;
&lt;aside&gt;The grayed-out parts of the code, are the default Google Analytics provides for you.&lt;/aside&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;ga('create', 'UA-XXXXXXXX-X', 'example.com');
ga('send', 'pageview');&lt;/span&gt;

setTimeout((function(timing) {
    ga('send', 'event', 'time', 'log', timing);

    // Bind another timeout to run in 10s
    // to fire off the next event
    setTimeout(arguments.callee.bind(null, timing+10), 10000);
}).bind(null, 10), 10000);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now what does that give us? Let's see:&lt;/p&gt;
&lt;img src=&quot;/public/img/high-page-time-1.jpg&quot;&gt;
&lt;p&gt;Ah, that's what I like to see! We've got a 3,331.25% &lt;em&gt;increase&lt;/em&gt; in the average session duration and the bounce rate &lt;em&gt;dropped&lt;/em&gt; by 91.54%. So this solution seems to work, or does it? Because I think 26 mins is a bit too long for reading my relatively short blog posts.&lt;/p&gt;
&lt;p&gt;Maybe we can find an explanation by adjusting our situation: Now, the visitor visits your page from a link aggregator and if I think about the way I use link aggregators, I'll exit them with 20 new tabs open.&lt;/p&gt;
&lt;p&gt;See, there might be the cause! The visitor opens your blog post, but he may not actually view it until he's finished dealing with the other 19 tabs. This wasn't a problem when Google Analytics had to figure the average time out by itself, because most recorded timings were zero.&lt;/p&gt;
&lt;p&gt;But now this has changed! Once a user opens the tab with your page loaded in it, we're telling Google Analytics that the visitor is on your site! So that's the next problem to fix!&lt;/p&gt;

&lt;h2&gt;2nd attempt&lt;/h2&gt;

&lt;p&gt;As I said, we need to find out, when the user actually starts viewing your blog post. But how are we going to do that? Well, this is the ideal situation to show off the relatively new &lt;a href=&quot;http://www.w3.org/TR/page-visibility/&quot;&gt;Page Visibility API&lt;/a&gt;. It can tell us if the browser's frontmost tab contains our site, or not.&lt;/p&gt;
&lt;p&gt;This should deliver a more accurate measure of when the page is actually viewed and read. But we can't just wait until a user views our page, i.e. the visibility event fires, because the user might just flit briefly over the tab, when navigating between them, for example.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;ga('create', 'UA-XXXXXXXX-X', 'example.com');&lt;/span&gt;
track_ga();

function track_ga() {
    // We can be quite sure that the user _is_ on our page,
    // once he's there for more than 10s
    var waiting_time = 10000;

    // Just send the pageview if page visibility is not supported
    if (!get_hidden_prop()) {
        ga('send', 'pageview');
        return;
    }

    if (!is_hidden()) {
        // If the page is visible, setup a timeout to send
        // the pageview, that gets cancelled when the user
        // navigates away from the page too soon.
        var timeout = setTimeout(function() {
            ga('send', 'pageview');
            setTimeout(event_poller.bind(null, 0, waiting_time), waiting_time);
        }, waiting_time);

        document.addEventListener('visibilitychange', function() {
            document.removeEventListener('visibilitychange', arguments.callee);
            if (is_hidden()) clearTimeout(timeout);
        });
    } else {
        // Otherwise, wait until the page becomes visible again
        // and do everything over again.
        document.addEventListener('visibilitychange', function() {
            document.removeEventListener('visibilitychange', arguments.callee);
            track_ga();
        });
    }
}

// Same as our previous periodic GA event sender.
function event_poller(timing, wait) {
    ga('send', 'event', 'time', 'log', String(timing));
    setTimeout(event_poller.bind(null, timing + wait / 1000, wait), wait);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The functions &lt;code&gt;get_hidden_prop()&lt;/code&gt; &amp;amp; &lt;code&gt;is_hidden()&lt;/code&gt; are from, and can be found on HTML5Rocks.com &lt;code&gt;get_hidden_prop()&lt;/code&gt; checks to see if the Page Visibility API is supported and for any vendor specific prefixes. &lt;code&gt;is_hidden()&lt;/code&gt;, obviously, returns true/false depending on if the page is visible.&lt;/p&gt;
&lt;p&gt;As you see, this version is a lot more complicated than our initial snippet, but will it improve our measurements?&lt;/p&gt;

&lt;img src=&quot;/public/img/high-page-time-2.jpg&quot;&gt;

&lt;p&gt;Hmm, no not really. So it seems, that's the best we can get with this technique.&lt;/p&gt;

&lt;h2&gt;Final thoughts&lt;/h2&gt;

&lt;p&gt;Although our second attempt didn't yield the expected results, I can still confidently say, that the second snippet is better than the first. For one, it saves resources (network), due to the fact that we only start sending events once the user is actually active on your site, which is especially important if you've got a lot of mobile vistors reading your blog. And the page timings are definitely more accurate than with the default page timing mechanism. But with the second snippet we also get insight into when our pages are just prerendered.&lt;/p&gt;
&lt;p&gt;So as you see, there doesn't seem to be a perfect solution, yet.&lt;/p&gt;</description>
    </item>
    
    <item>
      <title>Improving Go cookie handling</title>
      <link>http://jcla1.com/blog/improving-go-cookie-handling</link>
      <pubDate>Mon, 19 May 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/improving-go-cookie-handling</guid>
      <description>&lt;p&gt;Many people argue, a lot of Go's popularity comes from developers moving to Go from Ruby &amp; Python. And in a way, that may certainly be the case. Because Go, like Python famously, also has Batteries Included &amp;reg;, one of the many reasons I love the language.&lt;/p&gt;
&lt;p&gt;But like everything in the world, Go has its little idiosyncrasies. It's desperately trying to be RFC conformant with its cookie mechanism. Which is the reason, why certain cookies are just ignored by Go's cookiejar. In particular, Go just ignores cookies that contain characters like: \ (backslash) or &quot; (double quotes).&lt;/p&gt;
&lt;p&gt;Now there might have been good reasons to exclude these from the set of valid characters, i.e. it's obviously necessary to exclude a semi-colon, the cookie delimiter. But nevertheless, there may be situations in which Go will have to put up with servers sending cookie headers which are, acording to the RFC, just plain wrong and invalid.&lt;/p&gt;
&lt;p&gt;And this is exactly the situation I encountered! For &lt;a href=&quot;https://github.com/jcla1/goquizduell&quot;&gt;a Quizduell API library&lt;/a&gt; I was working on, I also had to talk to their 3rd-party server. And, you guessed it, they sent invalid cookies!&lt;/p&gt;
&lt;p&gt;So after about 3 hours, the time it took me to debug why all API calls weren't authenticated, I came across &lt;a href=&quot;https://code.google.com/p/go/issues/detail?id=7243&quot;&gt;an issue&lt;/a&gt; on the Go issue tracker, where a similar problem to mine was explained (basically, someone wanted to be able to have commas in cookies). And though the issue was resolved and a patch to allow commas in cookies was merged, the comments clearly indicated that the Go maintainers weren't happy with the idea of loosening the cookie character restrictions (although most browsers allow practically any character in a cookie).&lt;/p&gt;
&lt;p&gt;Knowing that my problem was an acknowleged issue, I was still left with my problem, that I needed to fix. Looking for a solution, that was &lt;em&gt;not&lt;/em&gt; copying the whole cookiejar implementation to a new package and just modifying this tiny function that checked wether a character is valid or not, I came up with the following solution:&lt;/p&gt;

&lt;aside&gt;I was looking to replace backslashes, but this should work with any character. Just modify the the character string that gets replaced.&lt;/aside&gt;

&lt;pre&gt;&lt;code&gt;cookie := response.Header.Get(&quot;Set-Cookie&quot;)
if cookie != &quot;&quot; {
    cookie = strings.Replace(cookie, &quot;\\&quot;, &quot;_&quot;, -1)
    response.Header.Set(&quot;Set-Cookie&quot;, cookie)
    c.Jar.SetCookies(request.URL, response.Cookies())
}
&lt;/code&gt;&lt;/pre&gt;

&lt;aside&gt;In the code example, &lt;code&gt;c&lt;/code&gt; is the API client that has his own cookiejar, since the http client's jar is private.&lt;/aside&gt;

&lt;p&gt;Simply put, this snippet just takes the raw cookie string and replaces, in this case, the backslash with an underscore (a character known not to occur in cookies issued by the Quizduell servers), puts the cookie back into the http response and manually tells the API client's cookiejar to store the cookies of this particular response. Notice, you need your own cookiejar (&lt;code&gt;c.Jar&lt;/code&gt;), since the one included in http clients is private.&lt;/p&gt;

&lt;p&gt;The following snippet, that loads the cookies stored in our cookiejar and attaches them to a new http request, is a bit more complicated, because it needs to handle the case of there already being other cookies that were set previously on the request.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cookies := c.Jar.Cookies(request.URL)
if len(cookies) &gt; 0 {
    for _, cookie := range cookies {
        s := cookie.Name + &quot;=\&quot;&quot; + cookie.Value + &quot;\&quot;&quot;
        s = strings.Replace(s, &quot;_&quot;, &quot;\\&quot;, -1)

        if c := request.Header.Get(&quot;Cookie&quot;); c != &quot;&quot; {
            request.Header.Set(&quot;Cookie&quot;, c+&quot;; &quot;+s)
        } else {
            request.Header.Set(&quot;Cookie&quot;, s)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But the idea is the same, load the cookie as a raw string, replace the underscores with the forbidden backslashes and manually attach the cookie as a header on the request.&lt;/p&gt;
&lt;p&gt;And it works! Perfectly fine in fact. Though as you can guess, this is not the ideal solution for all possible situations. We quickly run into a problem if there's no character where we know that it won't occur in the cookie (in our case that was the underscore, incase you haven't noticed yet).&lt;/p&gt;
&lt;p&gt;A possible workaround would be to base64 encode the relevant cookies and store the encoded version in the cookiejar.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>100 Days of Github</title>
      <link>http://jcla1.com/blog/100-days-of-github</link>
      <pubDate>Tue, 08 Apr 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/100-days-of-github</guid>
      <description>&lt;p&gt;In recent times &lt;a href=&quot;https://ryanseys.com/blog/177-days-of-github/&quot;&gt;there's been&lt;/a&gt; &lt;a href=&quot;http://natashatherobot.com/streak-github-mistakes/&quot;&gt;a trend&lt;/a&gt; &lt;a href=&quot;http://danwin.com/2013/12/github-activity-for-2013-1500-commits-52-day-streak/&quot;&gt;coming up&lt;/a&gt;, of having &lt;i&gt;long&lt;/i&gt; commit streaks on Github. Be it for fun, &lt;a href=&quot;http://dontbreakthechain.com/&quot;&gt;motivational purposes&lt;/a&gt; or just out of boredom. In any case, I decided to also hop onto the train and try it for myself. In the following, I'd like to share my experience with you as to what helped me get through my first 100 day commit streak on Github.&lt;/p&gt;

&lt;h2&gt;An open source project&lt;/h2&gt;
&lt;p&gt;Github is a platform for open source projects, so to build up your commit streak it will obviously be a great help to either contribute regularly to or even maintain an open source project, or multiple projects. This has saved me a few times during my streak, because as Ryan Seys already noticed in his &lt;a href=&quot;https://ryanseys.com/blog/177-days-of-github/&quot;&gt;blog post&lt;/a&gt; about commit streaks:&lt;/p&gt;
&lt;blockquote&gt;Pull requests count for 1 contribution when you make them and another contribution if they are merged. If they don’t get merged, sorry, no second contribution.&lt;/blockquote&gt;
&lt;p&gt;So no need to directly send a pull request (PR) when you push, you can take your time knowing that your PR will also count as a contribution. Plus if you get promoted to contributor status in a repository, your merge commits (of other PRs) also count as contributions.&lt;/p&gt;
&lt;p&gt;In my case, I contributed to a &lt;a href=&quot;https://github.com/kennyledet/Algorithm-Implementations&quot;&gt;repository of algorithms&lt;/a&gt;, which you should go check out (pun definitely intended) and contribute to. This repository also has the nice effect that there's a near infinite number of algorithms to implement (combined with an equally large number of different languages), so you won't run out of things to implement and might even learn a new language.&lt;/a&gt;

&lt;h2&gt;A blog&lt;/h2&gt;

&lt;p&gt;Blogs are the medium of developers &amp;mdash; it's through blogs that developer communicate and share their thoughts &amp;amp; ideas. So there is no reason why blogs (specifically your blog) should be excluded from your achievements as a developer, your commit streak.&lt;/p&gt;
&lt;p&gt;Be it writing posts or just drafting them, adding &lt;a href=&quot;https://schema.org/BlogPosting&quot;&gt;microdata markup&lt;/a&gt; (which is what I did) or completely redesigning them, you will definitely profit from maintaining a blog as a developer and so will your commit streak. As you see a blog is key, not just for your commit streak, but for your existence as a developer.&lt;/p&gt;

&lt;h2&gt;Programmer's challenges&lt;/h2&gt;
&lt;p&gt;This is a topic for another post, but for now what I recommend you do is: Keep a list of interesting challenges to solve, they needn't be programming related, but most of them will be (hopefully). To get you started on your list I can highly recommend Jason Rudolph's &lt;a href=&quot;http://jasonrudolph.com/blog/2011/08/09/programming-achievements-how-to-level-up-as-a-developer/&quot;&gt;Programming Achievements&lt;/a&gt;, Matt Might's &lt;a href=&quot;http://matt.might.net/#teaching&quot;&gt;course work assignments&lt;/a&gt; (especially the &lt;a href=&quot;https://github.com/mattmight/utah-sldi-sp2014-p1/blob/18e2393bfe13827c33b152b69340cad8bbb1d376/README.md&quot;&gt;scripting language assignments&lt;/a&gt;) and of course the exercises from The Structure and Interpretation of Computer Programs (SICP). Of course, for this to be beneficial to your commit streak it needs to be in a Github repository, so no solving Project Euler problems ;-) !&lt;/p&gt;

&lt;h2&gt;Final thoughts&lt;/h2&gt;
&lt;p&gt;Beyond all this, the most important thing is you. Well not really, it's your &lt;i&gt;ideas&lt;/i&gt;. They are what make your streaks possible in the first place, so they'd better be good ones. But I digress.&lt;/p&gt;
&lt;p&gt;Just make sure you have fun and get over the first two weeks, those are the hardest. So with this in mind, onwards and upwards! 200 days of Github, hopefully see you then.&lt;/p&gt;

&lt;img src=&quot;/public/img/streak-100.png&quot;&gt;</description>
    </item>
    
    <item>
      <title>FOSDEM 2014 lightning talk video</title>
      <link>http://jcla1.com/blog/fosdem-lightning-talk-video</link>
      <pubDate>Sat, 01 Mar 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/fosdem-lightning-talk-video</guid>
      <description>&lt;p&gt;Last month I was in Brussels with &lt;a href=&quot;http://pipetree.com/qmacro&quot;&gt;@qmacro&lt;/a&gt; for &lt;a href=&quot;https://fosdem.org/2014/&quot;&gt;FOSDEM 2014&lt;/a&gt;. At the time I was working on a little side project: &lt;a href=&quot;https://github.com/jcla1/gisp&quot;&gt;Gisp&lt;/a&gt;, a Lisp to Go compiler. On the Sunday I decided it was time to present Gisp to the world, so I gave a lightning talk in the Go room.&lt;/p&gt;
&lt;p&gt;In the talk I showcase the generated Go code Gisp produces for some simple Lisp programs, as well as the Go AST generating REPL that's included in Gisp. Also great thanks to &lt;a href=&quot;https://twitter.com/enneff&quot;&gt;Andrew Gerrand&lt;/a&gt; and &lt;a href=&quot;https://twitter.com/bradfitz&quot;&gt;Brad Fitzpatrick&lt;/a&gt; for organizing the Go dev-room at this year's FOSDEM!&lt;/p&gt;
&lt;p&gt;I'm up first in the video, but the other talks are definitely worth while too.

&lt;iframe width=&quot;640&quot; height=&quot;480&quot; src=&quot;//www.youtube.com/embed/cwpI5ONWGxc?rel=0&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;

&lt;p&gt;&lt;small&gt;&lt;a href=&quot;http://mirror.as35701.net/video.fosdem.org/2014/K4601/Sunday/Go_Lightning_Talks.webm&quot;&gt;Original video source&lt;/a&gt;&lt;/small&gt;&lt;/p&gt;

&lt;style&gt;
    iframe {
        width: 640px;
        height: 480px;
        margin-top: 20px;
    }
&lt;/style&gt;</description>
    </item>
    
    <item>
      <title>Personal Annual Report 2013</title>
      <link>http://jcla1.com/blog/personal-annual-report-2013</link>
      <pubDate>Thu, 02 Jan 2014 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/personal-annual-report-2013</guid>
      <description>&lt;p class=&quot;warning&quot;&gt;For those of you just looking for the actual report, you can find it right &lt;a href=&quot;/par/2013/&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Numbers are great! I think we can all agree on that. But I think they have even greater value if they give you insight into something.&lt;/p&gt;
&lt;p&gt;Astounded by the endless reports from &lt;a href=&quot;http://feltron.com/&quot;&gt;Nicolas Feltron&lt;/a&gt;, the packed article from &lt;a href=&quot;http://blog.stephenwolfram.com/2012/03/the-personal-analytics-of-my-life/&quot;&gt;Stephen Wolfram&lt;/a&gt; and especially the eye-opening reports of &lt;a href=&quot;http://jehiah.cz/one-two/&quot;&gt;Jehiah Czebotar&lt;/a&gt;, I decided to publish &lt;a href=&quot;/par/2013/&quot;&gt;my own&lt;/a&gt; Personal Annual Report.&lt;/p&gt;
&lt;p&gt;Even though my first tracking attempts were as late as September, I'm quite pleased with the results. Following Jehiah's example I've been mostly tracking computer activity (especially web-usage).&lt;/p&gt;
&lt;aside&gt;I've already got some prototypes for new ones, i.e. mouse-heatmaps, keystrokes and more detailed browsing activity.&lt;/aside&gt;
&lt;p&gt;The things I'm tracking include: &lt;i&gt;currently active application, open applications, URL of the frontmost tab, number of open tabs, etc.&lt;/i&gt; But beyond that I'm hoping that for this year's (2014) report I can include more things.&lt;/p&gt;

&lt;h2&gt;Technical Details&lt;/h2&gt;

&lt;aside&gt;To collect the network usage I'm polling a &lt;a href=&quot;http://humdi.net/vnstat/&quot;&gt;vnstat&lt;/a&gt; database, every 5 mins, which hooks into the kernel to get the net-usage data.&lt;/aside&gt;
&lt;p&gt;Although the actual report looks fine, I'm not happy with the data collection mechanism. Basically every 15 seconds an activity logging script is run, via cron, which collects data and then writes it to a file. Though there are a number of problems with this implementation. For example, when trying to aggregate the data (in Python) there are numerous occasions where a log file is corrupted and I have no idea why this is. Also running these script (currently written in a mix of Shell and Applescript) is quite slow.&lt;/p&gt;
&lt;aside&gt;And Applescript, although interesting, isn't the greatest language ever.&lt;/aside&gt;
&lt;p&gt;So to solve these problems I've set myself the task to rewrite (and extend) the data collection/aggregation mechanisms.&lt;/p&gt;
&lt;aside&gt;You can find the current and, hopefully soon, the new implementation &lt;a href=&quot;https://github.com/jcla1/quantified_self/&quot;&gt;on Github.&lt;/a&gt;&lt;/aside&gt;
&lt;br /&gt;
&lt;p&gt;Feedback and ideas appreciated&lt;/p&gt;
&lt;p&gt;Share and enjoy&lt;/p&gt;</description>
    </item>
    
    <item>
      <title>Crawling HackerNews</title>
      <link>http://jcla1.com/blog/crawling-hackernews</link>
      <pubDate>Mon, 13 May 2013 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/crawling-hackernews</guid>
      <description>&lt;p class=&quot;warning&quot;&gt;With the new &lt;a href=&quot;https://hn.algolia.com&quot;&gt;HN Search&lt;/a&gt; there's also a great &lt;a href=&quot;https://hn.algolia.com/api&quot;&gt;REST API&lt;/a&gt; provided. You should go check it out!&lt;/p&gt;

&lt;p&gt;It's been a while now since I started developing &lt;a href=&quot;https://github.com/jcla1/HN2JSON&quot;&gt;HN2JSON&lt;/a&gt; and I am actually still quite happy with that achievement.
If you've not heard of &lt;a href=&quot;https://github.com/jcla1/HN2JSON&quot;&gt;HN2JSON&lt;/a&gt; yet, it's basically a simple Ruby interface to &lt;a href=&quot;https://news.ycombinator.com/&quot;&gt;HackerNews&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But my dream was always to collect a complete copy of the HackerNews database! This wasn't possible with &lt;a href=&quot;https://github.com/jcla1/HN2JSON&quot;&gt;HN2JSON&lt;/a&gt;, because it is too slow and I didn't want to hammer HN with &lt;b&gt;millions&lt;/b&gt; of requests. What I was left with was the &lt;a href=&quot;https://www.hnsearch.com/api&quot;&gt;HNSearch API&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This was going to be a hard battle to win. And it was I can tell you. I won't trouble you with the details, but I had coded and thought for a whole week until I finally figured it out.&lt;/p&gt;

&lt;h2&gt;The battle begins&lt;/h2&gt;
&lt;p&gt;To understand why I thought this was such a hard problem to solve, you must know about the most complained about &quot;feature&quot; of the HN API. It restricts your search and you can't retrieve HN posts by their natural id.
Instead the db holding the data assigns a &lt;em&gt;signed_id&lt;/em&gt; to every db entry. You can get a post by signed_id, but they are near-impossible to guess.&lt;/p&gt;
&lt;p&gt;So confronted with this problem I had thought about writing a distributed system (that would guess entries based on pre-crawled data) and also just brute-force guessing all possible signed_ids.
Looking back, these approaches are ludicrous compared to the simple solution that I found in the end.&lt;/p&gt;

&lt;p&gt;For you to understand this simple solution, you must know that, when calling the API URL you can pass in filters based on various available parameters. Let me show you an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;http://api.thriftdb.com/api.hnsearch.com/items/_search? \
  filter[fields][username]=pg&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This URL will give you access to 10 posts and comments on HN where the submitter's username is &quot;pg&quot;.
Of course 10 entries isn't very helpful, apart from the fact that you can up that limit to 100, but what I realized was that there is also a filter on the submission date. This filter takes a date range:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;http://api.thriftdb.com/api.hnsearch.com/items/_search? \
  filter[fields][create_ts]=[2013-01-01T00:00:00Z + TO + *]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This URL will return you 10 posts and comments from start of 2013 upto anytime.
Might not look helpful at first, but when we combine this with a sorting filter we are able to collect all items in the database.&lt;/p&gt;

&lt;p&gt;Now let me explain that last bit again.&lt;/p&gt;

&lt;p&gt;Let's say, we sort all entries there are by date in ascending order. When we call the corresponding URL, we are presented with the first 10(0) entries ever on HN.
And now let's say that we take the last entry we get from the API and set a date-range filter going from that last entry to anytime. Now we get the next 10(0) entries from HN.
If you keep updating the URL, you are able to collect the complete HN database. An example URL for that would be something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;http://api.thriftdb.com/api.hnsearch.com/items/_search? \
  sortby=create_ts asc
  &amp;limit=100
  &amp;filter[fields][create_ts]=[&amp;lt;PUT LAST ENTRY'S DATE HERE&amp;gt; + TO + *]&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;So there you are, simple after all. Coding this mechanism up and making it fault-tolerant didn't even take me 2 hours. I plan to collect the whole db in the very near future and then to open-source it so that you and everyone else can benefit from it.&lt;/p&gt;</description>
    </item>
    
    <item>
      <title>Javascript and MapReduce</title>
      <link>http://jcla1.com/blog/javascript-mapreduce</link>
      <pubDate>Sat, 11 May 2013 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/javascript-mapreduce</guid>
      <description>&lt;p&gt;Don't we all love feeling like &lt;b&gt;big data scientists&lt;/b&gt;, &lt;b&gt;data miners&lt;/b&gt; or &lt;em&gt;&amp;lt;insert data buzzword here&amp;gt;&lt;/em&gt;?&lt;br&gt;Well here's a way to get that feeling in your everyday life:&lt;/p&gt;

&lt;p&gt;Recently I discovered the &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;reduce&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt; functions in Javascript. They are absolutely &lt;b&gt;awesome&lt;/b&gt;!
   To demonstrate their abilities we'll be building a wordcount program, using MapReduce, in Javascript, all chained.

&lt;h2&gt;Digging Data&lt;/h2&gt;

&lt;p&gt;As a datasource we'll use &lt;a href=&quot;https://news.ycombinator.com/bigrss&quot;&gt;HackerNews' big RSS feed&lt;/a&gt; and since we can treat RSS as plain HTML, it's very simple to get started:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var titles = document.getElementsByTagName('title');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is simply getting all the titles from the RSS feed. But we have a problem, &lt;code&gt;getElementsByTagName&lt;/code&gt; returns a &lt;code&gt;NodeList&lt;/code&gt; and not an &lt;code&gt;Array&lt;/code&gt;, which hasn't got the cool MapReduce functionallity we want.&lt;/p&gt;
&lt;p&gt;So we have to convert it to an array, and whilst doing so, we can also grab all the titles as strings, instead of HTML Nodes&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;var titles = Array.prototype.slice.call(document.getElementsByTagName('title'))&lt;/span&gt;
  .map(function(node) {
    return node.innerText;
  });
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;Simple isn't it? And now we have a list of all the titles on HackerNews (HN).&lt;/p&gt;

&lt;h2&gt;Introducing .map(callback [, thisArg])&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;map&lt;/code&gt; is a nice small function that takes 2 parameters, but usually only the first one is specified.&lt;/p&gt;
&lt;p&gt;
  As you can tell from the above code, the first argument is a callback function that is to be called over every element in the array, the second one is just to specify a value for &lt;code&gt;this&lt;/code&gt; during the function execution.
  More important are the parameters passed to the callback function. They are: the array element itself, its index and the whole array/context.
  So the callback function's signature would look something like this:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var callback = function(element, index, context) { /* omitted */ }
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Unwanted punctuation &amp; Individual words&lt;/h2&gt;

&lt;p&gt;
  As you may have noticed, the HN titles don't just contain letters, but they also carry numbers and punctuation.
  These are unwanted in our final wordcount, so we remove them. This can be done in the same &lt;code&gt;map&lt;/code&gt; call. Isn't Javascript a great language:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;var words = Array.prototype.slice.call(document.getElementsByTagName('title'))&lt;/span&gt;
  .map(function(node) {
    return node.innerText.toLowerCase().match(/([a-z]+)/g);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you're coding along, you'll have noticed this had a side-effect: It automatically gave us all the individual words, thanks to the RegEx, which returns all matches in an array.&lt;/p&gt;
&lt;p&gt;
  Even with this helpful side-effect, we are presented with a further problem. The &lt;code&gt;words&lt;/code&gt; array is &lt;a href=&quot;http://en.wikipedia.org/wiki/Array_data_structure#Multidimensional_arrays&quot;&gt;2d&lt;/a&gt;, which means we need to flatten it.
  Good job we've got &lt;code&gt;reduce&lt;/code&gt;:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;var words = Array.prototype.slice.call(document.getElementsByTagName('title'))
  .map(function(node) {
    return node.innerText.toLowerCase().match(/([a-z]+)/g);
  })&lt;/span&gt;
  .reduce(function(last, now) {
    return last.concat(now);
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Introducing .reduce(callback [, initialValue])&lt;/h2&gt;

&lt;p&gt;
  As &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;reduce&lt;/code&gt; takes 2 arguments.
  The first one is a callback function again, which is to be called on every element in the array.
  The &lt;code&gt;initialValue&lt;/code&gt; parameter will be easier to understand once you see the callback's signature:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var callback = function(previousValue, currentValue, index, context) { /* omitted */ }
&lt;/code&gt;&lt;/pre&gt;

&lt;aside&gt;Note: We wouldn't actually end up with a ginormous string, because strings don't have a &lt;code&gt;push&lt;/code&gt; method. It would just error out.&lt;/aside&gt;
&lt;p&gt;
  As you can see, the first parameter passed to the callback is the previous value.
  If you wanted to sum up an array of numbers, this would be not problem.
  But in our case we want an array returned, so we specify an inital value for the &lt;code&gt;previousValue&lt;/code&gt;.
  If we didn't do this we would end up with a ginormous string.
&lt;/p&gt;

&lt;h2&gt;Counting words&lt;/h2&gt;

&lt;p&gt;For this task, we can again use reduce, but before we start let me show you what the result will look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[['the', 'on', 'news', 'hacker', ...], [50, 66, 20, 19, ...]]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
  It'll be a &lt;a href=&quot;http://en.wikipedia.org/wiki/Array_data_structure#Multidimensional_arrays&quot;&gt;2d array&lt;/a&gt; again.
  The index of a word will correspond to the number of its occurrences.
  As an example the word &lt;em&gt;news&lt;/em&gt; has the index &lt;em&gt;2&lt;/em&gt;, in the first array, so its score is at index &lt;em&gt;2&lt;/em&gt; in the second array, in this case &lt;em&gt;20&lt;/em&gt;.
&lt;/p&gt;

&lt;p&gt;
  To code this, we'll use &lt;code&gt;reduce&lt;/code&gt; again and as an inital value we'll specify: &lt;code&gt;[[], []]&lt;/code&gt;
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;var scores = Array.prototype.slice.call(document.getElementsByTagName('title'))
  .map(function(node) {
    return node.innerText.toLowerCase().match(/([a-z]+)/g);
  })
  .reduce(function(last, now) {
    now.forEach(function(word) {
      last.push(word);
    });

    return last;
  }, [])&lt;/span&gt;
  .reduce(function(last, now) {
    var index = last[0].indexOf(now);

    if (index === -1) {
      last[0].push(now);
      last[1].push(1);
    } else {
      last[1][index] += 1;
    }

    return last;
  }, [[], []]);
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Zipping up the arrays&lt;/h2&gt;

&lt;p&gt;
  We're nearly done with collecting the data.
  All we need to do now is to combine the 2 arrays into one.
  The format this final array will be in is as follows:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[['the', 50], ['on', 66], ['news', 20], ['hacker', 19], ...]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For this we'll use &lt;code&gt;reduce&lt;/code&gt; again and utilize the 4th parameter passed to the callback:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&lt;span class=&quot;grayout&quot;&gt;var scores = Array.prototype.slice.call(document.getElementsByTagName('title'))
  .map(function(node) {
    return node.innerText.toLowerCase().match(/([a-z]+)/g);
  })
  .reduce(function(last, now) {
    now.forEach(function(word) {
      last.push(word);
    });

    return last;
  }, [])
  .reduce(function(last, now) {
    var index = last[0].indexOf(now);

    if (index === -1) {
      last[0].push(now);
      last[1].push(1);
    } else {
      last[1][index] += 1;
    }

    return last;
  }, [[], []])&lt;/span&gt;
  .reduce(function(last, now, index, context) {
    var zip = [];
    last.forEach(function(word, i) {
      zip.push([word, context[1][i]])
    });
    return zip;
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works, because the callback is only called once, so we can zip up the words with their scores.&lt;/p&gt;
&lt;p&gt;Now we have all our data collected. We could stop here, but humans love visualisations!&lt;/p&gt;

&lt;h2&gt;Visualisation&lt;/h2&gt;

&lt;p&gt;We're going to use &lt;a href=&quot;http://d3js.org/&quot;&gt;D3.js&lt;/a&gt; to visualize our data. And to be specific we'll create a force-directed chart.&lt;/p&gt;
&lt;p&gt;I won't explain how the visualisation works, because that isn't the subject of this post, but to find out you can always view source!&lt;/p&gt;
&lt;aside&gt;&lt;br&gt;Hover over the circles to see the exact number of occurrences and the word itself. Each color represents a different length of word.&lt;/aside&gt;



&lt;script&gt;
(function(){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var padding = 6,
    radius = d3.scale.log().range([8, 30]).domain([2, 82]),
    color = d3.scale.category10().domain([0, 15]);

var nodes = [];
var circle = [];
var force;

var svg = d3.select(&quot;div[itemprop=articleBody]&quot;).append(&quot;svg&quot;)
    .attr(&quot;width&quot;, width + margin.left + margin.right)
    .attr(&quot;height&quot;, height + margin.top + margin.bottom)
    .attr(&quot;class&quot;, &quot;vis&quot;)
  .append(&quot;g&quot;)
    .attr(&quot;transform&quot;, &quot;translate(&quot; + margin.left + &quot;,&quot; + margin.top + &quot;)&quot;);

d3.html('/data/hn_bigrss.html', function(err, html) {
  // This is our code executing on the recieved html
  scores=Array.prototype.slice.call(html.lastChild.getElementsByTagName(&quot;title&quot;)).map(function(a){return a.innerText.toLowerCase().match(/([a-z]+)/g)}).reduce(function(a,c){c.forEach(function(b){a.push(b)});return a},[]).reduce(function(a,c){var b=a[0].indexOf(c);-1===b?(a[0].push(c),a[1].push(1)):a[1][b]+=1;return a},[[],[]]).reduce(function(a,c,b,e){var d=[];a.forEach(function(a,b){d.push([a,e[1][b]])});return d});

  scores_filtered = scores.filter(function(score){return score[1] &gt; 1})
  scores_filtered = scores_filtered.filter(function(score){return score[0].length &gt; 1})

  scores_filtered.forEach(function(score) {
    nodes.push({radius: radius(score[1]), color: color(score[0].length), word: score[0], score: score[1]});
  });

  force = d3.layout.force()
    .nodes(nodes)
    .size([width, height])
    .gravity(0.01)
    .charge(-0.01)
    .on(&quot;tick&quot;, tick)
    .start();

  circle = svg.selectAll(&quot;circle&quot;)
    .data(nodes)
  .enter().append(&quot;circle&quot;)
    .attr(&quot;r&quot;, function(d) { return d.radius; })
    .style(&quot;fill&quot;, function(d) { return d.color; })
    .call(force.drag);

  circle.append(&quot;title&quot;)
    .text(function(d) { return &quot;(&quot; + d.score + &quot;) &quot; + d.word; });

});

function tick(e) {
  circle
      .each(cluster(10 * e.alpha * e.alpha))
      .each(collide(.5))
      .attr(&quot;cx&quot;, function(d) { return d.x; })
      .attr(&quot;cy&quot;, function(d) { return d.y; });
}

// Move d to be adjacent to the cluster node.
function cluster(alpha) {
  var max = {};

  // Find the largest node for each cluster.
  nodes.forEach(function(d) {
    if (!(d.color in max) || (d.radius &gt; max[d.color].radius)) {
      max[d.color] = d;
    }
  });

  return function(d) {
    var node = max[d.color],
        l,
        r,
        x,
        y,
        i = -1;

    if (node == d) return;

    x = d.x - node.x;
    y = d.y - node.y;
    l = Math.sqrt(x * x + y * y);
    r = d.radius + node.radius;
    if (l != r) {
      l = (l - r) / l * alpha;
      d.x -= x *= l;
      d.y -= y *= l;
      node.x += x;
      node.y += y;
    }
  };
}

// Resolves collisions between d and all other circles.
function collide(alpha) {
  var quadtree = d3.geom.quadtree(nodes);
  return function(d) {
    var r = d.radius + radius.domain()[1] + padding,
        nx1 = d.x - r,
        nx2 = d.x + r,
        ny1 = d.y - r,
        ny2 = d.y + r;
    quadtree.visit(function(quad, x1, y1, x2, y2) {
      if (quad.point &amp;&amp; (quad.point !== d)) {
        var x = d.x - quad.point.x,
            y = d.y - quad.point.y,
            l = Math.sqrt(x * x + y * y),
            r = d.radius + quad.point.radius + (d.color !== quad.point.color) * padding;
        if (l &lt; r) {
          l = (l - r) / l * alpha;
          d.x -= x *= l;
          d.y -= y *= l;
          quad.point.x += x;
          quad.point.y += y;
        }
      }
      return x1 &gt; nx2
          || x2 &lt; nx1
          || y1 &gt; ny2
          || y2 &lt; ny1;
    });
  };
}
})();
&lt;/script&gt;</description>
    </item>
    
    <item>
      <title>Browser ABC</title>
      <link>http://jcla1.com/blog/browser-abc</link>
      <pubDate>Thu, 09 May 2013 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/browser-abc</guid>
      <description>&lt;p&gt;&lt;em&gt;Deeply&lt;/em&gt; inspired by &lt;a href=&quot;http://twitter.com/timbray&quot;&gt;Tim Bray's&lt;/a&gt; &quot;&lt;a href=&quot;http://www.tbray.org/ongoing/When/201x/2011/03/03/ABC&quot;&gt;Letter Sweep&lt;/a&gt;&quot; and  my &lt;a href=&quot;http://www.pipetree.com/qmacro/&quot;&gt;dad's&lt;/a&gt; &quot;&lt;a href=&quot;http://www.pipetree.com/qmacro/blog/2011/03/my-browser-a-z/&quot;&gt;My Browser A-Z&lt;/a&gt;&quot;.
Notice, there are 3 Google subdomains, but no &lt;a href=&quot;http://google.com&quot;&gt;google.com&lt;/a&gt;. Is the omnibox killing the Google homepage?&lt;/p&gt;

&lt;p&gt;A: &lt;a href=&quot;http://api.thriftdb.com/api.hnsearch.com/users/&quot;&gt;api.thriftdb.com/api.hnsearch.com/users/&lt;/a&gt;&lt;br /&gt;
Even though it's an API I visit it regularly. Probably also got an extra push due to my &lt;a href=&quot;http://&quot;&gt;blog post&lt;/a&gt; about it.
&lt;/p&gt;

&lt;p&gt;B: &lt;a href=&quot;http://bost.ocks.org/mike/&quot;&gt;bost.ocks.org/mike/&lt;/a&gt;&lt;br /&gt;
For the latest and probably greatest visualisations on the net.
&lt;/p&gt;

&lt;p&gt;C: &lt;a href=&quot;http://closure-compiler.appspot.com&quot;&gt;closure-compiler.appspot.com&lt;/a&gt;&lt;br /&gt;
I can't even remember the last time I visited this, I'd grade it questionable.
&lt;/p&gt;

&lt;p&gt;D: &lt;a href=&quot;http://datamapper.org/docs/&quot;&gt;datamapper.org/docs/&lt;/a&gt;&lt;br /&gt;
My ORM of choice when working with &lt;a href=&quot;http://http://www.sinatrarb.com/&quot;&gt;Sinatra&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;E: &lt;a href=&quot;http://en.wikipedia.org/wiki/Category:Fundamental_categories&quot;&gt;en.wikipedia.org/wiki/Category:Fundamental_categories&lt;/a&gt;&lt;br /&gt;
I visit this page regularly to explore Wikipedia, it's very helpful for discovering new interesting topics.
&lt;/p&gt;

&lt;p&gt;F: &lt;a href=&quot;http://file://localhost/Users/joseph/Desktop/...&quot;&gt;file://localhost/Users/joseph/Desktop/...&lt;/a&gt;&lt;br /&gt;
All tinkering starts here!
&lt;/p&gt;

&lt;p&gt;G: &lt;a href=&quot;http://github.com&quot;&gt;github.com&lt;/a&gt;&lt;br /&gt;
Great! Nothing else.
&lt;/p&gt;

&lt;p&gt;H: &lt;a href=&quot;http://hnsearch.com/api&quot;&gt;hnsearch.com/api&lt;/a&gt;&lt;br /&gt;
Not sure if it's really useful or completely useless.
&lt;/p&gt;

&lt;p&gt;I: &lt;a href=&quot;http://isup.me&quot;&gt;isup.me&lt;/a&gt;&lt;br /&gt;
Slow internet connection makes me think sites are down :-(
&lt;/p&gt;

&lt;p&gt;J: &lt;a href=&quot;http://jcla1.com&quot;&gt;jcla1.com&lt;/a&gt;&lt;br /&gt;
My personal blog.
&lt;/p&gt;

&lt;p&gt;K: &lt;a href=&quot;http://kuler.adobe.com&quot;&gt;kuler.adobe.com&lt;/a&gt;&lt;br /&gt;
I know it's flash, but still good for finding nice color schemes.
&lt;/p&gt;

&lt;p&gt;L: &lt;a href=&quot;http://localhost:8000&quot;&gt;localhost:8000&lt;/a&gt;&lt;br /&gt;
You can't imagine with how many different ports I found this.
&lt;/p&gt;

&lt;p&gt;M: &lt;a href=&quot;http://mail.google.com&quot;&gt;mail.google.com&lt;/a&gt;&lt;br /&gt;
Apparently &lt;a href=&quot;http://www.emailisnotdead.com/&quot;&gt;&lt;b&gt;not&lt;/b&gt; dead&lt;/a&gt; and still useful.
&lt;/p&gt;

&lt;p&gt;N: &lt;a href=&quot;http://news.ycombinator.com&quot;&gt;news.ycombinator.com&lt;/a&gt;&lt;br /&gt;
Makes &gt;30% of my time on the web. GO HN!
&lt;/p&gt;

&lt;p&gt;O: &lt;a href=&quot;http://ozone3d.net/tutorials/mandelbrot_set_p3.php&quot;&gt;ozone3d.net/tutorials/mandelbrot_set_p3.php&lt;/a&gt;&lt;br /&gt;
Really great introduction to fractals. A must-read!
&lt;/p&gt;

&lt;p&gt;P: &lt;a href=&quot;http://plus.google.com&quot;&gt;plus.google.com&lt;/a&gt;&lt;br /&gt;
Is not being mainstream, too mainstream?
&lt;/p&gt;

&lt;p&gt;Q: &lt;a href=&quot;http://qvc.de&quot;&gt;qvc.de&lt;/a&gt;&lt;br /&gt;
Not recommended for buying tech, definitely.
&lt;/p&gt;

&lt;p&gt;R: &lt;a href=&quot;http://repl.it&quot;&gt;repl.it&lt;/a&gt;&lt;br /&gt;
Refrence implementation of web and esoteric languages. Helped a lot when building a Brainfuck interpreter.
&lt;/p&gt;

&lt;p&gt;S: &lt;a href=&quot;http://stuenings.de&quot;&gt;stuenings.de&lt;/a&gt;&lt;br /&gt;
Resource for a paper I have written recently.
&lt;/p&gt;

&lt;p&gt;T: &lt;a href=&quot;http://translate.google.com&quot;&gt;translate.google.com&lt;/a&gt;&lt;br /&gt;
What was that word again?
&lt;/p&gt;

&lt;p&gt;U: &lt;a href=&quot;http://underscorejs.org&quot;&gt;underscorejs.org&lt;/a&gt;&lt;br /&gt;
New second best friend? (d3 is top!)
&lt;/p&gt;

&lt;p&gt;V: &lt;a href=&quot;http://vivid.chengyichao.info&quot;&gt;vivid.chengyichao.info&lt;/a&gt;&lt;br /&gt;
Useful for coding along with &lt;a href=&quot;http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992&quot;&gt;The Little Schemer&lt;/a&gt; book that I'm reading at the moment.
&lt;/p&gt;

&lt;p&gt;W: &lt;a href=&quot;http://wolframalpha.com&quot;&gt;wolframalpha.com&lt;/a&gt;&lt;br /&gt;
To answer all the questions Google can't.
&lt;/p&gt;

&lt;p&gt;X: &lt;a href=&quot;http://xkcd.com&quot;&gt;xkcd.com&lt;/a&gt;&lt;br /&gt;
&lt;q&gt;Well, &lt;em&gt;of course&lt;/em&gt;.&lt;/q&gt; to quote &lt;a href=&quot;http://twitter.com/timbray&quot;&gt;Tim Bray&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;Y: &lt;a href=&quot;http://youtube.com&quot;&gt;youtube.com&lt;/a&gt;&lt;br /&gt;
For my weekly dose of &lt;a href=&quot;http://www.youtube.com/user/minutephysics&quot;&gt;physics&lt;/a&gt; and &lt;a href=&quot;http://www.youtube.com/user/Vsauce&quot;&gt;interesting factoids.&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;Z: &lt;a href=&quot;http://zachholman.com&quot;&gt;zachholman.com&lt;/a&gt;&lt;br /&gt;
Great presentations and more Github!
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>On Ulam spirals and matrix generation</title>
      <link>http://jcla1.com/blog/on-ulam-spirals-and-matrix-generation</link>
      <pubDate>Fri, 28 Dec 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/on-ulam-spirals-and-matrix-generation</guid>
      <description>&lt;p&gt;One of my Christmas presents was the fabulous book: &lt;a href=&quot;http://shop.oreilly.com/product/0636920025429.do&quot;&gt;Getting Started with D3&lt;/a&gt; by Mike Dewar.&lt;/p&gt;
&lt;p&gt;I recommend reading it, if you haven't already! But anyway, after I had read it, I was looking for some data I could visualize. The book suggested the New York transit dataset, but I didn't want to have to clean it just to play with d3. So after a bit of thinking and doing distractive things, I remembered having read about Ulam spirals quite a while back.&lt;/p&gt;

&lt;h2&gt;The Idea&lt;/h2&gt;
&lt;p&gt;The decision was made, what was missing was the data. I wanted to refresh my knowledge about &lt;a href=&quot;http://en.wikipedia.org/wiki/Ulam_spiral&quot;&gt;Ulam spirals&lt;/a&gt;,
so I loaded up Wikipedia and copied the spirals onto a whiteboard.&lt;/p&gt;
&lt;p&gt;I gave myself the task of finding an algorithm that would generate &lt;i&gt;just&lt;/i&gt; number spirals, given a dimension and &lt;code&gt;[x, y]&lt;/code&gt; coordinates to return a value.
I also gave this task to my father &lt;a href=&quot;http://pipetree.com/qmacro&quot;&gt;@qmacro&lt;/a&gt;, so we would compete on finding an algorithm.&lt;/p&gt;

&lt;p&gt;The source of both finished algorithms is here:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mine: &lt;a href=&quot;https://github.com/jcla1/ulam&quot;&gt;Github&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;My father's: &lt;a href=&quot;https://github.com/qmacro/ulam&quot;&gt;Github&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;aside&gt;
  Turns out, my father's algorithm is faster on smaller matrices and mine on bigger ones.
&lt;/aside&gt;
&lt;p&gt;and I ran them through JSPerf &lt;a href=&quot;http://jsperf.com/ulam-spiral&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Finding an algorithm&lt;/h2&gt;
&lt;p&gt;My approach was, I would say, a bit clumsy. It took quite a while, until I actually got anywhere, but when I finally did something it was an analytical approach.&lt;/p&gt;
&lt;p&gt;My idea was to just stare at the spiral for a long time until something
magically flew to my mind. And, as opposed to the expectations you may have to the outcome of this, I suddenly had an idea.
During the staring time I made some interesting observations, as can be seen in the next section.&lt;/p&gt;

&lt;h2&gt;Observations&lt;/h2&gt;
&lt;p&gt;Here is a sample 4x4 &amp; 5x5 matrix so you can follow along:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
                    ___________________   ________________________
                    |16 | 15 | 14 | 13|   |17 | 16 | 15 | 14 | 13|
                    |-----------------|   |----------------------|
                    |5  |  4 |  3 | 12|   |18 |  5 |  4 |  3 | 12|
                    |-----------------|   |----------------------|
                    |6  |  1 |  2 | 11|   |19 |  6 |  1 |  2 | 11|
                    |-----------------|   |----------------------|
                    |7  |  8 |  9 | 10|   |20 |  7 |  8 |  9 | 10|
                    -------------------   |----------------------|
                                          |21 | 22 | 23 | 24 | 25|
                                          ------------------------
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
  &lt;li&gt;Number spirals are just some matrices that follow a certain pattern.&lt;/li&gt;
  &lt;li&gt;The dimension squared is the highest value of the matrix.&lt;/li&gt;
  &lt;li&gt;The location of the dimension squared is dependent on parity: If odd, in the bottom right, if even, in the top left, corner of the matrix.&lt;/li&gt;
  &lt;li&gt;You can work out the numbers on the outer rim of the matrix with simple formulas.&lt;/li&gt;
  &lt;li&gt;If you compare the two matrices, how are they different? The 5x5 matrix has one &quot;frame&quot; more than the 4x4 matrix.&lt;br&gt; You could imagine it just being stuck on one of the sides, if you need higher dimensions. Again the side on which the last frame was &quot;stuck&quot; is determined by the parity of the dimension.&lt;br&gt; (In this case onto the left-bottom side)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So from these observations you could draw some conclusions, which I did!&lt;/p&gt;

&lt;h2&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;Based on the previous observations I had the thought that one could just &quot;drop a frame&quot; if the desired number doesn't lie within the area of that frame.&lt;/p&gt;
&lt;p&gt;So I wrote a function that worked out if &quot;dropping a frame&quot; was possible.
It takes coords of the location of the number you would like to have, and the dimension of the matrix.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function check_if_drop_frame(coords, d){
  if (d % 2 === 0){
    if (coords[0] != d &amp;&amp; coords[1] != 1){
      return true;
    } else {
      return false;
    }
  } else if (d % 2 === 1) {
    if (coords[0] != 1 &amp;&amp; coords[1] != d){
      return true;
    } else {
      return false;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In simple terms, the function checks the parity of the dimension and then checks if the coords &lt;br&gt;&lt;code&gt;[x, y]&lt;/code&gt; lie within the last frame.&lt;/p&gt;
&lt;p&gt;The idea is just to make the matrix smaller so, the original coords lie on the outermost frames, from which we know from the observations that they are easy values to work out.&lt;/p&gt;
&lt;p&gt;But in order to do so, we can't simply decrement the number of dimensions and leave the coords the same, we have to translate them.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function translate(coords, d_old){
  if (d_old % 2 === 0){
    coords[1] -= 1;
  } else if (d_old % 2 === 1) {
    coords[0] -= 1;
  }

  return coords;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This function again checks the parity and from that is knows which coord it needs to decrement, either &lt;code&gt;x&lt;/code&gt; or &lt;code&gt;y&lt;/code&gt;. So putting those two thing together we just drop frames/dimension as long as that is possible:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;while (check_if_drop_frame(coords, d)){
    coords = translate(coords, d);
    d -= 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once that loop has finished, it is guaranteed that the coords describe a number on one of the outermost frames.&lt;/p&gt;
&lt;p&gt;From there one only needs to find formulas to work out the value. Luckily I have already done that for you, they are a bit messy but they work. Wrapped in a function they look roughly like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function work_out_value(coords, d){
  var val = -1;

  var x = coords[0],
      y = coords[1];

  if (d % 2 === 0){
    if (coords[1] === 1){
      val = Math.pow(d, 2) - (coords[0] - 1)
    } else if (coords[1] === d){
      val = Math.pow(d, 2) - 2 * (d - 1) - (d - 2) + (x - 1) - 1
    } else if (coords[0] === 1){
      val = Math.pow(d, 2) - 3 * (d - 1) - (d - 2) + (y - 2)
    } else if (coords[0] === d){
      val = Math.pow(d, 2) - d - (y - 2)
    }
  } else if (d % 2 === 1){
    if (coords[1] === 1){
      val = Math.pow(d, 2) - 2 * (d - 1) - (x - 1)
    } else if (coords[1] === d){
      val = Math.pow(d, 2) - (d - 1) + (x - 1)
    } else if (coords[0] === 1){
      val = Math.pow(d, 2) - 2 * (d - 1) + (y - 1)
    } else if (coords[0] === d){
      val = Math.pow(d, 2) - 3 * (d - 1) - (y - 1)
    }
  }
  return val;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Basically, the function works out which is the outermost frame and then takes the dimension squared, whose position we can foresee, and works backward towards to desired coords.&lt;/p&gt;

&lt;p&gt;With a bit of boundary checking you can see the complete source &lt;a href=&quot;https://github.com/jcla1/ulam/blob/master/matrix.js&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Hooking it up with d3!&lt;/h2&gt;

&lt;p&gt;After I had figured out all of this it was night time, and I wasn't really bothered with good code style at that time of day, but since I wasn't satisfied yet I hooked it up with d3, and made my own ulam spiral.&lt;/p&gt;

&lt;script&gt;
(function(){
  function translate(a,b){return 0===b%2?a[1]-=1:1===b%2&amp;&amp;(a[0]-=1),a}function check_if_drop_frame(a,b){return 0===b%2?a[0]!=b&amp;&amp;1!=a[1]?!0:!1:1===b%2?1!=a[0]&amp;&amp;a[1]!=b?!0:!1:void 0}function check_values(a,b){return 1&gt;a[0]||1&gt;a[1]||a[0]&gt;b||a[1]&gt;b||1&gt;b?(console.log(&quot;Invalid values!&quot;),!1):!0}function work_out_value(a,b){var c=-1,d=a[0],e=a[1];return 0===b%2?1===a[1]?c=Math.pow(b,2)-(a[0]-1):a[1]===b?c=Math.pow(b,2)-2*(b-1)-(b-2)+(d-1)-1:1===a[0]?c=Math.pow(b,2)-3*(b-1)-(b-2)+(e-2):a[0]===b&amp;&amp;(c=Math.pow(b,2)-b-(e-2)):1===b%2&amp;&amp;(1===a[1]?c=Math.pow(b,2)-2*(b-1)-(d-1):a[1]===b?c=Math.pow(b,2)-(b-1)+(d-1):1===a[0]?c=Math.pow(b,2)-2*(b-1)+(e-1):a[0]===b&amp;&amp;(c=Math.pow(b,2)-3*(b-1)-(e-1))),c}function ulam(a,b){if(!check_values(a,b))return-1;for(;check_if_drop_frame(a,b);)a=translate(a,b),b-=1;return work_out_value(a,b)}
  isPrime=function(a){return isNaN(a)||!isFinite(a)||a%1||2&gt;a?!1:a==leastFactor(a)?!0:!1},leastFactor=function(a){if(isNaN(a)||!isFinite(a))return 0/0;if(0==a)return 0;if(a%1||2&gt;a*a)return 1;if(0==a%2)return 2;if(0==a%3)return 3;if(0==a%5)return 5;for(var b=Math.sqrt(a),c=7;b&gt;=c;c+=30){if(0==a%c)return c;if(0==a%(c+4))return c+4;if(0==a%(c+6))return c+6;if(0==a%(c+10))return c+10;if(0==a%(c+12))return c+12;if(0==a%(c+16))return c+16;if(0==a%(c+22))return c+22;if(0==a%(c+24))return c+24}return a};
  function draw(){svg=d3.select(&quot;body&quot;).append(&quot;svg&quot;).attr(&quot;width&quot;,width).attr(&quot;height&quot;,height),g=svg.selectAll(&quot;g&quot;).data(data).enter().append(&quot;g&quot;),g.selectAll(&quot;rect&quot;).data(function(a){return a}).enter().append(&quot;rect&quot;).attr(&quot;x&quot;,function(a){return 2*a[0]*radius+a[0]*spacing}).attr(&quot;y&quot;,function(a){return 2*a[1]*radius+a[1]*spacing}).attr(&quot;width&quot;,radius).attr(&quot;height&quot;,radius).style(&quot;fill&quot;,function(a){return a[2]})}window.data=[],mousedown=0,dimention=100,radius=4,spacing=-3,height=width=2*dimention*radius+dimention*spacing+2*radius-8,d3.range(dimention).forEach(function(a){data.push([]),d3.range(dimention).forEach(function(b){num=ulam([a+1,b+1],dimention),isPrime(num)?data[a].push([a,b,&quot;#F00&quot;]):data[a].push([a,b,&quot;#EEE&quot;])})});
  draw();
})();
&lt;/script&gt;

&lt;p&gt;This demo generates a 2d array and then loops though each element and checks if it is a prime.
If it is it sets the fill-color to red, else just leaves it gray.
Then it just gets d3 to draw the matrix.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Getting to work with CodeMirror</title>
      <link>http://jcla1.com/blog/getting-to-work-with-codemirror</link>
      <pubDate>Fri, 15 Jun 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/getting-to-work-with-codemirror</guid>
      <description>&lt;p&gt;Recently on &lt;a href=&quot;http://news.ycombinator.com/&quot;&gt;Hackernews&lt;/a&gt; I found an interesting link. It pointed to &lt;a href=&quot;http://rubyfiddle.com/&quot;&gt;RubyFiddle&lt;/a&gt;. The site is really nice, but my favourite bit was the editor.&lt;/p&gt;
&lt;p&gt;By then I had already guessed they hadn't done it themselves so I &lt;em&gt;investigated&lt;/em&gt; (looked in the source..) and found they're using &lt;a href=&quot;http://codemirror.net/&quot;&gt;CodeMirror&lt;/a&gt;.
I had heared about CodeMirror before but I never really liked online IDEs. But this editor &lt;strong&gt;really&lt;/strong&gt; caught my eye so I decided to try the most basic setup.&lt;/p&gt;
&lt;p&gt;Turns out, it's really simple! It's just 1, in words one, line of Javascript! (Plus basic HTML)&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CodeMirror(document.getElementById('container'));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That is all that is needed. Thanks to Marijn Haverbeke for such a great online editor.&lt;/p&gt;

&lt;p&gt;Below is a demo of it:&lt;/p&gt;

&lt;iframe src=&quot;http://bl.ocks.org/jcla1/raw/2938024&quot; height=&quot;500&quot; width=&quot;960&quot;&gt;&lt;/iframe&gt;

</description>
    </item>
    
    <item>
      <title>Web Audio API overview (Part 2 of 2)</title>
      <link>http://jcla1.com/blog/web-audio-api-overview-part2</link>
      <pubDate>Fri, 06 Apr 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/web-audio-api-overview-part2</guid>
      <description>&lt;p&gt;In the &lt;a href=&quot;/blog/2012/03/11/web-audio-api-overview-part1/&quot;&gt;first part&lt;/a&gt;, we looked at the basics of the Web Audio API and using it to visualize music.
In this second part I'll be showing you how to implement a LowPass Filter and gain control in our example from the first part.
We'll add some colour to it too.&lt;/p&gt;

&lt;p&gt;Let's start with the easiest bit, the color.
To change the color of the bars, all you need to do is change &lt;code&gt;ctx.fillStyle = &quot;white&quot;;&lt;/code&gt; to whatever color.
If you're like me, you won't like single color bars. I think those bars deserve a nice rainbow gradient. This is done very easily:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);

gradient.addColorStop(0, &quot;rgba(255, 0, 0, 1)&quot;);
gradient.addColorStop(0.15, &quot;rgba(255, 255, 0, 1)&quot;);
gradient.addColorStop(0.3, &quot;rgba(0, 255, 0, 1)&quot;);
gradient.addColorStop(0.5, &quot;rgba(0, 255, 255, 1)&quot;);
gradient.addColorStop(0.65, &quot;rgba(0, 0, 255, 1)&quot;);
gradient.addColorStop(0.8, &quot;rgba(255, 0, 255, 1)&quot;);
gradient.addColorStop(1, &quot;rgba(255, 0, 0, 1)&quot;);

ctx.fillStyle = gradient;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And that's it now we've a nice gradient.&lt;/p&gt;

&lt;p&gt;Next up, gain. You can create one just like an analyser:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;source = audioContext.createMediaElementSource(audioElement);
gain = audioContext.createGainNode();
analyser = audioContext.createAnalyser();

source.connect(gain);
gain.connect(analyser);
analyser.connect(audioContext.destination);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we have a &lt;code&gt;GainNode&lt;/code&gt;, but no way for the user to interact with it.&lt;/p&gt;

&lt;p&gt;To give the user some control over the gain, we'll have a well-known input.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;
&amp;lt;p&amp;gt;Gain: &amp;lt;input id=&amp;quot;gain&amp;quot; type=&amp;quot;range&amp;quot; value=&amp;quot;1&amp;quot; min=&amp;quot;0&amp;quot; max=&amp;quot;1&amp;quot; step=&amp;quot;0.01&amp;quot;&amp;gt;&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reason it has a max value of 1 is that the &lt;code&gt;GainNode&lt;/code&gt; by default sets this value (It is possible to change this).
Of course an input alone doesn't do anything. We'll add an event listener to it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;document.getElementById(&quot;gain&quot;).addEventListener('change',
  function(e){
  gain.gain.value = this.value
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This snippet sets &lt;code&gt;gain.gain.value&lt;/code&gt; to the value on the input.
And that is all there is to it.&lt;/p&gt;

&lt;p&gt;Adding a LowPass filter is the same procedure.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Add an input box.&lt;/li&gt;
  &lt;li&gt;Create the LowPass filter in Javascript.&lt;/li&gt;
  &lt;li&gt;Add a binding between input and LowPass filter&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is the source code:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;
&amp;lt;p&amp;gt;LowPass: &amp;lt;input id=&amp;quot;lowpass&amp;quot; type=&amp;quot;range&amp;quot; value=&amp;quot;5000&amp;quot; min=&amp;quot;0&amp;quot; max=&amp;quot;5000&amp;quot; step=&amp;quot;10&amp;quot;&amp;gt;&amp;lt;/p&amp;gt;

&amp;lt;script&amp;gt;
function init() {
  source = audioContext.createMediaElementSource(audioElement);
  gain = audioContext.createGainNode();
  filter = audioContext.createLowPass2Filter();
  filter.cutoff.value = 22050;
  analyser = audioContext.createAnalyser();
  source.connect(gain);
  gain.connect(filter);
  filter.connect(analyser);
  analyser.connect(audioContext.destination);
  draw();
}


document.getElementById(&amp;quot;lowpass&amp;quot;).addEventListener('change',
  function(e){
    filter.cutoff.value = this.value
});


&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this short series I have demonstrated how easy it is to work with the Web Audio API. You now know how to create Audio nodes and change their effect on audio.&lt;/p&gt;</description>
    </item>
    
    <item>
      <title>Web Audio API overview (Part 1 of 2)</title>
      <link>http://jcla1.com/blog/web-audio-api-overview-part1</link>
      <pubDate>Sun, 11 Mar 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/web-audio-api-overview-part1</guid>
      <description>&lt;p&gt;In the next 2 blog posts I'll be showing you some essential features of the Web Audio API. You can find its specification &lt;a href=&quot;https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html&quot;&gt;here&lt;/a&gt;.
The Web Audio API provides nearly all the functionality of a normal synthesizer, one of the reasons why it is so powerful.&lt;/p&gt;

&lt;p&gt;Anyway let's get going. I'm going to talk you through the source of a little audio visualizer in this post and the next one. &lt;a href=&quot;/iframes/web_audio_final.html&quot;&gt;Here is a demo of the final product.&lt;/a&gt;
In this first post I'll concentrate on &lt;a href=&quot;/iframes/web_audio_intro.html&quot;&gt;a simplified version&lt;/a&gt;.&lt;/p&gt;


&lt;p class=&quot;warning&quot;&gt;&lt;b&gt;Warning:&lt;/b&gt;  The code shown in this blog post is outdated and will only work in older version of Chrome.&lt;/p&gt;

&lt;p&gt;Now let's look at the HTML body structure. In this case it is very simple, it has a main &lt;code&gt;#container&lt;/code&gt;, that (as the name says) contains a canvas and an audio element. After that there are a couple of script tags. &lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;
&amp;lt;body&amp;gt;
  &amp;lt;div id=&amp;quot;container&amp;quot;&amp;gt;
    &amp;lt;canvas height=&amp;quot;200&amp;quot; width=&amp;quot;500&amp;quot; id=&amp;quot;fft&amp;quot;&amp;gt;&amp;lt;/canvas&amp;gt;
    &amp;lt;audio id=&amp;quot;audio&amp;quot; src=&amp;quot;IO2010.mp3&amp;quot; preload controls&amp;gt;&amp;lt;/audio&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;script&amp;gt;
  // requestAnim shim layer by Paul Irish
    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(callback, element){
                window.setTimeout(callback, 1000 / 60);
              };
    })();
  &amp;lt;/script&amp;gt;
  &amp;lt;script&amp;gt;
    // Some Javascript
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may already know what the contents of the first script tag are for.
It is a shim by &lt;a href=&quot;http://paulirish.com&quot;&gt;Paul Irish&lt;/a&gt; that makes it easier to use the &lt;code&gt;requestAnimationFrame()&lt;/code&gt; (To get more info read his &lt;a href=&quot;http://paulirish.com/2011/requestanimationframe-for-smart-animating/&quot;&gt;blog post&lt;/a&gt;). I'm not going to go further into how it works, but all it does &lt;em&gt;really&lt;/em&gt; is make user friendlier animations.&lt;/p&gt;

&lt;p&gt;The important parts for this blog post are the contents of the 2nd script tag:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// The audio element
audioElement = document.getElementById('audio');

// The canvas, its context and fillstyle
canvas = document.getElementById('fft');
ctx = canvas.getContext('2d');
ctx.fillStyle = &quot;white&quot;;

// Create new Audio Context and an audio analyzer
audioContext = new webkitAudioContext();
analyser = audioContext.createAnalyser();

// Canvas' height and width
CANVAS_HEIGHT = canvas.height;
CANVAS_WIDTH = canvas.width;
// We'll need the offset later
OFFSET = 100;
// Spacing between the individual bars
SPACING = 10;
// Initialize and start drawing
// when the audio starts playing
window.onload = init;
audioElement.addEventListener('play', draw);

function init() {
  // Take input from audioElement
  source = audioContext.createMediaElementSource(audioElement);
  // Connect the stream to an analyzer
  source.connect(analyser);
  // Connect the analyzer to the speakers
  analyser.connect(audioContext.destination);
  // Start the animation
  draw();
}

function draw() {
  // See http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  requestAnimFrame(draw, canvas);
  // New typed array for the raw frequency data
  freqData = new Uint8Array(analyser.frequencyBinCount);
  // Put the raw frequency into the newly created array
  analyser.getByteFrequencyData(freqData);
  // Clear the canvas
  ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  // This loop draws all the bars
  for (var i = 0; i &lt; freqData.length - OFFSET; i++) {
    // Work out the hight of the current bar
    // by getting the current frequency
    var magnitude = freqData[i + OFFSET];
    // Draw a bar from the bottom up (cause for the &quot;-magnitude&quot;)
    ctx.fillRect(i * SPACING, CANVAS_HEIGHT, SPACING / 2, -magnitude);
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;webkitAudioContext()&lt;/code&gt; created, is a context in which the audio interactions take place. Similar to the ones mentioned in my &lt;a href=&quot;/blog/2012/01/08/exploring-the-v8-js-engine-part-2/&quot;&gt;previous post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You could divide it into 2 main parts:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;p&gt;The setup&lt;/p&gt;&lt;/li&gt;
  &lt;li&gt;&lt;p&gt;The animation's &lt;code&gt;draw&lt;/code&gt; function&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;The setup&lt;/h2&gt;

&lt;p&gt;sets up all the variables (except &quot;freqData&quot;) and provides information on how each bar drawn should look.
The &lt;code&gt;init&lt;/code&gt; function connects the source of the audio (the audio element) with the analyzer and connects the analyzer with the destination. i.e. the speakers&lt;/p&gt;

&lt;p&gt;You can imagine connecting up &lt;code&gt;source&lt;/code&gt;, &lt;code&gt;analyzer&lt;/code&gt; and &lt;code&gt;destination&lt;/code&gt; as taking a few plugs and plugging them in some hardware.
The only difference is that this is virtual!&lt;/p&gt;

&lt;h2&gt;The animation's draw() function&lt;/h2&gt;

&lt;p&gt;takes care of drawing the bars.&lt;/p&gt;

&lt;p&gt;But what does that mean &lt;em&gt;exactly&lt;/em&gt;?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Call the &lt;code&gt;requestAnimFrame&lt;/code&gt; function to restart the animation at just the right time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a typed array (called &lt;code&gt;freqData&lt;/code&gt;) for holding the individual frequencies.
The parameter passed at creation is the size of the array (In this case &lt;code&gt;1024&lt;/code&gt; items).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Call a function on the analyzer to put the frequencies in &lt;code&gt;freqData&lt;/code&gt; (it doesn't return anything). &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Simply clear the canvas.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Loop through all the frequency data (except that in the offset) and each time:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;p&gt;Get the current frequency&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Draw a bar that is as high as the frequency. The magnitude has to be negative here so that the bar is drawn in the correct direction.&lt;/p&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lather. Rinse. Repeat.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nearly everything that has to do with the Web Audio API inherits from an object called &lt;code&gt;AudioNode&lt;/code&gt;, which contains some basic structure for working with audio.
For example the analyzer we are using here is also inherited from &lt;code&gt;AudioNode&lt;/code&gt;. Other examples of Audio Nodes are &lt;code&gt;BiquadFilter&lt;/code&gt;, &lt;code&gt;LowPassFilter&lt;/code&gt;, &lt;code&gt;AudioGainNode&lt;/code&gt; and many more. I will be covering some of them in part 2 of this mini series.&lt;/p&gt;

</description>
    </item>
    
    <item>
      <title>Exploring the V8 JS engine (Part 2 of 2)</title>
      <link>http://jcla1.com/blog/exploring-the-v8-js-engine-part-2</link>
      <pubDate>Sun, 08 Jan 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/exploring-the-v8-js-engine-part-2</guid>
      <description>&lt;p&gt;This is the second part of a 2 part series giving a simple technical overview of the V8 Javascript engine.&lt;/p&gt;

&lt;p&gt;In the &lt;a href=&quot;blog/2012/01/07/exploring-the-v8-js-engine-part-1/&quot;&gt;first part&lt;/a&gt; of this series I showed you how simple it is to get started with the V8 Javascript engine.&lt;/p&gt;
&lt;p&gt;In this second part we'll look into sharing objects and variables in a V8 program, as well as digging into the source of the popular (on V8 based) &lt;a href=&quot;http://nodejs.org/&quot;&gt;Node.js&lt;/a&gt;, to see how variable/object sharing is implemented in a real world example.&lt;/p&gt;

&lt;p&gt;In V8 there are 2 types shared variables:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Variables where you can change the value&lt;/li&gt;
  &lt;li&gt;Variables with an unchangeable value&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;warning&quot;&gt;&lt;b&gt;Warning&lt;/b&gt;: You are able to change the value of and unchangeable variable, but it will only be reflected in the Javascript (not the C++).&lt;/p&gt;

&lt;p&gt;For variables with an unchangeable value you only have to set the value.&lt;/p&gt;
&lt;p&gt;This is a bit trickier with shared variables that are changeable, for those you need &quot;Getter&quot; &amp; &quot;Setter&quot; functions, that get called when the variable is accessed.&lt;/p&gt;
&lt;p&gt;I will cover both of those types below and then show them implemented in the Node.js source.&lt;/p&gt;

&lt;h2&gt;Variables with an unchangeable value&lt;/h2&gt;

&lt;p&gt;Based off our &lt;a href=&quot;/blog/2012/01/07/exploring-the-v8-js-engine-part-1/#gist-1574928&quot;&gt;previous example (part 1 of this series)&lt;/a&gt;, sharing an unchangeable variable is pretty simple. All you have to do is use the &lt;code&gt;Set(...)&lt;/code&gt; function to set the variable's value.&lt;/p&gt;

&lt;p&gt;This program will create the variable &lt;code&gt;pid&lt;/code&gt; in the Javascript's context:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &amp;lt;v8.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;
// Include the header that contains the &quot;getpid()&quot; function

using namespace v8;

int main(int argc, char* argv[]) {

  // Create a stack-allocated handle scope.
  HandleScope handle_scope;

  Handle&amp;lt;ObjectTemplate&amp;gt; global_templ = ObjectTemplate::New();
  global_templ-&gt;Set(String::New(&quot;pid&quot;), Integer::New(getpid()));

  // Create a new context.
  Persistent&amp;lt;Context&amp;gt; context = Context::New(NULL, global_templ);

  // Enter the created context for compiling and
  // running the hello world script.
  context-&gt;Enter();

  // Create a string containing the JavaScript source code.
  Handle&amp;lt;String&amp;gt; source = String::New(&quot;pid;&quot;);

  // Compile the source code.
  Handle&amp;lt;Script&amp;gt; script = Script::Compile(source);

  // Run the script to get the result.
  Handle&amp;lt;Value&amp;gt; result = script-&gt;Run();

  // Dispose the persistent context.
  context.Dispose();

  // Convert the result to an ASCII string and print it.
  String::AsciiValue ascii(result);
  printf(&quot;%s\n&quot;, *ascii);
  return 0;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you save it in a file called &lt;code&gt;variable_share_unchangeable.cc&lt;/code&gt; (in &lt;code&gt;~/dev/v8/&lt;/code&gt;) you can compile and run it with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ g++ -m32 -Iinclude libv8.a -lpthread variable_share_unchangeable.cc \
  -o variable_share_unchangeable
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;For more information on running and compiling see &lt;a href=&quot;http://jcla1.com/blog/2012/01/07/exploring-the-v8-js-engine-part-1/&quot;&gt;the first post&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When this program is run it will print out its own &lt;code&gt;pid&lt;/code&gt;. The interesting thing about that is now though, that the &lt;code&gt;pid&lt;/code&gt; is accessed by the Javascript not the C++.&lt;/p&gt;

&lt;h2&gt;Variables with a changeable value&lt;/h2&gt;

&lt;p&gt;Defining variables that a C++ and Javascript program share, where you are able to change the value are a bit trickier.&lt;/p&gt;
&lt;p&gt;As I said before, you need to define a &quot;Getter&quot; and &quot;Setter&quot; for each variable you want to share.
Here is a program that demonstrates the use of shared changeable variables:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &amp;lt;v8.h&amp;gt;

using namespace v8;

// This is the variable we are going to share
int x = 15;

// Gets called when the value of x is requested
Handle&amp;lt;Value&amp;gt; XGetter(Local&amp;lt;String&amp;gt; property, const AccessorInfo&amp; info) {
  // Create a new Javascript int from the
  // current value of &quot;x&quot;
  return Integer::New(x);
}

// Gets called when &quot;x&quot; is set to a new value
void XSetter(Local&amp;lt;String&amp;gt; property, Local&amp;lt;Value&amp;gt; value, const AccessorInfo&amp; info) {
  // Change the value of the &quot;x&quot; in the C++
  // to a 32-Bit representation of the value passed
  x = value-&gt;Int32Value();
}

void CompileAndPrint(const Handle&amp;lt;String&amp;gt; source) {
  // Compile the source code.
  Handle&amp;lt;Script&amp;gt; script = Script::Compile(source);

  // Run the script to get the result.
  Handle&amp;lt;Value&amp;gt; result = script-&gt;Run();

  // Convert the result to an ASCII string and print it.
  String::AsciiValue ascii(result);
  printf(&quot;%s\n&quot;, *ascii);
}

int main(int argc, char* argv[]) {

  // Create a stack-allocated handle scope.
  HandleScope handle_scope;

  // Create a new ObjectTemplate
  Handle&amp;lt;ObjectTemplate&gt; global_templ = ObjectTemplate::New();

  // Set the XGetter and XSetter function
  // to be called when the value of &quot;x&quot; is requested
  // or &quot;x&quot; is set to a different value.
  global_templ-&gt;SetAccessor(String::New(&quot;x&quot;), XGetter, XSetter);

  // Create a new context.
  Persistent&amp;lt;Context&amp;gt; context = Context::New(NULL, global_templ);

  // Enter the created context for compiling and
  // running the hello world script.
  context-&gt;Enter();

  // x is still equal to 15 here
  Handle&amp;lt;String&amp;gt; s1 = String::New(&quot;x;&quot;);
  CompileAndPrint(s1);

  // Here we change x to 250
  Handle&amp;lt;String&gt;&amp;gt;s2 = String::New(&quot;x = 250;&quot;);
  CompileAndPrint(s2);

  // We print out x in C++ to see if the value has changed
  printf(&quot;%d\n&quot;, x);

  // Dispose the persistent context.
  context.Dispose();

  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It seems a lot of code for just one variable, though as you will see in the Node.js source, once you use multiple variables you will hardly notice the surroundings.&lt;/p&gt;

&lt;h2&gt;Node.js source&lt;/h2&gt;

&lt;p&gt;Here we'll dig into where and how Node.js uses these shared variables.&lt;/p&gt;
&lt;p&gt;Specifically I will use the process object as an example.&lt;/p&gt;
&lt;p&gt;It is not necessary that you fully understand how the internals of Node.js work, all you need to know is that there is a &lt;code&gt;&lt;a href=&quot;https://github.com/joyent/node/blob/master/src/node.cc#L3087-3140&quot;&gt;Start&lt;/a&gt;&lt;/code&gt; function right at the end of &lt;a href=&quot;https://github.com/joyent/node/blob/master/src/node.cc&quot;&gt;this file&lt;/a&gt;, that calls another function, which then calls another function that sets up the process object. The name of this function is &lt;code&gt;&lt;a href=&quot;https://github.com/joyent/node/blob/master/src/node.cc#L2301-2484&quot;&gt;SetupProcessObject&lt;/a&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This function sets up, among others, the &lt;code&gt;pid&lt;/code&gt; variable that we had as an example. In the case of Node.js, this variable is unchangeable.&lt;/p&gt;
&lt;p&gt;An example of a changeable variable in Node.js is the &lt;code&gt;process.title&lt;/code&gt;, it is the name or the title of the current program.&lt;/p&gt;
&lt;p&gt;Try it out by doing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ node
&gt; process.title = &quot;this_is_a_test&quot;;
'this_is_a_test'
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You won't notice a difference in node but if you look up the process name of node in Activity Monitor or Task Manager, etc. it will be &quot;this_is_a_test&quot; (without quotes):&lt;/p&gt;

&lt;img src=&quot;/public/img/exploring-v8-top.jpg&quot; alt=&quot;img of top with node process&quot;&gt;&lt;/img&gt;

&lt;h2&gt;End&lt;/h2&gt;

&lt;p&gt;That was a short overview of shared variables in the V8 Javascript engine.&lt;/p&gt;
&lt;p&gt;I didn't cover shared functions, because the post was that long already, but if you would like me to write a blog post about them too, just &lt;a href=&quot;mailto:whitegolem@gmail.com&quot;&gt;email me at whitegolem@gmail.com&lt;/a&gt;.&lt;/p&gt;





</description>
    </item>
    
    <item>
      <title>Exploring the V8 JS engine (Part 1 of 2)</title>
      <link>http://jcla1.com/blog/exploring-the-v8-js-engine-part-1</link>
      <pubDate>Sat, 07 Jan 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/exploring-the-v8-js-engine-part-1</guid>
      <description>&lt;p&gt;This is the first part of a 2 part series giving a simple technical overview of the V8 Javascript engine.&lt;/p&gt;

&lt;p&gt;First of all some basic facts:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Developed and maintained by Google&lt;/li&gt;
  &lt;li&gt;Javascript engine behind Google Chrome&lt;/li&gt;
  &lt;li&gt;Also powers Node.js?&lt;/li&gt;
  &lt;li&gt;Really Fast!&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;V8 is written in C++ so you should have basic understanding of OOP and some C/C++ knowledge wouldn't do bad too.&lt;/p&gt;
&lt;p&gt;The engine (V8) executes Javascript in so called &lt;code&gt;contexts&lt;/code&gt;, these are sandboxed and you can create multiple contexts in one V8 virtual machine (engine).&lt;/p&gt;
&lt;p&gt;This has the advantage that if you run 2 (or more) Javascript programs you don't have to worry about namespacing. The creation of these contexts is not as memory hungry as you may think, so don't worry about that.&lt;/p&gt;
&lt;p&gt;One of the great features of V8 is sharing C++ functions, objects and variables with Javascript, which we will cover in the second part of this series. To use V8 you write a C++ program that uses the V8 libs (to set up the contexts, scopes, templates) and then executes a string which is your Javascript program. You will understand how this works later in this post.&lt;/p&gt;

&lt;p&gt;I'll take you through setting up the V8 lib and a simple &lt;code&gt;Hello World!&lt;/code&gt; program.&lt;/p&gt;

&lt;h2&gt;Downloading and Building&lt;/h2&gt;

&lt;p&gt;I'm using a Mac to build the library, but &lt;a href=&quot;http://code.google.com/p/v8/wiki/BuildingOnWindows&quot;&gt;Windows is supported too&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To build V8 you will need:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Subversion 1.4 or higher&lt;/li&gt;
  &lt;li&gt;Python 2.4 or higher&lt;/li&gt;
  &lt;li&gt;SCons 1.0.0 or higher&lt;/li&gt;
  &lt;li&gt;GNU Compiler (GCC) 4.x.x&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To download the source type this into you terminal:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ mkdir ~/dev/
$ cd ~/dev/
$ svn checkout http://v8.googlecode.com/svn/trunk/ v8-read-only
$ mv v8-read-only v8
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you have the source you can build the V8 library and header file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Simple isn't it? Now once the build has finished you should be able to see the &lt;code&gt;libv8.a&lt;/code&gt; file. This file is important for compiling the C++ program that uses the V8 library.&lt;/p&gt;

&lt;h2&gt;Your first V8 program&lt;/h2&gt;

&lt;p&gt;Now that you have all the parts needed for compiling a C++ program that uses the V8 classes, let's get to the interesting part.&lt;/p&gt;

&lt;p&gt;Here is a simple C++ program that runs the Javascript: &lt;code&gt;&quot;Hello World!&quot;&lt;/code&gt;. Obviously, this is not a very spectacular Javascript program, but it should do to our needs. The comments explain what a each part does:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &lt;v8.h&gt;

using namespace v8;

int main(int argc, char* argv[]) {

  // Create a new context.
  Persistent&amp;lt;Context&amp;gt; context = Context::New();

  // Enter the created context for compiling and
  // running the hello world program.
  context-&gt;Enter();

  // Create a stack-allocated handle scope.
  HandleScope handle_scope;

  // Create a string containing the JavaScript code
  // to execute (notice the quotation).
  Handle&amp;lt;String&amp;gt; source = String::New(&quot; 'Hello World!'; &quot;);

  // Compile the Javascript code.
  Handle&amp;lt;Script&amp;gt; script = Script::Compile(source);

  // Run the script to get the result.
  Handle&amp;lt;Value&amp;gt; result = script-&gt;Run();

  // Get rid of the persistent context.
  context.Dispose();

  // Convert the result to an ASCII string and print it.
  String::AsciiValue ascii(result);
  printf(&quot;%s\n&quot;, *ascii);

  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Save that in a file called hello_world.cc in the &lt;code&gt;~/dev/v8/&lt;/code&gt; directory.&lt;/p&gt;
&lt;p&gt;Next you need to compile the &lt;code&gt;hello_world.cc&lt;/code&gt; file by doing:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ g++ -m32 -Iinclude libv8.a -lpthread hello_world.cc -o hello_world
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This compiles the hello world program to a 32-bit executable that includes the &lt;code&gt;libv8.a&lt;/code&gt; library.&lt;/p&gt;
&lt;p&gt;If the compilation was successful you should have a new file called &lt;code&gt;hello_world&lt;/code&gt; in your V8
directory. Then you execute the file and it should print out &quot;Hello World!&quot; (without the quotes):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ ./hello_world
Hello World!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Congratulations you have just run your first program that uses V8.&lt;/p&gt;

&lt;p&gt;In the next part of this series we'll look into sharing variables and objects and dig into the source of Node.js.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Using content providers in Android</title>
      <link>http://jcla1.com/blog/using-content-providers-in-android</link>
      <pubDate>Tue, 03 Jan 2012 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/using-content-providers-in-android</guid>
      <description>&lt;p&gt;In this blog post I'll show you how to get data stored on an Android phone using content providers.
We'll write an app that fetches all the bookmarks and history from the phone's browser.&lt;/p&gt;

&lt;p&gt;Most Data in Android is exposed through so called &quot;Content Providers&quot;. The person who wrote a specific part of Android (i.e. the browser, but surely it wasn't just one person), could decide how to implement the storage. If he used SQLite or just a basic file or json, etc. It didn't matter because Google decided to let their developers implement these content providers so that there would be a standard way for developers like us, to access the data.&lt;/p&gt;

&lt;p&gt;In Android all the content providers are stored in the package: &lt;code&gt;android.provider.*&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;They are queried using their URIs and Cursors.&lt;/p&gt;
&lt;p&gt;Specifically the Browser's Bookmark and History content provider URI is in: &lt;code&gt;android.provider.Browser.BOOKMARKS_URI&lt;/code&gt;&lt;br&gt;(The name is a bit misleading, since it is the URI for &lt;i&gt;BOTH&lt;/i&gt; Bookmarks and History.)&lt;/p&gt;
&lt;p&gt;To retrieve data you need to find the names of the columns you want to retrieve and put them in an Array.
You can find the package that contains the column definition for the bookmarks and history &lt;a href=&quot;http://developer.android.com/reference/android/provider/Browser.BookmarkColumns.html&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;So let's get started!&lt;/p&gt;
Let's first set up all the variables:

&lt;pre&gt;&lt;code&gt;import android.widget.Button;
import android.provider.Browser;
import android.net.Uri;

import java.util.List;

Button getBookmarksButton = (Button)this.findViewById(R.id.getBookmarksButton);
// I have set up a simple button in my layout, for which we will write a onClick listener.

Uri bookmarks =  Browser.BOOKMARKS_URI;
// The URI to query for bookmarks and history

List&lt;String&gt; bookmarksList = new ArrayList&lt;String&gt;();
// Here we'll store the retrieved data.

String[] columns = new String[] {
    BookmarkColumns.URL
};
// Array of all the columns you want to get. If you wanted any more like when it was created,
// just add another entry in the Array.
&lt;/code&gt;&lt;/pre&gt;

Now that we have the basic variables we can write the cursor. The function that creates it takes a lot of
arguments. As you can see not many of these are important for us:

&lt;pre&gt;&lt;code&gt;import android.database.Cursor;

Cursor managedCursor = managedQuery(
    bookmarks, // URI of the resource
    columns,   // Which columns to return
    null,      // Which rows to return (all rows)
    null,      // Selection arguments (none)
    null);     // Order the results (in the order they come)
&lt;/code&gt;&lt;/pre&gt;

Next we'll make a new onClick listener for the button. This listener basically loops
through all the data rows and does something with them:

&lt;pre&gt;&lt;code&gt;import android.view.View.OnClickListener;

getBookmarksButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (managedCursor.moveToFirst()) {
            String url;
            // Variable for holding the retrieved URL
            int urlColumn = cur.getColumnIndex(BookmarkColumns.URL);
            // Reference to the the column containing the URL

            do {
                url = cur.getString(urlColumn);
                // Get the field values
                bookmarksList.add(url);
                // Do something with the values.
            } while (managedCursor.moveToNext());

        }
    }
});
&lt;/code&gt;&lt;/pre&gt;

Now you have a list containing the bookmarks and history of a phones browser and you could for example send the urls to a server.

&lt;p&gt;You can download the whole Activity &lt;a href=&quot;https://raw.github.com/gist/1554163/7a0b4101462d4e0685289e6c0920b7e5c8d490a7/activity.java&quot;&gt;here&lt;/a&gt;&lt;/p&gt;</description>
    </item>
    
    <item>
      <title>RSA public/private key encryption explained</title>
      <link>http://jcla1.com/blog/rsa-public-private-key-encryption-explained</link>
      <pubDate>Sat, 10 Dec 2011 00:00:00 +0000</pubDate>
      <author>Joseph Adams (whitegolem@gmail.com)</author>
      <guid>http://jcla1.com/blog/rsa-public-private-key-encryption-explained</guid>
      <description>&lt;p&gt;In this blog post I'll show you how to calculate a simple RSA private-/public-key pair.&lt;/p&gt;

&lt;p&gt;First of all you need to know that each key (the public-key and the private-key) consists of 2 parts. The first part is different in each key, the second is equal in both. So let's start calculating!&lt;/p&gt;

&lt;p class=&quot;warning&quot;&gt;&lt;b&gt;Warning:&lt;/b&gt;  The encryption in this tutorial has a very low security level, because of the low values of &lt;code&gt;p&lt;/code&gt; and &lt;code&gt;q&lt;/code&gt;! To improve the security level choose higher primes.&lt;/p&gt;

&lt;ol&gt;
    &lt;li&gt;
      &lt;p&gt;Think of 2 prime numbers.&lt;/p&gt;

      &lt;p&gt;In real openssl, these prime numbers are very large and have a similar bit-size. So that we have no problem doing the calculations I'll choose 2 numbers that are quite small:&lt;/p&gt;
      &lt;pre&gt;&lt;code&gt;p = 3, q = 11
      &lt;/code&gt;&lt;/pre&gt;

    &lt;/li&gt;

    &lt;li&gt;
      &lt;p&gt;Calculate the modulus for the public/private key.&lt;/p&gt;

      &lt;p&gt;This is the number that is the same in both keys, let's call it &lt;code&gt;n&lt;/code&gt;. It is used as the modulus in en- and decryption. You calculate it by doing: &lt;pre&gt;&lt;code&gt;n = 3*11&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;
    &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Calculate the totient of n.&lt;/p&gt;

    &lt;p&gt;Calculating the totient is easy. You could use a table and look up the value, but the calculation is just as easy and faster.
    Just do:&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;totient(n) = (p - 1) * (q - 1)&lt;/code&gt;&lt;/pre&gt;
    &lt;p&gt;In our case we do:&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;totient(33) = (3 - 1) * (11 - 1)&lt;/code&gt;&lt;/pre&gt;
    &lt;p&gt;This equals &lt;code&gt;20&lt;/code&gt;.&lt;/p&gt;

    So far we have:
&lt;pre&gt;&lt;code&gt;p = 3
q = 11
n = 33
totient(n) = 20
&lt;/code&gt;&lt;/pre&gt;

  &lt;li&gt;
    &lt;p&gt;Choose a number for &lt;code&gt;e&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;This number is is a bit harder than the others. It has to be between &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;n&lt;/code&gt;,
    also coprime to &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
    &lt;p&gt;This basically means that the greatest common divisor of both numbers is &lt;code&gt;1&lt;/code&gt;.
    If you choose a prime number for &lt;code&gt;e&lt;/code&gt; all you need to do now is check that &lt;code&gt;e&lt;/code&gt; isn't a divisor of
    &lt;code&gt;n&lt;/code&gt;. I'll choose the number: &lt;pre&gt;&lt;code&gt;e = 17&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;
  &lt;/li&gt;


  &lt;li&gt;
    &lt;p&gt;Calculating the modular multiplicative inverse of &lt;code&gt;e * (mod totient(n))&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;Now at first this sounds a bit overwhelming, I struggled a bit to find out what it means. Expressed in an easy way you could say: &lt;q&gt;What is the solution to the equation:&lt;/q&gt;&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;(e * x - 1) mod (totient(n)) = 0&lt;/code&gt;&lt;/pre&gt;
    It would take quite long to work it out by hand so I wrote a small Javascript function that does the work for me:

&lt;pre&gt;&lt;code&gt;function doLoop(e, totient) {
  var i = 1, x;
  while (true) {
    x = (e * i - 1) % totient;
    if (x === 0) {
      console.log(i);
      break;
    }
    i++;
  }
}
&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;The function takes 2 arguments, one is &lt;code&gt;e&lt;/code&gt; the other is the &lt;code&gt;totient(n)&lt;/code&gt;. Depending on your processor and the size of the numbers you choose it can take longer or shorter to run.&lt;/p&gt;
    &lt;p&gt;In our case the function will log the value &lt;code&gt;13&lt;/code&gt;, which I'll call &lt;code&gt;d&lt;/code&gt;. Now you have all the values needed for public-/private-key encryption and decryption.&lt;/p&gt;

  &lt;li&gt;
    &lt;p&gt;Putting it all together&lt;/p&gt;

    &lt;p&gt;All the values up to now:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;p = 3
q = 11
n = 33
totient(n) = 20
e = 17
d = 13
&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;Your public-key is now: &lt;code&gt;e = 17, n = 33&lt;/code&gt;&lt;/p&gt;
    &lt;p&gt;Your private-key is now: &lt;code&gt;d = 13, n = 33&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;With this private and public-key you can now encrypt data by doing this:&lt;/p&gt;

    &lt;p&gt;We'll encrypt the value:&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;m = 9&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;To encrypt with the public key, you take m to the power of e (in the public-key) mod n&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;m ^ e mod n&lt;/code&gt;&lt;/pre&gt;
    &lt;pre&gt;&lt;code&gt;9 ^ 17 mod 33 = 15&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;Our encrypted value is:&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;c = 15&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;This can only be decrypted with the private-key.&lt;/p&gt;
    &lt;p&gt;To decrypt it, you take c to the power of d (in the private-key) mod n&lt;/p&gt;
    &lt;pre&gt;&lt;code&gt;c ^ d mod n&lt;/code&gt;&lt;/pre&gt;
    &lt;pre&gt;&lt;code&gt;15 ^ 13 mod 33 = 9&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;Now we have our original value!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;


</description>
    </item>
    

  </channel>
</rss>