<?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>incompl - Greg Smith&#039;s Web Design and JavaScript Blog &#187; programming</title>
	<atom:link href="http://incompl.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://incompl.com</link>
	<description>Design, Programming and the Web</description>
	<lastBuildDate>Mon, 26 Jul 2010 02:54:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Uploading Large Files in Ruby on Rails</title>
		<link>http://incompl.com/2010/uploading-large-files-in-ruby-on-rails/</link>
		<comments>http://incompl.com/2010/uploading-large-files-in-ruby-on-rails/#comments</comments>
		<pubDate>Thu, 06 May 2010 20:26:04 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=866</guid>
		<description><![CDATA[File upload is a common feature for web sites, yet for some reason a lot of frameworks make it hard on you. JSF doesn&#8217;t even support it by default; it requires the installation of additional libraries. In Ruby on Rails it worked pretty well out of the box, but with a catch. File uploads are<br/><a href="http://incompl.com/2010/uploading-large-files-in-ruby-on-rails/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p>File upload is a common feature for web sites, yet for some reason a lot of frameworks make it hard on you. <a href="http://en.wikipedia.org/wiki/JavaServer_Faces">JSF</a> doesn&#8217;t even support it by default; it requires the installation of additional libraries.</p>
<p>In Ruby on Rails it worked pretty well out of the box, but with a catch. File uploads are stored in memory, so if you are letting users upload large files, the server will quickly run out of memory.</p>
<p>To solve this I discovered a new (as of 2.3) component of Rails called <a href="http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal">Metal</a>. Metal is a thin wrapper around <a href="http://rack.rubyforge.org/">Rack</a>, a minimal piece of middleware that handles HTTP requests for Rails. While Metal is a part of Rails, it lets you bypass Rails for the most part, and work at a lower level for those performance-critical bits. Happily, Metal lets you grab an uploaded file without making a copy of it in memory.</p>
<p>Here is an example of a Metal class that does file upload. To test this you&#8217;d just need to throw it in a <em>/app/metal</em> directory for your Rails project, then navigate to <em>http://example.com/uploadtest</em> to try it out.</p>
<blockquote>
<pre> 
class Uploadtest

  def self.call(env)

    if env["PATH_INFO"] =~ /^\/uploadtest$/

      request = Rack::Request.new(env)

      # Get temp file from request
      # Format: {:filename, :type, :name, :tempfile, :head}
      file = request.POST["file"] 

      # Make sure we have the parameter
      if !file.nil?

        # Create new file path
        directory = File.join("uploads", "uploadtest")
        FileUtils.mkpath(directory)
        path = File.join(directory, file[:filename])

        # Copy the uploaded file
        FileUtils.cp file[:tempfile].path, path

        # Response
        [200, {"Content-Type" =&gt; "text/html"}, ["Upload Complete"]]

      else
        # Show an example submission form
        [200, {"Content-Type" =&gt; "text/html"},
              ['&lt;form method="post"
                      action="/uploadtest"
                      enctype="multipart/form-data"&gt;
                &lt;input type="file" name="file"/&gt;
                &lt;input type="submit" value="Upload"/&gt;
                &lt;/form&gt;']]
      end
    else
      [404, {"Content-Type" =&gt; "text/html"}, ["Not Found"]]
    end
  end
end</pre>
</blockquote>
<p>I hope this helps someone who runs into the same situation I was in!</p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2010/uploading-large-files-in-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Menu Key</title>
		<link>http://incompl.com/2010/the-menu-key/</link>
		<comments>http://incompl.com/2010/the-menu-key/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 17:42:40 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=785</guid>
		<description><![CDATA[Do you use your keyboard&#8217;s Menu key? The one with a picture of a menu and a cursor. All it does is bring up the context menu. It was introduced at the same time as the Windows key but didn&#8217;t get the same press, probably because its effect couldn&#8217;t compare to the indignity of having<br/><a href="http://incompl.com/2010/the-menu-key/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://incompl.com/wp-content/uploads/2010/04/keyboard1.jpg"><img class="alignright size-full wp-image-790" title="Menu key" src="http://incompl.com/wp-content/uploads/2010/04/keyboard1.jpg" alt="The menu key on a standard keyboard" width="301" height="231" /></a>Do you use your keyboard&#8217;s <a href="http://en.wikipedia.org/wiki/Menu_key">Menu key</a>? The one with a picture of a menu and a cursor. All it does is bring up the <a href="http://en.wikipedia.org/wiki/Context_menu">context menu</a>. It was introduced at the same time as the <a href="http://en.wikipedia.org/wiki/Windows_key">Windows key</a> but didn&#8217;t get the same press, probably because its effect couldn&#8217;t compare to the indignity of having a Windows logo affixed to nigh every computer user&#8217;s keyboard, their choice of OS notwithstanding.</p>
<p>What good is this thing in practice? For awhile I figured this would be an awesome way to correct typos while typing, since the context menu has corrections. Mistype, menu key, enter, keep typing. But alas, spell checkers notice misspellings after the word has lost focus, so the Menu key isn&#8217;t really practical for this use.</p>
<p>So what is this thing for? Does anyone use their Menu key? Was it just another button to add to already-overcrowded keyboards along with the overwhelmingly useful ones like &#8220;open web browser&#8221; and &#8220;shut down&#8221;? Maybe that&#8217;s why the delightfully simple <a href="http://en.wikipedia.org/wiki/File:Apple-wireless-keyboard-aluminum-2007.jpg">Apple keyboards</a> don&#8217;t have it?</p>
<p><a href="http://en.wikipedia.org/wiki/File:Wireless_Media_Center_keyboard_FK-760.JPG">[Image Credit]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2010/the-menu-key/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Incubators</title>
		<link>http://incompl.com/2010/incubators/</link>
		<comments>http://incompl.com/2010/incubators/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 16:21:15 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=748</guid>
		<description><![CDATA[Robert Biswas-Diener wrote an article on CNN coining the term &#8220;incubator&#8221; for people who seem like procrastinators but are actually a different breed. I felt that this article described my own work habits perfectly. Incubators have a clear sense of deadlines, gets things done on time, and produce quality work. Before performing an important task,<br/><a href="http://incompl.com/2010/incubators/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://incompl.com/wp-content/uploads/2010/02/coffee.jpg"><img class="alignright size-full wp-image-749" title="Coffee" src="http://incompl.com/wp-content/uploads/2010/02/coffee.jpg" alt="A picture of a mug of coffee" width="203" height="209" /></a>Robert Biswas-Diener wrote <a href="http://www.cnn.com/2010/LIVING/worklife/02/16/o.procrastinator.or.incubator/index.html?hpt=Mid">an article on CNN</a> coining the term &#8220;incubator&#8221; for people who seem like procrastinators but are actually a different breed. I felt that this article described my own work habits perfectly.</p>
<p>Incubators have a clear sense of deadlines, gets things done on time, and produce quality work. Before performing an important task, such as writing a term paper, they engage in an incubation phase that is necessary for their process. It looks like slacking off, but their mind is constantly brewing, preparing information for the outpouring of effort to come.</p>
<p>I always knew that I work this way, and that other people are like me. What I like about this article, though, is that Robert decided to give a name to it. From the article:</p>
<blockquote><p>For most incubators, having a label that is less pejorative than &#8220;procrastinator&#8221; can be a breath of fresh air.</p></blockquote>
<p><a href="http://www.flickr.com/photos/deapeajay/3046121538/">[image credit]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2010/incubators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Text Editor Question</title>
		<link>http://incompl.com/2009/the-text-editor-question/</link>
		<comments>http://incompl.com/2009/the-text-editor-question/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 18:56:58 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=563</guid>
		<description><![CDATA[Back in college, I had a professor pose an interesting question on an exam. It was worded like this: &#8220;On the back of this paper, write out every keystroke and mouseclick you would take to add five spaces at the beginning of the first 10 lines of a file in a text editor.&#8221; Naturally, some<br/><a href="http://incompl.com/2009/the-text-editor-question/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://incompl.com/wp-content/uploads/2009/12/800px-Linotype_CRTronic_360.jpg"><img class="alignright size-full wp-image-570" title="800px-Linotype_CRTronic_360" src="http://incompl.com/wp-content/uploads/2009/12/800px-Linotype_CRTronic_360.jpg" alt="800px-Linotype_CRTronic_360" width="243" height="191" /></a>Back in college, I had a <a href="http://en.wikipedia.org/wiki/William_Clinger_(computer_scientist)">professor</a> pose an interesting question on an exam. It was worded like this:</p>
<blockquote><p>&#8220;On the back of this paper, write out every keystroke and mouseclick you would take to add five spaces at the beginning of the first 10 lines of a file in a text editor.&#8221;</p></blockquote>
<p>Naturally, some people protested. But he insisted that the literal meaning of the question was to be carried out.</p>
<p>Some students assumed it was a trick question that they didn&#8217;t understand, and wrote nothing. Some students write out the entirety of what was necessary to do this in Notepad:</p>
<blockquote><p>space, space, space, space, space, down, home, space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space, down, home,space, space, space, space, space</p></blockquote>
<p>At the time, I had been learning <a href="http://en.wikipedia.org/wiki/Vim_(text_editor)">Vim</a> at the professor&#8217;s advice. So, feeling very clever, I wrote this on the back of my paper:</p>
<blockquote><p>:1,10s/^/     /</p></blockquote>
<p>In a few days, when the exam was returned, students noticed that the this question had not been graded. The professor answered them:</p>
<blockquote><p>&#8220;Your reward for getting it right is not having to write out an entire page of text to do something trivially simple. If you haven&#8217;t followed my advice and learned a good text editor, you waste this much time a hundred times over every time you write a program.&#8221;</p></blockquote>
<p>Invaluable advice for any programmer. Use good tools, and get really good at using them.</p>
<p><a href="http://www.flickr.com/people/8399025@N07">[Image Credit]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2009/the-text-editor-question/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regarding Block Style</title>
		<link>http://incompl.com/2009/regarding-block-style/</link>
		<comments>http://incompl.com/2009/regarding-block-style/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 20:31:45 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=456</guid>
		<description><![CDATA[I went to a great talk by Douglas Crockford today. If you&#8217;re a JavaScript programmer and haven&#8217;t read any of his articles, head over to his site and get started. It&#8217;s more important than reading this blog.  Seriously. Alright. I want to show an example he used that doesn&#8217;t seem to be included in any<br/><a href="http://incompl.com/2009/regarding-block-style/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://incompl.com/wp-content/uploads/2009/09/374961356_4ea13e95e1.jpg"><img class="alignright size-full wp-image-462" title="374961356_4ea13e95e1" src="http://incompl.com/wp-content/uploads/2009/09/374961356_4ea13e95e1.jpg" alt="374961356_4ea13e95e1" width="194" height="200" /></a>I went to a great talk by Douglas Crockford today. If you&#8217;re a JavaScript programmer and haven&#8217;t read any of his articles, head over to <a href="http://crockford.com">his site</a> and get started. It&#8217;s more important than reading this blog.  Seriously.</p>
<p>Alright. I want to show an example he used that doesn&#8217;t seem to be included in any of his articles online. This may not be exactly the same, but is close to how I remember it.</p>
<p>Everyone argues about where to put the starting curly-brace of a block.  Usually they don&#8217;t have any substantial cause to pick one over the other, but everyone agrees one technique should be used consistently in a given program.  There is a reason to choose one style over the other in JavaScript. Check out this example:</p>
<blockquote>
<pre>function test1() {
    return {
        foo: "bar"
    };
}

function test2()
{
    return
    {
        foo: "bar"
    };
}

alert(test1() === undefined); // false
alert(test2() === undefined); // true</pre>
</blockquote>
<p>These two functions appear to only differ in their formatting.  Surprised by these results?</p>
<p>The first function does exactly what it looks like it should. In the second, 4 different language design problems cause the program to do something unexpected while providing no errors.</p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/JavaScript_syntax#Whitespace_and_semicolons">Semi-colon insertion</a> causes the <em>return</em> to be a <em>return;</em></li>
<li>A line that starts with <em>{</em> starts a block. There is no block-level scope, so in this case the block does nothing. This &#8220;feature&#8221; is only there because <a href="http://en.wikipedia.org/wiki/C_(programming_language)">C</a> has it.</li>
<li>The<em> foo: </em>looks like part of an object literal, but we&#8217;re in a block, not an object literal. This should be an error, right? No, it&#8217;s a label. Even though we&#8217;re not in code where a label could do anything, such as a <em>for</em> loop.</li>
<li>The rest of the line after the label is the value &#8220;bar&#8221;. A value by itself counts as a statement, even though it doesn&#8217;t do anything.</li>
</ol>
<p>Wow. That function does something wildly different than what it appears to do. The point Crockford was making here was that in JavaScript, unlike in most languages, preferring the first type of curly-brace placement helps you avoid mistakes like this one.</p>
<p>He also mentioned that <a href="http://jslint.com/">JSLint</a>,  his free JavaScript code quality tool, is able to pick up on this kind of mistake. Try running my example through it!</p>
<p><a href="http://www.flickr.com/photos/lifeontheedge/374961356/">[Image Credit]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2009/regarding-block-style/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exceptional Exceptions</title>
		<link>http://incompl.com/2009/exceptional-exceptions/</link>
		<comments>http://incompl.com/2009/exceptional-exceptions/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 18:07:33 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=405</guid>
		<description><![CDATA[I&#8217;ve heard a lot of mantras regarding how to handle exceptions properly in programming languages that support checked exceptions (eg Java).  Sometimes these mantras are regarded a little too highly, even doing harm in some situations.  I&#8217;d like to dissect a couple of these. Never Sometimes catch the top-level &#8220;Exception&#8221; class. There are times when<br/><a href="http://incompl.com/2009/exceptional-exceptions/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://incompl.com/wp-content/uploads/2009/08/wtf-coffee.jpg"><img class="alignright size-medium wp-image-411" title="wtf coffee" src="http://incompl.com/wp-content/uploads/2009/08/wtf-coffee-300x246.jpg" alt="wtf coffee" width="300" height="246" /></a>I&#8217;ve heard a lot of mantras regarding how to handle exceptions properly in programming languages that support checked exceptions (eg Java).  Sometimes these mantras are regarded a little too highly, even doing harm in some situations.  I&#8217;d like to dissect a couple of these.</p>
<h2><span style="text-decoration: line-through;">Never</span> Sometimes catch the top-level &#8220;Exception&#8221; class.</h2>
<p>There are times when it is definitely appropriate.  Imagine some controller code in a web application.  An underlying system has produced an unexpected exception.  Controller code can&#8217;t do anything to fix it, but allowing the exception to continue up the call stack would cause a <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error">500 error</a>.  Catching any thrown exception can allow the Controller to do something better, like output a message to the user notifying them of the error and making a suggestion on what to do next.</p>
<p>In short, catch the top-level Exception class if you know for sure that every thrown exception will be handled more poorly by your caller than you can handle it, and you can&#8217;t improve the caller&#8217;s behavior.</p>
<h2><span style="text-decoration: line-through;">Always</span> When appropriate catch the most  specific exceptions thrown.</h2>
<p>Catching the most specific exceptions thrown is meant to create error handling specific to the problem that was raised.  For example, a &#8220;DatabaseConnectionLost&#8221; exception would be caught, and in the catch block the connection would be repaired.  It seems reasonable to always want to do this, but in practice, some exceptions are thrown in cases where you can&#8217;t do anything about it.  Lets say a method throws &#8220;DatabaseConnectionLost&#8221; and &#8220;DatabaseQueryInvalid&#8221;, both of which are children of &#8220;DatabaseException.&#8221;  In a situation where the calling code can&#8217;t repair the connection or fix the query, catching the parent is appropriate, rather than handling each specific case without anything specific to do.  If the code can do something like email the DBA, catching DatabaseException seems useful.</p>
<p>In short, you should always catch the most specific exceptions that you can actually do something about.</p>
<h2>Never leave a catch block empty (if you can help it)</h2>
<p>This is actually one of those rare never-ism that I&#8217;m OK with.  But sadly, when interfacing with poorly thought out code, sometimes you are forced to do this.</p>
<p>Lets say you want to create User objects and add them all to a list, and you know their IDs.  You can get users by ID from a piece of library code that you cannot change.  However, you cannot check if a user ID is valid: there is no method for it.  Further, the getUser method throws UserIdInvalidException when you try to get a user by an invalid ID.  For you, an invalid ID is not an exceptional circumstance, but the library code assumes it is.  Sadly you might be forced to write something like this:</p>
<blockquote>
<pre>for (id : userIds) {</pre>
<pre>    try {</pre>
<pre>        users.add(UserLib.getUser(id));</pre>
<pre>    }</pre>
<pre>    catch (UserIdInvalidException e) {</pre>
<pre>        // If ID is invalid don't include it on the list</pre>
<pre>    }</pre>
<pre>}</pre>
</blockquote>
<p>It is very rare that you actually can&#8217;t find a better way.  For the most part, consider a catch block like this to be a mistake unless proven otherwise.</p>
<h2>Conclusion</h2>
<p>Forget all these &#8220;always&#8221; and &#8220;never&#8221; rules.  A rule to live by would read more like this:  Exceptions should always be handled as best they can by the code best suited to handle them.</p>
<p>[<a href="http://www.flickr.com/photos/bitzcelt/399136360/">Image credit</a>]</p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2009/exceptional-exceptions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My Favorite WMP Bug</title>
		<link>http://incompl.com/2009/my-favorite-wmp-bug/</link>
		<comments>http://incompl.com/2009/my-favorite-wmp-bug/#comments</comments>
		<pubDate>Fri, 10 Apr 2009 19:38:38 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=260</guid>
		<description><![CDATA[Found a very interesting bug in Windows Media Player (WMP).  An embedded player will fail to play if the URL of the page it is embedded into is too long. This is fun because you can see this on any website. I have only tried this in Firefox and Internet Explorer 7 on Windows, but<br/><a href="http://incompl.com/2009/my-favorite-wmp-bug/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p>Found a very interesting bug in Windows Media Player (WMP).  An embedded player will fail to play if the URL of the page it is embedded into is too long.</p>
<p>This is fun because you can see this on any website.  I have only tried this in Firefox and Internet Explorer 7 on Windows, but compare these URLs:</p>
<p><a href="http://www.mediacollege.com/video/format/windows-media/streaming/embed-examples.html">Page with short URL</a></p>
<p><a href="http://www.mediacollege.com/video/format/windows-media/streaming/embed-examples.html?&amp;query=%E6%94%BE%E4%B8%8B%E8%BA%AB%E6%AE%B5%E8%83%BD%E5%AE%9E%E6%96%BD%E5%B0%B1%E8%83%BD%E5%A4%9F%E6%8&amp;query=%E6%94%BE%E4%B8%8B%E8%BA%AB%E6%AE%B5%E8%83%BD%E5%AE%9E%E6%96%BD%E5%B0%B1%E8%83%BD%E5%A4%9F%E6%8&amp;query=%E6%94%BE%E4%B8%8B%E8%BA%AB%E6%AE%B5%E8%83%BD%E5%AE%9E%E6%96%BD%E5%B0%B1%E8%83%BD%E5%A4%9F%E6%8&amp;query=%E6%94%BE%E4%B8%8B%E8%BA%AB%E6%AE%B5%E8%83%BD%E5%AE%9E%E6%96%BD%E5%B0%B1%E8%83%BD%E5%A4%9F%E6%8&amp;query=%E6%94%BE%E4%B8%8B%E8%BA%AB%E6%AE%B5%E8%83%BD%E5%AE%9E%E6%96%BD%E5%B0%B1%E8%83%BD%E5%A4%9F%E6%8">Same page with long URL parameters added</a></p>
<p>The WMP APIs are pretty embarrassing, but for me, this one takes the cake.</p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2009/my-favorite-wmp-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript: The Replace Secret</title>
		<link>http://incompl.com/2008/javascript-the-replace-secret/</link>
		<comments>http://incompl.com/2008/javascript-the-replace-secret/#comments</comments>
		<pubDate>Thu, 25 Dec 2008 02:31:22 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[replace]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=189</guid>
		<description><![CDATA[I was taking a look at the MDC page for JavaScript&#8217;s replace function and noticed something interesting: It can take a function for its second argument.  That page is a little fuzzy on the details and other docs on the internet generally don&#8217;t even mention this option.  So I explored a little.  Here is an<br/><a href="http://incompl.com/2008/javascript-the-replace-secret/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p>I was taking a look at <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Replace">the MDC page for JavaScript&#8217;s <em>replace</em> function</a> and noticed something interesting: It can take a function for its second argument.  That page is a little fuzzy on the details and other docs on the internet generally don&#8217;t even mention this option.  So I explored a little.  Here is an example of using this functionality to do a search and replace.</p>
<blockquote>
<pre>var text = "Any reviewer who expresses rage and loathing for a novel" +
           " is preposterous. He or she is like a person who has put" +
           " on full armor and attacked a hot fudge sundae." +
           " -- Kurt Vonnegut"</pre>
<pre>var count = 0</pre>
<pre>var newVersion = text.replace(/ (\w+) (is)/g, function(match, g1, g2,
                                                       position, input) {</pre>
<pre>    count++</pre>
<pre>    document.write("Match: [" + match + "]. Found [" + g1 +
                   "] before [" + g2 + "] at position [" +
                   position + "].&lt;br/&gt;")</pre>
<pre>    return " " + g1 + " " + " REALLY is"</pre>
<pre>})</pre>
<pre>document.write(count + " matches found&lt;br/&gt;")
document.write("New version:&lt;br/&gt;"
document.write(newVersion)</pre>
</blockquote>
<p>This code will output:</p>
<blockquote><p>Match: [ novel is]. Found [novel] before [is] at position [50].<br />
Match: [ she is]. Found [she] before [is] at position [79].<br />
2 matches found<br />
New version:<br />
Any reviewer who expresses rage and loathing for a novel REALLY is preposterous. He or she REALLY is like a person who has put on full armor and attacked a hot fudge sundae. &#8212; Kurt Vonnegut</p></blockquote>
<p>There is a lot going on in this example, but I think it demonstrates what you can do with this function that is definitely not possible if you only use a string for the second argument to replace.</p>
<p>Here are what appear to be the arguments to the function passed to replace:</p>
<blockquote><p>Match: The current substring that was matched by the regex.</p>
<p>Group 1: The first parenthesized group in the regex.</p>
<p>&#8230;</p>
<p>Group N: The Nth parenthesized group in the regex.  There can be an arbitrary number of these.</p>
<p>Position:  The numeric position in the text where this match occurs.</p>
<p>Input: The entire input text with changes that have ocurred so far.</p></blockquote>
<p>The power to customize your replacement based on a variety of factors, as well as have an unrelated behavior happen for each match, is definitely useful.  Another JavaScript secret revealed!</p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2008/javascript-the-replace-secret/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Find Idea</title>
		<link>http://incompl.com/2008/a-find-idea/</link>
		<comments>http://incompl.com/2008/a-find-idea/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 19:42:29 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[intellij idea jetbrains search]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=170</guid>
		<description><![CDATA[Check out this suggestion IntelliJ IDEA makes when I try to find a file: Never mind the terrible file name.  Notice how it finds it even though I didn&#8217;t know it had an underscore in the name.  Making the search do exactly what you expect would have been fine, but a real programmer thinks about<br/><a href="http://incompl.com/2008/a-find-idea/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p>Check out this suggestion <a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a> makes when I try to find a file:</p>
<p><a href="http://incompl.com/wp-content/uploads/2008/11/ideafind.png"><img class="alignnone size-full wp-image-171" title="IDEA Find" src="http://incompl.com/wp-content/uploads/2008/11/ideafind.png" alt="" width="297" height="81" /></a></p>
<p>Never mind the terrible file name.  Notice how it finds it even though I didn&#8217;t know it had an underscore in the name.  Making the search do exactly what you expect would have been fine, but a real programmer thinks about what is really useful, even if it defies expectations.</p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2008/a-find-idea/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Just Do It</title>
		<link>http://incompl.com/2008/dont-just-do-it/</link>
		<comments>http://incompl.com/2008/dont-just-do-it/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 22:22:41 +0000</pubDate>
		<dc:creator>gsmith</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[management]]></category>
		<category><![CDATA[project]]></category>

		<guid isPermaLink="false">http://incompl.com/?p=142</guid>
		<description><![CDATA[The most important programming skill I can think of has nothing to do with programming.  It is the ability to think of every task in the context of the software that is being made. The task: write an HTML parser in one week.  A good programmer gets it done.  A great one explains why the<br/><a href="http://incompl.com/2008/dont-just-do-it/"> [read more] </a>]]></description>
			<content:encoded><![CDATA[<p>The most important programming skill I can think of has nothing to do with programming.  It is the ability to think of every task in the context of the software that is being made.</p>
<p>The task: write an HTML parser in one week.  A good programmer gets it done.  A great one explains why the project is better off using an existing HTML parser.</p>
<p>The task: write a function to export a data structure to XML in three days.  A good programmer gets it done.  A great programmer asks why, finds out the reason for the task is irrelevant, and spends three days doing something useful.</p>
<p>The task: write a class that encapsulates some inventory business logic in a day.  A good programmer gets it done.  A great programmer thinks about it, nods, then gets it done.</p>
<p>If you&#8217;re worried that if you followed this process you&#8217;d often get the response &#8220;Just do it!&#8221; then your management may have some serious problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://incompl.com/2008/dont-just-do-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
