<?xml version="1.0" encoding="iso-8859-1"?>
<rss version="2.0" 
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
  xmlns:admin="http://webns.net/mvcb/"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:content="http://purl.org/rss/1.0/modules/content/">

<channel>
<title>davidbau.com</title>
<link>http://davidbau.com/</link>
<description>A Dabbler&apos;s Weblog</description>
<dc:language>en-us</dc:language>
<dc:creator>david.bau@gmail.com</dc:creator>
<dc:date>2013-04-19T22:17:44-05:00</dc:date>
<admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=2.661" />
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<sy:updateBase>2000-01-01T12:00+00:00</sy:updateBase>

<item>
<title>Local Variable Debugging with see.js</title>
<link>http://davidbau.com/archives/2013/04/19/local_variable_debugging_with_seejs.html</link>
<description>Modern Javascript debuggers are fun to use because you can inspect the program state at any time without stopping at a breakpoint. The problem is, you can only inspect global state. What if you want to see local variables? Then...</description>
<guid isPermaLink="false">422@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Modern Javascript debuggers are fun to use because you can inspect the program state at any time without stopping at a breakpoint.  The problem is, you can only inspect global state.  What if you want to see local variables?  Then you're back in 1980, setting breakpoints each time you want to see your closure state again.</p>

<p>The solution is <a href="https://raw.github.com/davidbau/see/master/see.js">see.js</a>.  It is a simple debugger that I've written that lets you interact with an eval closure that you can insert at any scope you want to view.  In Javascript it is pretty common to use closures to encapsulate a lot of state - even your whole program. With see.js, you can write clean code like this without losing the ability to debug.</p>

<p>More details below.</p>]]></content:encoded>
<dc:date>2013-04-19T22:17:44-05:00</dc:date>
</item>
<item>
<title>Mapping the Earth with Complex Numbers</title>
<link>http://davidbau.com/archives/2013/02/16/mapping_the_earth_with_complex_numbers.html</link>
<description>Conformal maps have their history in 18th century cartographic science, so I have updated my conformal map tool to be able to render the surface of the earth according to the conformal projection of your choice. The lower-right corner of...</description>
<guid isPermaLink="false">421@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Conformal maps have their history in 18th century cartographic science, so I have updated my conformal map tool to be able to render the surface of the earth according to the conformal projection of your choice.  The lower-right corner of the window has a &#x2295; button that renders the earth as seen from space.</p>

<p>Below is the <a target=map href="/conformal/#z&b=earth">default (polar azumithal) projection</a>.  It places the equator on the unit circle, the south pole at infinity, and the prime meridian on the real line towards +1.  Because the south pole is at infinity, there is a large distortion of sizes as you go south of the equator.  However, the map is conformal, which means that locally, all angles are still accurate.<br />
<iframe name=map width=600 height=480 src="http://davidbau.com/conformal/#z&b=earth"></iframe></p>

<p>Here is a zoom-in on <a target=map href="/conformal/#iz/16+.35&b=earth">Greenwich, London at +0.35</a> on the polar projection.  On the same projection, here is a zoom-in on <a target=map href="/conformal/#(e^2.4i)(iz/3+1.9)&b=earth">Adelaide, Australia</a>.  Even though the southern hemisphere seems grossly large on the whole-plane rendering, it still looks correct locally.</p>

<p>The Mercator projection is the most well-known conformal projection, and here it can be rendered using <a target=map href="/conformal/#e^iz&b=earth">e^iz</a>.  Other projections such as the classical <a target=map href="/conformal/#disk(z%2B1)i(z%2B1-i)%2F(z%2B1%2Bi)-disk(z-1)i(z-1-i)%2F(z-1%2Bi)&b=earth">azimuthal stereographic</a> and the <a target=map href="/conformal/#(disk(z%2F2)(z%2F2-i)%2F(z%2F2%2Bi))%5E2&b=earth">Lagrange</a> projectections are also just other complex-valued functions.</p>

<p>Read about <a href="http://www.progonos.com/furuti/MapProj/Normal/ProjConf/projConf.html">other conformal projections here</a>.</p>

<p>Can you find functions that implement other interesting projections?</p>]]></content:encoded>
<dc:date>2013-02-16T05:39:00-05:00</dc:date>
</item>
<item>
<title>Conformal Map Viewer</title>
<link>http://davidbau.com/archives/2013/02/10/conformal_map_viewer.html</link>
<description>Have you ever wanted a visualization tool for complex functions? While reading some complex number proofs I wanted one, but online I could only find installable software or Java applets (to be avoided because of security problems). So I wrote...</description>
<guid isPermaLink="false">420@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Have you ever wanted a visualization tool for complex functions?</p>

<p>While reading some complex number proofs I wanted one, but online I could only find installable software or Java applets (to be avoided because of security problems).  So I wrote a <a href="http://davidbau.com/conformal/">Javascript conformal map viewer</a>, which you can see here (click <a href="http://davidbau.com/conformal/" target="_blank">here</a> to view it as a full page - it is about 1000 lines of javascript on a single page, and it is a nice example of doing canvas rendering with web workers):</p>

<p><iframe name=cm width=600 height=400 src="http://davidbau.com/conformal/#z"></iframe></p>

