<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tommy Chheng</title>
	<atom:link href="http://tommy.chheng.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://tommy.chheng.com</link>
	<description>Computer Research and Programming Blog</description>
	<lastBuildDate>Sun, 07 Mar 2010 18:30:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Processing in Scala!</title>
		<link>http://tommy.chheng.com/index.php/2010/03/processing-in-scala/</link>
		<comments>http://tommy.chheng.com/index.php/2010/03/processing-in-scala/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 18:28:40 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=248</guid>
		<description><![CDATA[One of the great things about scala is that it inter-operate with any existing Java library. Both ways, use scala classes from java and java from scala.  Here&#8217;s an quick example of using Processing in Scala. 

I&#8217;m using IntelliJ IDEA 9.0.1 with the Scala plugin.
To get Processing working in IntelliJ:

Download the processing.org jars
Create a [...]]]></description>
			<content:encoded><![CDATA[<p>One of the great things about scala is that it inter-operate with any existing Java library. Both ways, use scala classes from java and java from scala.  Here&#8217;s an quick example of using Processing in Scala. </p>
<p><a href="http://tommy.chheng.com/wp-content/uploads/2010/03/processing-in-scala1.png"><img src="http://tommy.chheng.com/wp-content/uploads/2010/03/processing-in-scala1.png" alt="" title="processing in scala" width="686" height="561" class="alignnone size-full wp-image-252" /></a></p>
<p>I&#8217;m using IntelliJ IDEA 9.0.1 with the Scala plugin.<br />
To get Processing working in IntelliJ:</p>
<ol>
<li>Download the <a href="http://processing.org">processing.org</a> jars</li>
<li>Create a Scala project.</li>
<li>Add them to your libraries list in the modules setting.</li>
<li>Create a new scala object example below.</li>
</ol>
<p>How is this useful? Scala&#8217;s syntax and its core data structures allow processing of data in a much more concise and understandable manner. Imagine you want to visualize xml or csv files with the Processing/Scala combo. Scala makes this easy with its xml and string manipulation libraries.</p>
<p> This example code is from Ben Fry&#8217;s <a href="http://www.amazon.com/gp/product/0596514557?ie=UTF8&#038;tag=tomchhsblo-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0596514557">Visualizing Data Book</a><img src="http://www.assoc-amazon.com/e/ir?t=tomchhsblo-20&#038;l=as2&#038;o=1&#038;a=0596514557" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<p><code></p>
<pre>
import processing.core._
object Draw extends processing.core.PApplet {

  override def setup() {
    size(200, 200)
    noStroke( )
    fill(0, 102, 153, 204)
  }

  override def draw() {
    background(255)
    rect(width-mouseX, height-mouseY, 50, 50)
    rect(mouseX, mouseY, 50, 50)
  }

  def main(args: Array[String]) {
    val frame = new javax.swing.JFrame("Draw")
    frame.getContentPane().add(Draw)
    Draw.init

    frame.pack
    frame.setVisible(true)
  }
}
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/03/processing-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to make a Javascript Bookmarklet</title>
		<link>http://tommy.chheng.com/index.php/2010/03/javascript-bookmarklet/</link>
		<comments>http://tommy.chheng.com/index.php/2010/03/javascript-bookmarklet/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 23:22:23 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=240</guid>
		<description><![CDATA[There&#8217;s a niffy trick in browsers that you you execute Javascript code in the url location bar. (This is how a lot of security holes are created too!)
Try typing the below into your browser url bar:

javascript:alert('look how cool this is')

Cool, it runs javascript!
You may have noticed a lot of websites take advantage of this to [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a niffy trick in browsers that you you execute Javascript code in the url location bar. (This is how a lot of security holes are created too!)<br />
Try typing the below into your browser url bar:<br />
<code><br />
javascript:alert('look how cool this is')<br />
</code><br />
Cool, it runs javascript!</p>
<p>You may have noticed a lot of websites take advantage of this to enhance a service. Instapaper&#8217;s &#8220;Read Later&#8221; saves the current page and Pastefire&#8217;s &#8220;Pastefire this&#8221; saves the selected text.</p>
<p>To make your own, just write javascript inside a link tag as a one liner.  Then just ask users to click and drag the link to the bookmark toolbar.<br />
<img src="http://tommy.chheng.com/wp-content/uploads/2010/03/sprocketit_bookmarklet.png" alt="" title="sprocketit_bookmarklet" width="418" height="85" class="alignnone size-full wp-image-243" /></p>
<p>Here&#8217;s an example for my Next Sprocket site which will start you on a new open source task with the title and description partially filled out:<br />
<a href="javascript:(function(){location.href='http://nextsprocket.com/tasks/new?task[title]='+encodeURIComponent(document.title)+'&amp;task[description]=More details at '+encodeURIComponent(window.location.href)})()">Sprocket it!</a></p>
<p><code><br />
&lt;a href="javascript:(function(){location.href='http://nextsprocket.com/tasks/new?task[title]='+encodeURIComponent(document.title)+'&amp;task[description]=More details at '+encodeURIComponent(window.location.href)})()"&gt;Sprocket it!&lt;/a&gt;<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/03/javascript-bookmarklet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gettext On Rails 3.0.0.beta: first open source task accomplished via Next Sprocket!</title>
		<link>http://tommy.chheng.com/index.php/2010/03/gettext-on-rails-3-0-0-beta-first-open-source-task-accomplished-via-next-sprocket/</link>
		<comments>http://tommy.chheng.com/index.php/2010/03/gettext-on-rails-3-0-0-beta-first-open-source-task-accomplished-via-next-sprocket/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 17:01:42 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=236</guid>
		<description><![CDATA[Great to wake up on Monday morning to see that someone has accepted and paid for the first open source task on our website Next Sprocket! Very happy to see our concept working.
The task was for making gettext rails 3.0 compatibility and providing a sample Rails 3.0 app. Check out the solution here.
If you have [...]]]></description>
			<content:encoded><![CDATA[<p>Great to wake up on Monday morning to see that someone has accepted and paid for the first open source task on our website Next Sprocket! Very happy to see our concept working.</p>
<p>The task was for making gettext rails 3.0 compatibility and providing a sample Rails 3.0 app. <a href="http://nextsprocket.com/tasks/gettext-on-rails-3-0-0-beta">Check out the solution here</a>.</p>
<p>If you have a gem that you need upgraded or any open source problem, please post the task on <a href="http://nextsprocket.com">Next Sprocket</a>. Someone will get it done and it will be an open source benefit.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/03/gettext-on-rails-3-0-0-beta-first-open-source-task-accomplished-via-next-sprocket/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MongoDB For Natural Development</title>
		<link>http://tommy.chheng.com/index.php/2010/02/mongodb-for-natural-development/</link>
		<comments>http://tommy.chheng.com/index.php/2010/02/mongodb-for-natural-development/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 17:41:50 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=229</guid>
		<description><![CDATA[Here&#8217;s the slides from a talk about MongoDB at the feb OC Ruby meetup. 
MongoDB For Natural Development 
There were a few examples from Tim Morgan&#8217;s presentation at the LaRubyConf2010 that resonated how ActiveRecord can be a source of many headaches.  I wager this is because the ActiveRecord ORM adds complexity to mapping from [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the slides from a talk about MongoDB at the feb <a href="http://ocruby.com">OC Ruby meetup</a>. </p>
<p><a title="View MongoDB For Natural Development on Scribd" href="http://www.scribd.com/doc/27488895/MongoDB-For-Natural-Development" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;">MongoDB For Natural Development</a> <object id="doc_866619320309658" name="doc_866619320309658" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" ><param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><param name="FlashVars" value="document_id=27488895&#038;access_key=key-2e44oc8mh1x18iiuxdfk&#038;page=1&#038;viewMode=slideshow"><embed id="doc_866619320309658" name="doc_866619320309658" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=27488895&#038;access_key=key-2e44oc8mh1x18iiuxdfk&#038;page=1&#038;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"></embed></object></p>
<p>There were a few examples from <a href="http://www.scribd.com/doc/27168812/Oh-Shit-How-to-Break-a-Large-Website-and-how-not-to-PDF-version">Tim Morgan&#8217;s presentation</a> at the LaRubyConf2010 that resonated how ActiveRecord can be a source of many headaches.  I wager this is because the ActiveRecord ORM adds complexity to mapping from ruby objects to SQL world. The mapping isn&#8217;t one to one and complexity is the unfortunate byproduct. </p>
<p>On the other hand, MongoDB&#8217;s data modeling naturally maps to today&#8217;s popular programming languages.  Essentially, most data are hashes(or associative arrays/dictionaries) and hashes are the basic data model for MongoDB. By having such a similar data representation, the ORM complexity level is extremely minimal compared to a typical ORM designed for SQL.</p>
<p>So use MongoDB because it can reduce the amount of complexity and bugs in your system.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/02/mongodb-for-natural-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Next Sprocket: The Open Source Developer&#8217;s Marketplace</title>
		<link>http://tommy.chheng.com/index.php/2010/02/next-sprocket-the-open-source-developers-marketplace/</link>
		<comments>http://tommy.chheng.com/index.php/2010/02/next-sprocket-the-open-source-developers-marketplace/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 01:54:25 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=218</guid>
		<description><![CDATA[As a developer, I have come to appreciate how useful open source technologies is for me and everyone.  Occasionally I come across a problem in an open source project that I can&#8217;t fix myself but willing to contribute some money to have it fixed. I am positive many other developers would too.

So I started [...]]]></description>
			<content:encoded><![CDATA[<p>As a developer, I have come to appreciate how useful open source technologies is for me and everyone.  Occasionally I come across a problem in an open source project that I can&#8217;t fix myself but willing to contribute some money to have it fixed. I am positive many other developers would too.</p>
<p><a href="http://nextsprocket.com"><img src="http://tommy.chheng.com/wp-content/uploads/2010/02/ns.png" alt="" title="ns" width="555" height="345" class="alignnone size-full wp-image-225" /></a></p>
<p>So I started <a href="http://nextsprocket.com">Next Sprocket</a> with my buddy Nitin. Next Sprocket is the Open Source Developer&#8217;s Marketplace.</p>
<p>The basic idea is for any developer to post a task for a reward, let others contribute to the money pot and allow other developers to solve the problem. All the transactions are done via Paypal&#8217;s Adaptive Payments API.</p>
<p>You can help by <a href="http://nextsprocket.com/tasks/new">posting a task</a> up or you can vote for us in the <a href="https://www.x.com/community/ppx/devchallenge/lp">Paypal Developer Challenge</a>. The PayPal Developer Challenge voting ends on March 5. The top 10 will be judged by the likes of Marc Andreessen, Scott Cook and many others for the winner. </p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/02/next-sprocket-the-open-source-developers-marketplace/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Indexing XML files using DIH in Solr 1.4</title>
		<link>http://tommy.chheng.com/index.php/2010/02/indexing-xml-files-using-dih-in-solr-1-4/</link>
		<comments>http://tommy.chheng.com/index.php/2010/02/indexing-xml-files-using-dih-in-solr-1-4/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 18:45:19 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=204</guid>
		<description><![CDATA[I have an large set of xml files(110K documents at ~900MB) that i wanted to import into Solr as fast as possible.
Previously I tried just using Jruby/nokogiri and embedded solr connection but that was taking about 15 minutes. So i tried using Solr&#8217;s builtin DIH to import the xml files to speed up imports(and re-imports). [...]]]></description>
			<content:encoded><![CDATA[<p>I have an large set of xml files(110K documents at ~900MB) that i wanted to import into Solr as fast as possible.<br />
Previously I tried just using Jruby/nokogiri and embedded solr connection but that was taking about 15 minutes. So i tried using Solr&#8217;s builtin DIH to import the xml files to speed up imports(and re-imports). Here&#8217;s how to do it:</p>
<p>Assume you have a large list of xml records like:<br />
<code><br />
&lt;awardlist&gt;<br />
&lt;award&gt;<br />
&lt;awardnumber&gt;0706313&lt;/awardnumber&gt;<br />
&lt;title&gt;Coherent Phonon Dynamics  in Semiconductors and Nanotubes&lt;/title&gt;<br />
&lt;expirationdate&gt;November 30, 2009&lt;/expirationdate&gt;<br />
&lt;/award&gt;<br />
&lt;award&gt;<br />
&lt;awardnumber&gt;9909156&lt;/awardnumber&gt;<br />
&lt;title&gt;Sustainability of Arctic Communities: Advancing the Science of Integrated Assessment &lt;/title&gt;<br />
&lt;expirationdate&gt;November 30, 2009&lt;/expirationdate&gt;<br />
&lt;/award&gt;<br />
&lt;/awardlist&gt;<br />
</code><br />
Add a request handler to your solrconfig.xml file:<br />
<code><br />
&lt;requestHandler name="/dataimport"&gt;<br />
&lt;lst name="defaults"&gt;<br />
&lt;str name="config"&gt;xml-data-config.xml&lt;/str&gt;<br />
&lt;/lst&gt;<br />
&lt;/requestHandler&gt;<br />
</code><br />
Create the xml-data-config.xml file:<br />
<code><br />
&lt;dataConfig&gt;<br />
&lt;dataSource type="FileDataSource" /&gt;<br />
&lt;document&gt;<br />
&lt;entity name="nsfgrantsdir" rootEntity="false" dataSource="null"<br />
processor="FileListEntityProcessor"<br />
fileName="^.*\.xml$" recursive="false"<br />
baseDir="/data/rw/data/nsf_grants_xml"<br />
&gt;<br />
&lt;entity name="nsf-grants"<br />
pk="id"<br />
datasource="nsfgrantsdir"<br />
url="${nsfgrantsdir.fileAbsolutePath}"<br />
processor="XPathEntityProcessor"<br />
forEach="/awardslist/award"<br />
transformer="DateFormatTransformer, RegexTransformer"&gt;<br />
&lt;field column="id" xpath="/awardslist/award/awardnumber" /&gt;<br />
&lt;field column="title_s" xpath="/awardslist/award/title"/&gt;<br />
&lt;field column="expirationdate_dt" xpath="/awardslist/award/expirationdate" dateTimeFormat="MMMMM dd, yyyy" /&gt;<br />
&lt;/entity&gt;<br />
&lt;/entity&gt;<br />
&lt;/document&gt;<br />
&lt;/dataConfig&gt;<br />
</code><br />
The first entity block will read all xml files in /data/rw/data/nsf_grants_xml and feed it into the second entity block for handling.</p>
<p>After done with the config files, start up solr and visit the dataimport admin page at http://localhost:8983/solr/admin/dataimport.jsp?handler=/dataimport and click the &#8220;Full-import&#8221;</p>
<p>This is where the import should just magically work for you. Unfortunately, I ran into many errors on the import. The first problem was the DateFormatTransformer couldn&#8217;t parse the correct date because it assumes the locale for the documents is the same locale on your machine. Feeling like a good open source citizen, I submitted a <a href="http://issues.apache.org/jira/browse/SOLR-1762">patch</a>!</p>
<p>Then, I found xml data files contained illegal characters not allowed in XML:<br />
<code><br />
Caused by: java.lang.RuntimeException: com.ctc.wstx.exc.WstxUnexpectedCharException: Illegal character ((CTRL-CHAR, code 11))<br />
</code></p>
<p>Now i have to strip all the illegal characters. I found this helpful Java code snippet from lucas song in the solr mailing list. Just add a FileUtils.readFileToString and FileUtils.writeStringToFile to quickly rewrite the xml files with validated characters.<br />
<code><br />
public class XmlCharFilter {<br />
    public static String doFilter(String in) {<br />
    StringBuffer out = new StringBuffer(); // Used to hold the output.<br />
    char current; // Used to reference the current character.<br />
    if (in == null || ("".equals(in)))<br />
        return ""; // vacancy test.<br />
    for (int i = 0; i < in.length(); i++) {<br />
        current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught<br />
                                // here; it should not happen.<br />
        if ((current == 0x9) || (current == 0xA) || (current == 0xD)<br />
                || ((current >= 0x20) &#038;&#038; (current <= 0xD7FF))<br />
                || ((current >= 0xE000) &#038;&#038; (current <= 0xFFFD))<br />
                || ((current >= 0x10000) &#038;&#038; (current <= 0x10FFFF)))<br />
            out.append(current);<br />
    }<br />
    return out.toString();<br />
}<br />
}<br />
</code></p>
<p>After filtering the xml for correct characters, the DIH import ran pretty fast, around 5 minutes for 120K documents of 400 MB on my Macbook pro laptop.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/02/indexing-xml-files-using-dih-in-solr-1-4/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>A Tale of Two Mice Packaging</title>
		<link>http://tommy.chheng.com/index.php/2010/02/a-tale-of-two-mice-packaging/</link>
		<comments>http://tommy.chheng.com/index.php/2010/02/a-tale-of-two-mice-packaging/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 20:30:35 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=198</guid>
		<description><![CDATA[
I recently purchased two Logitech mice: a VX Nano for my mobile use and a RX1500 for desktop use. The VX Nano came in retail packaging and the RX1500 came in OEM packaging. This photo illustrates the problem and solution to sustainable computer packaging. The OEM came with just what I need: the mouse. The [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/tommychheng/4323355100/"><img alt="logitech vx nano rx1500 packaging" src="http://farm5.static.flickr.com/4029/4323355100_5b5144d8e7.jpg" title="logitech vx nano rx1500" class="alignnone" width="500" height="333" /></a></p>
<p>I recently purchased two Logitech mice: a VX Nano for my mobile use and a RX1500 for desktop use. The VX Nano came in retail packaging and the RX1500 came in OEM packaging. This photo illustrates the problem and solution to sustainable computer packaging. The OEM came with just what I need: the mouse. The retail packaging has everything and the kitchen sink. Who needs a driver CD? A manual for a mouse? All the extra cardboard?</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/02/a-tale-of-two-mice-packaging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paypal Adaptive Ruby Gem Released</title>
		<link>http://tommy.chheng.com/index.php/2009/12/paypal-adaptive-ruby-gem-released/</link>
		<comments>http://tommy.chheng.com/index.php/2009/12/paypal-adaptive-ruby-gem-released/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 19:27:24 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=188</guid>
		<description><![CDATA[I have been tinkering with the new Paypal Adaptive Payments API and created a simple ruby gem to interface with it. Still pretty new but I&#8217;m using it with little problems so far. Submit bug reports if found. See the code at github
Paypal Adaptive Payments API
The adaptive payments api gives you the opportunity to make [...]]]></description>
			<content:encoded><![CDATA[<p>I have been tinkering with the new Paypal Adaptive Payments API and created a simple ruby gem to interface with it. Still pretty new but I&#8217;m using it with little problems so far. Submit bug reports if found. See the code at <a href="http://github.com/tc/paypal_adaptive">github</a></p>
<p><strong>Paypal Adaptive Payments API</strong><br />
The adaptive payments api gives you the opportunity to make preapproved payments, chained payments and parallel payments.  The chained/parallel payments are great for commission-based apps or if you are trying to connect  a buyer to multiple sellers with a single interface.</p>
<p><strong>How to use with Rails:</strong><br />
Install:<br />
<code><br />
sudo gem install paypal_adaptive<br />
</code><br />
Setup your API info by adding a paypal_adaptive.yml to your config folder:</p>
<pre><code>
development:
  environment: "sandbox"
  username: "sandbox_username"
  password: "sandbox_password"
  signature: "sandbox_signature"
  application_id: "sandbox_app_id"

test:
  environment: "sandbox"
  username: "sandbox_username"
  password: "sandbox_password"
  signature: "sandbox_signature"
  application_id: "sandbox_app_id"

production:
  environment: "production"
  username: "my_production_username"
  password: "my_production_password"
  signature: "my_production_signature"
  application_id: "my_production_app_id"
</code></pre>
<p>Make the payment request:</p>
<pre>
<code>
pay_request = PaypalAdaptive::Request.new

data = {
"returnUrl" => "http://testserver.com/payments/completed_payment_request",
"requestEnvelope" => {"errorLanguage" => "en_US"},
"currencyCode"=>"USD",
"receiverList"=>{"receiver"=>
     [{"email"=>"testpp_1261697850_per@nextsprocket.com", "amount"=>"10.00"}]},
"cancelUrl"=>"http://testserver.com/payments/canceled_payment_request",
"actionType"=>"PAY",
"ipnNotificationUrl"=>"http://testserver.com/payments/ipn_notification"
}

pay_response = pay_request.pay(data)

if pay_response.success?
  redirect_to pp_response.approve_paypal_payment_url
else
  puts pay_response.errors.first['message']
  redirect_to failed_payment_url
end
</code>
</pre>
<p>Once the user goes to pp_response.approve_paypal_payment_url, they will be prompted to login to Paypal for payment.</p>
<p>Upon payment completion page, they will be redirected to http://testserver.com/payments/completed_payment_request.</p>
<p>They can also click cancel to go to http://testserver.com/payments/canceled_payment_request</p>
<p>The actual payment details will be sent to your server via &#8220;ipnNotificationUrl&#8221; You have to create a listener to receive POST messages from paypal. I added a Rails metal template in the templates folder which handles the callback.</p>
<p>Additionally, you can make calls to Paypal Adaptive&#8217;s other APIs:</p>
<pre>
<code>
payment_details, preapproval, preapproval_details,
cancel_preapproval, convert_currency, refund
</code>
</pre>
<p>Input is just a Hash just like the pay method. Refer to the <a href="https://www.x.com/docs/DOC-1531">Paypal Adaptive manual</a> for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/12/paypal-adaptive-ruby-gem-released/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Sorting a HashMap by Value in Java vs Ruby</title>
		<link>http://tommy.chheng.com/index.php/2009/12/sorting-a-hashmap-by-value-in-java-ruby/</link>
		<comments>http://tommy.chheng.com/index.php/2009/12/sorting-a-hashmap-by-value-in-java-ruby/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 16:40:15 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[hashmap]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=176</guid>
		<description><![CDATA[I&#8217;m working a graph problem in Java where I need to sort nodes by its edge count. I have a HashMap of nodes to edge count so I just need to sort a HashMap by its value.
A quick Google search brought up a few solutions. Below is a snippet of a typical solution from StackOverFlow


public [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working a graph problem in Java where I need to sort nodes by its edge count. I have a HashMap of nodes to edge count so I just need to sort a HashMap by its value.<br />
A quick Google search brought up a few solutions. Below is a snippet of a typical solution from <a href="http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java">StackOverFlow</a></p>
<pre>
<code>
public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue(Map<K, V> map) {
    final int size = map.size();
    final List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size);
    list.addAll(map.entrySet());
    final ValueComparator<V> cmp = new ValueComparator<V>();
    Collections.sort(list, cmp);
    final List<K> keys = new ArrayList<K>(size);
    for (int i = 0; i < size; i++) {
        keys.set(i, list.get(i).getKey());
    }
    return keys;
}
private static final class ValueComparator<V extends Comparable<? super V>>
                                     implements Comparator<Map.Entry<?, V>> {
    public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}
</code>
</pre>
<p>Can you believe it?? >10 lines of verbose madness! The Ruby solution is:<br />
<code><br />
>> x = {:a => 1, :b => 2, :c => 1, :d => 5}<br />
>> x.keys.sort_by{|k| x[k]}<br />
=> [:a, :c, :b, :d]<br />
</code></p>
<p>This makes you really appreciate closure support in languages. Java 7&#8217;s support of closure should bring more sanity to the Java world.</p>
<p>I&#8217;m also learning Clojure right now, the solution is just as nice as Ruby.<br />
<code><br />
user=> (def x {:a 1 :b 2 :c 1 :d 5})<br />
user=> (sort-by #(x %) (keys x))<br />
(:a :c :b :d)<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/12/sorting-a-hashmap-by-value-in-java-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Converting from United States State Plane Coordinate System to Lat/Long WGS84</title>
		<link>http://tommy.chheng.com/index.php/2009/11/converting-from-united-states-state-plane-coordinate-system-to-latlong-wgs84/</link>
		<comments>http://tommy.chheng.com/index.php/2009/11/converting-from-united-states-state-plane-coordinate-system-to-latlong-wgs84/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 05:03:09 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[state plane]]></category>
		<category><![CDATA[wgs84]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=169</guid>
		<description><![CDATA[State Plane Coordinate System is a cartesian coordinate system that is widely used by many local practitioners in the United States. It&#8217;s only useful for local regions because projections used ignore the Earth&#8217;s curvature.
UTM?
When googling solutions for the conversion, I came across the UTM system. It looked related as it referenced the data in the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/State_Plane_Coordinate_System">State Plane Coordinate System</a> is a cartesian coordinate system that is widely used by many local practitioners in the United States. It&#8217;s only useful for local regions because projections used ignore the Earth&#8217;s curvature.</p>
<p><strong>UTM?</strong><br />
When googling solutions for the conversion, I came across the <a href="http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system">UTM system.</a> It looked related as it referenced the data in the same easting and northing points. UTM is a cartesian coordinate system but generalized for the entire world. It is not as specific as the State Plane Coordinate System.</p>
<p><strong>WGS84?</strong><br />
<a href="http://en.wikipedia.org/wiki/World_Geodetic_System">WGS84</a> is the latest revision for the World Geodetic System widely used. Google Earth references lat/lng using this system and this is our target.</p>
<p><strong>Convert from the California Zone VI State Plane Coordinate System to WGS84.</strong><br />
Now, back to the problem, our input is 6080411.905 ft easting 2169099.127 ft northing. We want its corresponding lat/lng.</p>
<p><strong>Use cs2cs for the conversion</strong><br />
Download <a href="http://trac.osgeo.org/proj/wiki/man_cs2cs">cs2cs</a> from <a href="http://trac.osgeo.org/proj">proj.4</a> cs2cs will convert coordinates from one system to another with the right projection parameters.</p>
<p><strong>Find the corresponding projection for California Zone VI State Plane Coordinate System:</strong></p>
<p><a href="http://spatialreference.org/ref/esri">spatialreference.org</a> has an extensive source of different coordinate systems.</p>
<p>Here&#8217;s the correct parameters for California VI as found on <a href="http://spatialreference.org/ref/esri/102646/">http://spatialreference.org/ref/esri/102646/</a></p>
<pre>
PROJCS["NAD_1983_StatePlane_California_VI_FIPS_0406_Feet",
    GEOGCS["GCS_North_American_1983",
        DATUM["North_American_Datum_1983",
            SPHEROID["GRS_1980",6378137,298.257222101]],
        PRIMEM["Greenwich",0],
        UNIT["Degree",0.017453292519943295]],
    PROJECTION["Lambert_Conformal_Conic_2SP"],
    PARAMETER["False_Easting",6561666.666666666],
    PARAMETER["False_Northing",1640416.666666667],
    PARAMETER["Central_Meridian",-116.25],
    PARAMETER["Standard_Parallel_1",32.78333333333333],
    PARAMETER["Standard_Parallel_2",33.88333333333333],
    PARAMETER["Latitude_Of_Origin",32.16666666666666],
    UNIT["Foot_US",0.30480060960121924],
    AUTHORITY["EPSG","102646"]]
</pre>
<p><strong>Run cs2cs</strong><br />
Pipe the input coordinates to cs2cs with the correct parameters given above.<br />
<code>echo '6080411.905 2169099.127' | cs2cs -f %.16f +proj=lcc +lat_1=32.78333333333333 +lat_2=33.88333333333333 +lat_0=32.16666666666666 +lon_0=-116.25 +x_0=2000000 +y_0=500000.0000000002 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs +to  +proj=latlon</code></p>
<p><strong>Lat/Lng Output:</strong><br />
<code>-117.8701429123491806   33.6091316264922995 0.0000000000000000</code></p>
<p>Alternatively, if you can&#8217;t use cs2cs or you rather implement the conversion directly with the projection parameters. The transformation equations here are listed at <a href="http://www.remotesensing.org/geotiff/proj_list/lambert_conic_conformal_2sp.html">http://www.remotesensing.org/geotiff/proj_list/lambert_conic_conformal_2sp.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/11/converting-from-united-states-state-plane-coordinate-system-to-latlong-wgs84/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