<p>The starting function "<a href="/conformal/#(z)" target=cm>(z)</a>" is the identity function, and shows how the tool colors the complex plane, with a ring at |z| = 1 and a small circle at |z| < 1/16, and 1/16th unit colored checkers on the rest of the plane.  There is also a colored circle shown towards infinity, at |z| > 16.  Colors are turquoise in the positive direction, red in the negative, gold-green in the "+i" direction, and they get darker as you go out towards infinity.  The tool draws a quick fuzzy preview; wait a minute for it to complete the computation for a clear antialiased rendering.  Lots of other functions can be typed into the box.  For example, notice that <a target=cm href="/conformal/#%7Cz%7C*e%5E(i*arg(z))">|z|*e^(i*arg(z))</a> is the same as <a href="/conformal/#z" target=cm>z</a>.</p>

<p>Try visualizing the complex values in <a href="/conformal#z^2" target=cm>z^2<a>, <a target=cm href="/conformal#sin(z)" >sin(z)</a>, <a target=cm href="/conformal#e^z" >e^z</a>, <a target=cm href="/conformal#log(z)">log(z)</a>, <a target=cm href="/conformal#sech(z)">sech(z)</a>, <a target=cm href="/conformal#arctan(z)">arctan(z)</a>, <a target=cm href="/conformal#z^3-1">z^3-1</a>, <a target=cm href="/conformal#sin(z^3-1)/z">sin(z^3-1)/z</a>, Jacobi elliptical functions <a target=cm href="/conformal#sn(z,0.4)">sn(z,0.3)</a>, the Gamma function <a target=cm href="/conformal#gamma(z)">gamma(z)</a>, or a polynomial to squeeze a circle into a square <a target=cm href="/conformal#0.926(z%2B7.3857e-2%20z%5E5%2B4.5458e-3%20z%5E9)">0.926(z+7.3857e-2 z^5+4.5458e-3 z^9)</a>.  </p>

<p>Or try this: <a href="http://davidbau.com/conformal/#iter(z+z'^2,z,12)">iter(z+z'^2,z,12)</a>.  Recognize it?</p>]]></content:encoded>
<dc:date>2013-02-10T01:54:01-05:00</dc:date>
</item>
<item>
<title>Jobs in 1983</title>
<link>http://davidbau.com/archives/2012/10/04/jobs_in_1983.html</link>
<description>Here is a remarkable tape of jobs presenting to the International Design Conference in Aspen, unearthed by Marcel Brown. Worth a listen. It is hard to remember how long ago 1983 was. Jobs speaks about science-fiction ideas such as using...</description>
<guid isPermaLink="false">419@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Here is a remarkable tape of jobs presenting to the  International Design Conference in Aspen, unearthed by <a href="http://lifelibertytech.com/2012/10/02/the-lost-steve-jobs-speech-from-1983-foreshadowing-wireless-networking-the-ipad-and-the-app-store/">Marcel Brown</a>.</p>

<p><iframe width="100%" height="166" scrolling="no" frameborder="no" src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F62010118&show_artwork=false"></iframe></p>

<p>Worth a listen. It is hard to remember how long ago 1983 was.  Jobs speaks about science-fiction ideas such as using computers as a new communication medium; interactive street maps based on photos of every intersection; the balance of privacy and openness in politics; the concept of an online app store; digital imagery; voice recognition; management at Apple; and his strategy for Apple's next decade.</p>

<blockquote>We want to put an incredibly great computer in a book that you can carry around with you, that you can learn how to use in 20 minutes...  We really want to do it with a radio link in it, so you don't need to hook up to anything and you're in communication with all these larger databases and other computers.</blockquote>

<p>Remember, in 1983, PCs had no networking and no GUIs, and in his lecture, he had to explain "what is a computer program", and the nutty idea of displaying proportional fonts on computers.</p>]]></content:encoded>
<dc:date>2012-10-04T07:50:35-05:00</dc:date>
</item>
<item>
<title>The Problem With China</title>
<link>http://davidbau.com/archives/2012/09/22/the_problem_with_china.html</link>
<description>Written by British expat and 16-year China resident Mark Kitto, You&apos;ll never be Chinese... why I&apos;m leaving the country I loved is one of the most insightful, honest essays on the problems facing China I have read in a long...</description>
<guid isPermaLink="false">418@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Written by British expat and 16-year China resident Mark Kitto, <a href="http://www.prospectmagazine.co.uk/politics/mark-kitto-youll-never-be-chinese-leaving-china/">You'll never be Chinese... why I'm leaving the country I loved</a> is one of the most insightful, honest essays on the problems facing China I have read in a long time.</p>

<p>On the pent-up economic problems in China:<br />
<blockquote>Everything the Party does to fix things in the short term only makes matters worse in the long term by setting off property prices again. Take the recent cut in interest rates, which was done to boost domestic consumption, which won’t boost itself until the Party sorts out the healthcare system, which it hasn’t the money for because it has been invested in American debt, which it can’t sell without hurting the dollar, which would raise the value of the yuan and harm exports, which will shut factories and put people out of work and threaten social stability.</blockquote></p>

<p>On the decline of community and civic culture:<br />
<blockquote>Traditional family culture, thanks to 60 years of self-serving socialism followed by another 30 of the “one child policy,” has become a “me” culture. Except where there is economic benefit to be had, communities do not act together... In the small rural village where we live I am not asked about my health or that of my family, I am asked how much money our small business is making, how much our car cost, our dog.<br />
</blockquote></p>

<p>On the implications of Chinese racism and exceptionalism:<br />
<blockquote>Leadership requires empathy, an ability to put yourself in your subordinate’s shoes. It also requires decisiveness and a willingness to accept responsibility. Believing themselves to be unique, the Chinese find it almost impossible to empathise. Controlled by people with conflicting interests, China’s government struggles to be decisive in domestic issues, let alone foreign ones....<br />
</blockquote></p>

<p>On the education:<br />
<blockquote>The domestic Chinese lower education system does not educate. It is a test centre. The curriculum is designed to teach children how to pass them.... Schools do not produce well-rounded, sociable, self-reliant young people with inquiring minds. They produce winners and losers. Winners go on to college or university to take “business studies.” Losers go back to the farm or the local factory their parents were hoping they could escape.<br />
</blockquote></p>

<p>Kitto also points out that the biggest property bubble on the planet (in China) seems to be caused by the unreliability of Chinese banks and stock markets, and the inability of Chinese to invest overseas due to the restrictions on yuan exchange, leaving property as the only place to park savings.  My wife points out that Chinese have always liked to buy land; at any rate, Chinese property is a bubble of gigantic proportions and the government does not seem to have any way to deflate it.</p>

<p>Kitto seems to share the view that, without more inspired leadership, a terrible cliff is on the horizon for China.</p>

<p><a href="http://www.prospectmagazine.co.uk/politics/mark-kitto-youll-never-be-chinese-leaving-china/">Worth a read.</a></p>

<p>(<a href="http://www.prospectmagazine.co.uk/blog/china-response-mark-kitto-prospect/">Also, here is a contrary opinion by an American expat</a>.)</p>]]></content:encoded>
<dc:date>2012-09-22T14:40:52-05:00</dc:date>
</item>
<item>
<title>Omega Improved</title>
<link>http://davidbau.com/archives/2011/12/10/omega_improved.html</link>
<description>The natural method to multiply two n × n matrices takes O(n3) steps, but in 1969, Volker Strassen stunned the computational world by publishing an algorithm that does it in only O(n2.808) steps. The greek letter omega is used to...</description>
<guid isPermaLink="false">417@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>The natural method to multiply two n × n matrices takes O(n<sup>3</sup>) steps, but in 1969, <a href="http://en.wikipedia.org/wiki/Strassen_algorithm">Volker Strassen stunned the computational world by publishing an algorithm</a> that does it in only O(n<sup>2.808</sup>) steps.  The greek letter omega is used to denote the minimum exponent for the complexity of matrix multiplication.  Strassen had shown the world that omega, which had always been assumed to be 3, was actually less than 2.808.</p>

<p>What is the true value of omega?</p>

<p>Strassen's discovery touched off a flurry of research.  In the following two decades, bounds on omega were improved and tuned until 1987, when <a href="http://www.cs.umd.edu/~gasarch/ramsey/matrixmult.pdf">Don Coppersmith and Shmuel Winograd reduced the exponent to 2.3755</a>.  That low exponent has stood as the best upper-bound for omega for 24 years.</p>

<p>Although the Strassen and C-W algorithms are not practical for most real-world problems, the theoretical work shows that matrix multiplication is fundamentally simpler than we would naively assume.  It hints that the mathematical world has a gap in knowledge with respect to the fundamental operation of composing linear operations.  Some believe (or hope) that matrix multiplication will ultimately be shown to be O(n<sup>2</sup>).  But for decades nobody has been able to get the exponent lower than 2.3755 - until now.</p>

<p><b>The Race for a Better Omega is On Again</b></p>

<p>A few days ago, <a href="http://www.cs.berkeley.edu/~virgi/">Virginia Vassilevska Williams</a> published a paper achieving an exponent lower than 2.3727, improving the bound by 0.0028 and importantly showing that C-W is not the end of the story.  She credits <a href="http://www.maths.ed.ac.uk/pg/thesis/stothers.pdf">Andrew Stothers</a> for doing thesis work last year that pointed the way to breaking the C-W record.  Then she describes an algorithm that beats upon the Stothers algorithm bound further, and she describes a general method to generate further algorithms that have low exponents.</p>

<p>Why did it take so long to make this next improvement?  In her words, "with each new tensor power, the number of new values that need to be analyzed grows quadratically. For the eighth tensor power for instance, 30 separate analyses are required! Prior to our work, each of these analyses would require a separate application of the CW techniques. It would have required an enormous amount of patience to analyze larger tensor powers, and since the third tensor power does not give any improvement, the prospects looked bleak."</p>

<p>Her paper (<a href="http://www.cs.berkeley.edu/~virgi/matrixmult.pdf">here</a>) is an example of a breed of modern mathematics that has grown to be comfortable with using computers as a tool.  Not only does she drive computer algebra systems to crack formulas with a higher level of complexity than would be practical to do when working by hand: she describes algorithms for creating algorithms, driving computers to sift through large numbers of permutations, hunting for the best ideas.</p>

<p>Links.  <a href="http://www.cs.berkeley.edu/~virgi/matrixmult.pdf">The Paper</a>; <a href="http://rjlipton.wordpress.com/2011/11/29/a-breakthrough-on-matrix-product/">RJ Lipton's blog entry</a>; <a href="http://www.newscientist.com/article/dn21255-mathematical-matrix-multiplier-sees-first-advance-in-24-years.html">New Scientist</a>.<br />
</p>]]></content:encoded>
<dc:date>2011-12-10T07:08:32-05:00</dc:date>
</item>
<item>
<title>Made In America Again</title>
<link>http://davidbau.com/archives/2011/11/06/made_in_america_again.html</link>
<description>Manufacturing wages in China have risen fourfold in the last 10 years. Factory real estate in coastal Chinese cities is now several times more expensive than it is in the Southern United States. Energy costs in China are up. And...</description>
<guid isPermaLink="false">416@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Manufacturing wages in China have risen fourfold in the last 10 years.  Factory real estate in coastal Chinese cities is now several times more expensive than it is in the Southern United States.  Energy costs in China are up.   And on top of all this, the yuan continues its inevitable rise against the dollar: the artificially low yuan cannot last forever because Chinese foreign trade reserves cannot grow without bound.</p>

<p>All of these trends point in the same direction.  Within the next decade - before my children are in the workforce - the cost advantages of outsourcing U.S. manufacturing to China will have evaporated, and the U.S. economy will begin to look very different again.  The change will happen quickly.</p>

<p>A <a href="http://www.bcg.com/documents/file84471.pdf">report from BCG summarizing this thinking</a> has been making the rounds and is worth a read.</p>

<p>My opinion: it is a good time to be an American exporter and a bad time to be an importer.  Good time to be a manufacturer and a bad time to be a retailer.  If you can make a profit exporting goods to China today, then you are going to be rolling in profits in the next decade.</p>

<p>A list of <a href="http://www.globaltrade.net/f/business/pdf/United-States/Transportation-and-Storage-Top-100-Exporters-2009.html">top U.S. exporters by container volume is here</a>.  This list is dominated by high-volume low-value exports (trash and paper).  Missing are companies like Boeing or Intel that do not use a lot of container space.  What would be more interesting would be a good listing of exporters by dollar value.</p>]]></content:encoded>
<dc:date>2011-11-06T06:38:40-05:00</dc:date>
</item>
<item>
<title>Avoiding Selectors for Beginners</title>
<link>http://davidbau.com/archives/2011/10/16/avoiding_selectors_for_beginners.html</link>
<description>I am finding that the jquery syntax of $(&apos;#id&apos;) is getting in the way of teaching middle-schoolers. There are two problems: first, the generality of jQuery selectors is an unnecessary concept to know before you even know what a function...</description>
<guid isPermaLink="false">415@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>I am finding that the jquery syntax of <b>$('#id')</b> is getting in the way of teaching middle-schoolers.</p>

<p>There are two problems: first, the generality of jQuery selectors is an unnecessary concept to know before you even know what a function is.  And second, the punctuation is too much for inexperienced typers to type: shift-4 for dollar, shift-9 and shift-0 for smooth parentheses, a choice to decide between single and double quotes, and don't forget shift-3 for the hashmark.</p>

<p>So I am considering giving kids a template that starts all their programs with a call to <b>$.setupids()</b> where idvars is a function defined as follows:</p>

<pre style="background:lightblue">
$.setupids = function setupids(prefix) {
  prefix = prefix || '';
  $('[id]').each(function(j, item) {
    window[prefix + item.id] = $('#' + item.id);
  });
};
</pre>

<p>The idea is that after <b>$.setupids();</b>, every HTML element that has an id of "r" has a corresponding global variable "r = $('#r');" which is the jquery selecting that element (not just the bare element).</p>

<pre style="background:lightblue">
&lt;script src="/lib/jq.js"&gt;&lt;/script&gt;
&lt;img id="a" src="/public/asteroid.gif"&gt;
&lt;img id="r" src="/public/rocket.png"&gt;
&lt;script&gt;
$.setupids(); // supplied in the template
a.move();
r.turnto(a);
&lt;/script&gt;
</pre>]]></content:encoded>
<dc:date>2011-10-16T09:33:38-05:00</dc:date>
</item>
<item>
<title>Turtle Graphics Fern with jQuery</title>
<link>http://davidbau.com/archives/2011/10/15/turtle_graphics_fern_with_jquery.html</link>
<description>Here is another classic turtle graphics example: b { display: inline-block; } t t = $(&apos;#t&apos;); t.moveto(300, 300).pen(&apos;green&apos;); function fern(size) { if (size Click here to see a demo....</description>
<guid isPermaLink="false">414@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>Here is another classic turtle graphics example:
<xmp style="background:lightblue;"
><script src="/lib/jq.js"></script>
<style>b { display: inline-block; }</style>
<b id="t">t</b>
<script>
t = $('#t');
t.moveto(300, 300).pen('green');
function fern(size) {
  if (size < 1) return;
  t.todo(function() {
    t.move(size).turn(5);
    fern(size * .9);
    t.turn(90);
    fern(size * .4);
    t.turn(-180);
    fern(size * .4);
  });
}
fern(50);
</script>
</xmp>

<p>Click <a href="http://jsdabbler.appspot.com/home/davidbau/fern.html" target="fern" onclick="document.getElementById('fern').style.display='block'">here</a> to see a demo.

<iframe style="display:none" name="fern" id="fern" height=320 width=640></iframe>

<p>]]></content:encoded>
<dc:date>2011-10-15T10:03:48-05:00</dc:date>
</item>
<item>
<title>Learning To Program with jQuery</title>
<link>http://davidbau.com/archives/2011/10/10/learning_to_program_with_jquery.html</link>
<description>What is the best programming language to learn first? The right answer in today&apos;s world is Javascript - with jQuery. Javascript is the most widely supported programming language in the world. It has readable algebraic syntax and simple typing that...</description>
<guid isPermaLink="false">413@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>What is the best programming language to learn first?  The right answer in today's world is Javascript - with jQuery.</p>

<p>Javascript is the most widely supported programming language in the world.  It has readable algebraic syntax and simple typing that is forgiving for beginners.  With its good support for closures, objects, and literals, it is an elegant little language with room to grow.</p>

<p>The main disadvantage of Javascript is its odd and unreliable GUI-oriented standard library, the HTML DOM.  But jQuery has fixed that.  With its efficient, robust design, jQuery has <a href="http://www.google.com/trends?q=jquery%2C+dojo%2C+mootools%2C+closure%2C+prototype&ctab=0&geo=all&date=all&sort=0">far outstripped all its rivals</a> as the "version 2" DOM.  Today, <a href="http://www.google.com/trends?q=jquery%2C+javascript&ctab=0&geo=all&date=all&sort=0">jQuery is approaching the universality of Javascript itself</a>.</p>

<p><b>But is jQuery accessible to beginners?</b></p>

<p>This Fall I will be testing that question.  Together with several Google friends, I'm teaching a learn-to-program course to a group of 17 sixth graders (we're doing it as part of the <a href="http://www.citizenschools.org/volunteer/">Citizen Schools</a> program where every child in the <a href="http://www.bostonpublicschools.org/school/mccormack-middle-school">Dorchester public middle school</a> is required to participate in an after-school program).</p>

<p>The theme of the class is "web game programming" - a popular topic.  We are using Javascript and jQuery on Chromebooks along with a small set of jQuery extensions including <a href="http://code.google.com/p/jquery-turtle/">jquery-turtle</a>, described below.  We have ten hours to get the kids from "hello world" to creating their own games.</p>

<p>In our first two hours, we've explored the Javascript debugger and made our own webpages.  Hour three is coming up.  It will be our first exercise in making a simple game with some scaffolding.</p>

<p><a href="http://dmcpanthers.appspot.com/examples/clickme.html">Here is the example for class 3<a>.<br />
</p>]]></content:encoded>
<dc:date>2011-10-10T22:30:43-05:00</dc:date>
</item>
<item>
<title>jQuery-turtle</title>
<link>http://davidbau.com/archives/2011/10/08/jqueryturtle.html</link>
<description>You have three img elements with ids r, x, and a. What does the following javascript program do with them? function tick() { if ($(&apos;#r&apos;).touches(&apos;#a&apos;)) { $(&apos;#x&apos;).turn().moveto(&apos;#a&apos;).attr(&apos;src&apos;, &apos;/public/poof.gif&apos;); $(&apos;#a&apos;).turn().move(); } else { $(&apos;#r&apos;).turnto(&apos;#a&apos;, 10).move(10); $(window).moveto(&apos;#r&apos;); } } setInterval(tick, 50); Click...</description>
<guid isPermaLink="false">412@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>You have three img elements with ids r, x, and a.  What does the following javascript program do with them?

<xmp style="background-color: lightblue"
>function tick() {
  if ($('#r').touches('#a')) {
    $('#x').turn().moveto('#a').attr('src', '/public/poof.gif');
    $('#a').turn().move();
  } else {
    $('#r').turnto('#a', 10).move(10);
    $(window).moveto('#r');
  }
}
setInterval(tick, 50);
</xmp>

<p>Click <a href="#" onclick="document.getElementById('demo').style.display='block'">here</a> to see a demo.

<iframe style="display:none" id="demo" src="http://jsdabbler.appspot.com/home/davidbau/scroll.html" height=400 width=650></iframe>

<p><b>Open-Source Library</b>

<p>The jQuery extension being used here makes simple javascript game dynamics accessible enough for kids to use directly.  The extension is called <a href="http://code.google.com/p/jquery-turtle/">jQuery-turtle</a> and I am licensing it under MIT license terms.  It builds on top of <a href="http://www.zachstronaut.com/posts/2009/08/07/jquery-animate-css-rotate-scale.html">Zachary Johnson's useful rotation extensions</a> to jQuery.

<p><a href="http://code.google.com/p/jquery-turtle/source/browse/trunk/src/jquery-turtle.js">jQuery-turtle source code here</a>.

<p>The extension adds the following methods to jQuery:

<pre>
$(elt).turn(degrees)      // turns elements right by a number of degrees 
$(elt).turnto(direction)  // sets absolute compass direction
$(elt).move(pixels)       // moves elements forward by a number of pixels
$(elt).moveto(location)   // sets absolute position of the center of the elements
$(elt).mirror(flip)       // mirrors elements across the current axis
$(elt).center()           // returns the absolute center coordinates of an element
$(elt).direction()        // returns the absolute compass direction of an element
$(elt).touches(target)    // true if one element touches another
$(elt).encloses(target)   // true if one element geometrically encloses another
$(elt).pen(color)         // starts tracing a line with the given style
$(elt).fill(color)        // fills the elements with the given style
</pre>

<p>Any element can be turned and walked around the screen using turtle geometry and hit-tested against any other element.  Key features of this extension avoid learning barriers for beginning programmers:
<ul>
<li>No need to understand cartesian coordinates. Trigonometry of turtle graphics is handled.
<li>Plays nicely with css: turtle heading is css rotation, and position is set using css attributes.
<li>Mouse events are easy: move to the location of a mouse event by $(elt).moveto(event).
<li>Hit testing is easy: pixel-precise rotated-rectangle hit testing is implemented by $(elt).touches(otherelt).
<li>Objects are positioned by their center, which simplifies most game calculations.
<li>Fractional positions are remembered, avoiding roundoff problems at small steps or angles.
<li>Turning towards another object is implemented by $(elt).turnto(otherelt), an alternative to $(elt).turnto(degrees).
<li>Window scrolling is also easy and is done by $(window).moveto(pos).
<li>Every element can have a pen with its own color and size.
<li>Canvas for pen lines created on-demand and does not interfere with the document.
</ul>]]></content:encoded>
<dc:date>2011-10-08T16:22:48-05:00</dc:date>
</item>
<item>
<title>Python Templating with @stringfunction</title>
<link>http://davidbau.com/archives/2011/09/09/python_templating_with_stringfunction.html</link>
<description>I&apos;ve posted a new version of the templet.stringfunction utility I have discussed before. I have been using it to make a bunch of web UI in programming projects with my son (actually pretty sophisticated little projects - http://js.dabbler.org). This version...</description>
<guid isPermaLink="false">411@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>I've posted a <a href="http://davidbau.com/downloads/templet.py">new version</a> of the templet.stringfunction utility <a href="http://davidbau.com/archives/2007/03/11/python_string_functions.html">I have discussed before</a>.  I have been using it to make a bunch of web UI in programming projects with my son (actually pretty sophisticated little projects - <a href="http://js.dabbler.org">http://js.dabbler.org</a>).  This version reflects what's needed for a 2011-era web app.</p>

<p><b>What's New</b></p>

<p>This version is still svelte, clocking in at 91 lines of python code (plus comments and tests).  Version 3.3 changes the following from v2:</p>

<ul>
<li>The old class-template idioms in the original version have been removed; they were slow and unwieldy.  Now it's just @stringfunction and @unicodefunction.
<li>Common uses of $ in javascript no longer need to be escaped in templates.  Jquery $. and $( are very common, and regular expressions often have $/ and $' and $", so all these sequences now pass through the template without escape.
<li>Line numbers are aligned exactly so that both syntax errors and runtime errors in exception traces are reported on the correct line of the template file in which the code appears.
</ul>

<p>Together these small changes - particularly accurate error line numbers - make @stringfunction much more usable for composing large templates for website development.</p>

<p><b>Usage</b></p>

<p>Usage is unchanged: just annotate a python function with @stringfunction or @unicodefunction, and then put the template text where the docstring would normally be.  Leave the function body empty, and efficient code to concatenate the contents will be created.</p>

<pre style=background:lightblue>
  from templet import stringfunction
  
  @stringfunction
  def myTemplate(animal, body):
    "the $animal jumped over the $body."
  
  print myTemplate('cow', 'moon')
</pre>

<p>This is turned into something like this:</p>

<pre style=background:lightblue>
  def myTemplate(animal, body):
    out = []
    out.append("the ")
    out.append(str(animal))
    out.append(" jumped over the ")
    out.append(str(body))
    out.append(".")
    return ''.join(out)
</pre>

<p>There are just six constructs that are supported, all starting with $:</p>

<ul>
<li><b>$myvar</b> inserts the value of the variable 'myvar'
<li><b>${...}</b> evaluates the expression and inserts the result
<li><b>${[...]}</b> runs a list comprehension and concatenates the results
<li><b>${{...}}</b> executes enclosed code; use 'out.append(text)' to insert text
<li><b>$$</b> an escape for a single $
<li><b>$</b> (at the end of the line) is a line continuation
</ul>

<p>All ordinary uses of $ in the template need to be escaped by doubling the $$ - with the exception of (as mentioned above) $., $(, $/, $', and $".</p>

<p><b>Philosophy</b></p>

<p>The philosophy behind templet is to introduce only the concepts necessary to simplify the construction of long strings in python; and then to encourage all other logic to be expressed using ordinary python.</p>

<p>A @stringfunction function can do everything that you can do with any function that returns a string: it can be called recursively; it can have variable or keyword arguments; it can be a member of a package or a method of a class; and it can access global imports or invoke other packages.  As a result, although the construct is extremely simple, it brings all the power of python to templates, and the @stringfunction idea scales very well.</p>

<p>Beyond simple interpolation, templet does not invent any new syntax for data formatting.  If you want to format a floating-point number, you can write <tt>${"%2.3f" % num}</tt>; if you want to escape HTML sequences, just write <tt>${cgi.escape(message)}</tt>.  Not as brief as a specialized syntax, but easy to remember, brief enough, and readable to any python programmer.</p>

<p>Similarly, templet does not invent any new control flow or looping structures.  To loop a template, you need to use a python loop or list comprension and call the subtemplate as a function:</p>

<pre style=background:lightblue>
 @stringfunction
 def doc_template(table):
   """
   &lt;body>
   &lt;h1>${ table.name }&lt;/h1>
   &lt;table>
   ${{
     for item in table:
       out.append(self.row_template(item))
   }}
   &lt;/table>
   &lt;/body>
   """
</pre>

<p>If you prefer list comprehensions, it is slightly more brief:</p>

<pre style=background:lightblue>
 @stringfunction
 def doc_template(table):
   """
   &lt;body>
   &lt;h1>${ table.name }&lt;/h1>
   &lt;table>
   ${[self.row_template(item) for item in table]}
   &lt;/table>
   &lt;/body>
   """
</pre>

<p>The design encourages simple templates that read in straight-line fashion, an excellent practice in the long run.  Although when invoking subtemplates you need to pass state, of course you can use @stringfunction to make methods and pass state on "self", or use object parameters.</p>

<p><b>Details and Style</b></p>

<p>Some tips/guidelines for using these annotations.</p>

<p>Whitespace can be important inside HTML, but for python readability you often want to indent things, so @unicodefunction / @stringfunction gives you a few tools:</p>

<ol><li>It identifies the number of leading spaces that are uniformly used to the left of the template and strips them.<li>It strips the first line of the template, if empty.<li>It allows you to use a $ at the end of a line for a line continuation.</ol>

<p>So my recommended style for multiline templates is:<br />
<ul><li>indent template text in the function as if it were python code.<br />
<li>use a python triple-quote and put the opening quote on its own line.<br />
<li>never indent HTML tags - they just get too deep, so put them all at column 0.<br />
<li>when nesting gets confusing, for readability, just put one tag on each line.<br />
<li>liberally use $ continuations if layout demands no-whitespace.<br />
<li>indent code inside ${{ and then put }} on its own line (a newline right after a closing }} is eaten).<br />
</ul></p>

<p>Relative indenting for python code inside ${{...}} is preserved using the same leading-space-stripping trick as is used for the templates themselves, so you can indent embedded python as normal, and you can start the indenting at whichever column feels natural.  I usually indent embedded python by one more level.</p>

<p>In the unusual case where it is necessary to emit text that has leading spaces on every line, you can begin the template with a continuation line with the $ in the column that you want to treat as column zero.</p>

<p>One question is whether the opening """ should be on the same line as the def or its own line.  Either style is supported - for line number purposes, the program source is just scanned to discover the position of the opening quote - but for clarity I usually put the opening quote on its own line.</p>

<p>For example, if you want to achieve all on one line the following:</p>

<pre><font size=-5>
&lt;tr>&lt;td class="...">&lt;a class="..." href="/foo/bar/...">....&lt;/a>&lt;/td>&lt;td class="...">...&lt;/td>&lt;/tr>
</font></pre>

<p>Then you could use:</p>

<pre style="background:lightblue">
@unicodefunction
def table_row(row_data):
  """
  &lt;tr>$
  &lt;td class="${col1_class} def">$
  &lt;a class="${link_class}"$
   href="/foo/bar/${cgi.escape(filename, True)}">$
  ${cgi.escape(link_text})}$
  &lt;/a>$
  &lt;/td>$
  &lt;td class="${col2_class}">$
  ${{
    if (enrolled): out.append('enrolled')
  }}
  ${cgi.escape(label_text)}$
  &lt;/td>$
  &lt;/tr>
  """
</pre>]]></content:encoded>
<dc:date>2011-09-09T13:08:26-05:00</dc:date>
</item>
<item>
<title>PUT and DELETE in call.jsonlib.com</title>
<link>http://davidbau.com/archives/2011/03/02/put_and_delete_in_calljsonlibcom.html</link>
<description><![CDATA[My son was trying to use call.jsonlib.com to access the Google Docs API and told me he needed the ability to execute HTTP PUT and DELETE, not just GET and POST. Done. Now call.jsonlib.com/fetch supports a "&amp;method=" CGI argument that...]]></description>
<guid isPermaLink="false">409@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>My son was trying to use <a href="http://call.jsonlib.com/">call.jsonlib.com</a> to access the <a href="http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html">Google Docs API</a> and told me he needed the ability to execute HTTP PUT and DELETE, not just GET and POST.</p>

<p>Done.  Now call.jsonlib.com/fetch supports a "&amp;method=" CGI argument that you can set to PUT or DELETE, and Anthony reports that it's working fine for accessing the API.  (Does anybody know of any simple public HTTP servers out there that will echo your request so that it can be easily tested?  At most URLs, using these unusual methods will just give you a 405 error.)</p>

<p><b>Access-Control-Allow-Origin</b></p>

<p>Another change is that call.jsonlib.com now supports cross-domain access via XHR (not just jsonp) on browsers that support the Access-Control-Allow-Origin header.</p>

<p>The problem with JSONP is that you can only use the GET method, not POST, so all of your submitted data must fit in a URL string.  Some browsers, servers, and proxies may have trouble handling URL strings longer than about 2K, so this means you cannot use JSONP to reliably submit long chunks of data.</p>

<p>The solution is to go back to using traditional XHR techniques, but to tell your browser that cross-origin access is OK using the Access-Control-Allow-Origin header.  This header is supported on modern browsers (FF, Chrome, Safari, Opera, and IE8+).</p>

<p>You can write code like the following (jQuery) to use the POST method to interact with jsonlib:</p>

<pre class=code>
$.post('http://call.jsonlib.com/fetch',
  { url: 'http://davidbau.com/data/animals' },
  function(m) { output(m); },
  'json');
</pre>

<p>The above just uses POST to talk to jsonlib, and asks jsonlib to do a GET, but obviously you can use a POST to ask jsonlib to do a POST or a PUT as well.</p>

<p><b>Sniffing Character Encodings</b></p>

<p>The other update is logic for sniffing encodings.  Since call.jsonlib.com always returns its contents as JSON unicode strings, it needs to understand how to convert responses from arbitrary other encodings.  For text documents, it now uses BeautifulSoup and the chardet library to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful Soup Gives You Unicode, Dammit">automatically detect encodings</a> and convert text and html documents to unicode.  This behavior can be overridden using the &amp;encoding= CGI argument.</p>

<p>Examples: <a href="http://call.jsonlib.com/fetch?url=http://davidbau.com/data/utf8quote.txt">fetching utf-8 smart quotes</a> and <a href="http://call.jsonlib.com/fetch?url=http://davidbau.com/data/1252quote.txt">fetching cp-1252 smart quotes</a>.</p>

<p>Non-text documents are treated as iso-8859-1 which is the simplest way use unicode 0-255 codepoints as a way of storing a bytestream (example: <a href="http://call.jsonlib.com/fetch?url=http://davidbau.com/images/art/enigma.jpg">fetching a jpeg</a>.)</p>]]></content:encoded>
<dc:date>2011-03-02T06:52:50-05:00</dc:date>
</item>
<item>
<title>Party like it&apos;s 1789</title>
<link>http://davidbau.com/archives/2011/02/24/party_like_its_1789.html</link>
<description>What is going on in the world? It is like the 18th century out there. The information-dominated 21st century is different from the nuclear-tipped 20th. In today&apos;s world, the power of the message is what matters. Will historians see the...</description>
<guid isPermaLink="false">408@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>What is going on in the world?  It is like the 18th century out there.</p>

<p><a href="http://davidbau.com/archives/2007/02/25/obamas_weak_speech.html">The information-dominated 21st century is different from the nuclear-tipped 20th. In today's world, the power of the message is what matters.</a></p>

<p>Will historians see the 21st century as a second Enlightenment?</p>]]></content:encoded>
<dc:date>2011-02-24T18:43:11-05:00</dc:date>
</item>
<item>
<title>Using goo.gl with jsonlib</title>
<link>http://davidbau.com/archives/2011/01/30/using_googl_with_jsonlib.html</link>
<description>An example using jsonlib to invoke an inconvenient HTTP API from Javascript. When Google released the goo.gl URL shortener API recently, they did not provide a JSONP API, so it is not convenient to make goo.gl URLs directly from Javascript....</description>
<guid isPermaLink="false">407@http://davidbau.com/</guid>
<dc:subject></dc:subject>
<content:encoded><![CDATA[<p>An example using <a href="http://call.jsonlib.com/">jsonlib</a> to invoke an inconvenient HTTP API from Javascript.</p>

<p>When Google released the <a href="http://code.google.com/apis/urlshortener/v1/getting_started.html">goo.gl URL shortener API</a> recently, they did not provide a JSONP API, so it is not convenient to make <a href="http://goo.gl/">goo.gl</a> URLs directly from Javascript.  But then I wanted to implement a goo.gl-based "Save As Short Url" feature in the save box of <a href="https://chrome.google.com/webstore/detail/ccbhekjfmokgloklnjnidfhlaofegeno">Heidi's Sudoku</a> Chrome App.  The app is 100% Javascript and isn't even hosted on its own web server.  What to do?</p>

<p>It is easy to do cross-domain HTTP by bouncing JSONP requests off <a href="http://call.jsonlib.com/">call.jsonlib.com</a>.  With jsonlib, invoking the goo.gl API is just a few lines of code.</p>

<p><b>How To Do It</b></p>

<p>Here is how the <a href="http://code.google.com/apis/urlshortener/v1/getting_started.html#shorten">goo.gl API</a> works:</p>

<ol><li>You assemble a JSON string containing your long URL in the 'longUrl' field.
<li>This string must be POSTed to the googleapis server, with Content-Type "application/json".
<li>The response is JSON that will have your short URL in the 'id' field.</ol>

<p>In Javascript, it is inconvenient to POST data that is not formatted as "application/x-www-form-urlencoded", and it is hard to use cross-domain HTTP requests that do not return script-formatted JSONP services.  However, <a href="http://call.jsonlib.com/">call.jsonlib.com</a> solves both of these problems easily.</p>

<p>Here is the code for a goo.gl shortener wrapper that shows how it can be done with a single call to <a href="http://call.jsonlib.com/jsonlib-src.js">jsonlib.fetch</a>:</p>

<pre class=code>
&lt;script src="http://call.jsonlib.com/jsonlib.js">&lt;/script>
&lt;script>
function googlurl(url, cb) {
  jsonlib.fetch({
    url: 'https://www.googleapis.com/urlshortener/v1/url',
    header: 'Content-Type: application/json',
    data: JSON.stringify({longUrl: url})
  }, function (m) {
    var result = null;
    try {
      result = JSON.parse(m.content).id;
      if (typeof result != 'string') result = null;
    } catch (e) {
      result = null;
    }
    cb(result);
  });
}
// Make a short URL for a nicely written book.
googlurl('http://www.amazon.com/Numerical-Linear-Algebra-Lloyd-'
       + 'Trefethen/dp/0898713617', function(s) { alert(s); });
&lt;/script>
</pre>

<p>Voila!  Short URLs in a single function call.</p>

<p><a href="http://dabbler.org/edit/david/googlshortener.html">Play with the code here if you like</a>.</p>]]></content:encoded>
<dc:date>2011-01-30T11:53:47-05:00</dc:date>
</item>


</channel>
</rss>