<?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>Codethink &#187; coding</title>
	<atom:link href="https://codethink.no-ip.org/tags/coding/feed" rel="self" type="application/rss+xml" />
	<link>https://codethink.no-ip.org</link>
	<description>A blog about coding, life, and other arbitrary topics</description>
	<lastBuildDate>Sun, 15 Mar 2026 21:30:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.29</generator>
	<item>
		<title>Matchbook &#8211; Multi-platform Realtime Gaming</title>
		<link>https://codethink.no-ip.org/archives/1046</link>
		<comments>https://codethink.no-ip.org/archives/1046#comments</comments>
		<pubDate>Sun, 26 Jan 2014 13:56:58 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[objc]]></category>
		<category><![CDATA[open-source]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=1046</guid>
		<description><![CDATA[Have you ever thought that it would be cool if you could build a cross-platform or multi-platform game and connect from one platform to another without having to do all the heavy lifting with respect to matchmaking, communications, and related &#8230; <a href="https://codethink.no-ip.org/archives/1046">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Have you ever thought that it would be cool if you could build a cross-platform or multi-platform game and connect from one platform to another without having to do all the heavy lifting with respect to matchmaking, communications, and related tasks yourself?  Well now you can, thanks to <a href="https://github.com/adam-roth/matchbook" target="_blank">Matchbook</a>.</p>
<div id="attachment_1049" style="width: 650px" class="wp-caption aligncenter"><a href="http://codethink.no-ip.org/wordpress/wp-content/uploads/2014/01/running_small.jpg" rel="lightbox[1046]"><img src="http://codethink.no-ip.org/wordpress/wp-content/uploads/2014/01/running-1200x721.jpg" alt="Matchbook Example &quot;Game&quot;" title="Matchbook Example &quot;Game&quot;" width="640" height="384" class="size-large wp-image-1049" /></a><p class="wp-caption-text">Matchbook Example &quot;Game&quot;, 2x iOS and 2x Android clients</p></div>
<p>Matchbook is a lightweight and platform-agnostic matchmaking solution, intended for use in mobile applications (think games that require near-real-time, relatively-low-latency, persistent communications between two or more client devices).</p>
<p>At its core is a server component, which provides a JSON-based webservice allowing clients to find, create, and join matches. The server also acts as a proxy/relay when necessary, allowing client devices to tunnel through any firewalls that might exist between them.</p>
<p>In addition to the server component, Matchbook includes prebuilt SDK&#8217;s for both Java and Objective-C. These SDK&#8217;s are intended to support the development of native applications that make use of the Matchbook webservice on Android and iOS devices, respectively.</p>
<p>I could go on at length, but it&#8217;s simpler to just link to the project on Github (Matchbook is open-source, and permissively licensed, naturally):</p>
<p><a href="https://github.com/adam-roth/matchbook" target="_blank">https://github.com/adam-roth/matchbook</a></p>
<p>Note that Google is currently building comparable functionality into Google Play, although their realtime communications API is currently only available on Android (iOS support is under development).  </p>
<p>And although Apple already has realtime and turn-based gaming API&#8217;s for iOS, they natually have no intention of inviting Android devices to the party.  Ever.</p>
<p>So let the record show that Matchbook got there first.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/1046/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NSObject+SimpleJson</title>
		<link>https://codethink.no-ip.org/archives/924</link>
		<comments>https://codethink.no-ip.org/archives/924#comments</comments>
		<pubDate>Wed, 08 Jan 2014 07:37:39 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[objc]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=924</guid>
		<description><![CDATA[Certainly the subject of JSON processing on iOS is fairly old-hat at this point. After all, Apple has provided native support for JSON serialization and parsing since the release of iOS 5. So why bring it up now? Personally I&#8217;ve &#8230; <a href="https://codethink.no-ip.org/archives/924">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Certainly the subject of JSON processing on iOS is fairly old-hat at this point.  After all, Apple has provided native support for JSON serialization and parsing since the release of iOS 5.  So why bring it up now?  </p>
<p>Personally I&#8217;ve never been entirely happy with the implementation provided by Apple, and in particular their decision to build their API around <i>NSData</i> instead of <i>NSString</i>.  Granted there&#8217;s probably a reason why Apple chose to go that route, and also a reason why they didn&#8217;t bother to provide convenience methods that allow people to work with whichever type they prefer.  But as far as I&#8217;m concerned, JSON is a textual/non-binary data format, so therefore the natural iOS data structure to use for outputting and inputting JSON data is an <i>NSString</i>.  Using <i>NSData</i> instead is counter-intuitive, and clunky as a result.</p>
<p>So because of that clunkiness, I&#8217;ve stuck with the tried and true <a href="http://superloopy.io/json-framework/?utm_source=ipadsummary&#038;utm_medium=twitter">SBJson</a> library, even though the author of that library himself recommends just using Apple&#8217;s implementation.  This preference is largely based around the very helpful (and also very deprecated) &#8216;<i>NSObject+SBJson</i>&#8216; category that is included in the library.  This category imbues objects with a couple of very convenient methods:</p>
<pre class="brush: cpp; title: ; notranslate">- (NSString*)JSONRepresentation;
- (id)JSONValue;</pre>
<p>These methods can be used to turn an appropriate object (i.e. an <i>NSArray</i> or an <i>NSDictionary</i>) into a JSON string, and to turn a JSON string back into a proper object, respectively.  No parameters, no options, no boxing to or unboxing from <i>NSData</i>; just a simple API that is basically just &#8216;<i>[thing turnIntoJson];</i>&#8216; and &#8216;<i>[json turnBackIntoThing];</i>&#8216;.  It doesn&#8217;t get much more convenient than that.  </p>
<p>And that was all well and good, until I wanted to build a <a href="https://github.com/kstenerud/iOS-Universal-Framework">framework</a> which internally used SBJson, and then use that framework within a project that also needs to make its own use of SBJson.  Linker hell was the result.  And long story short, I decided that it would be faster to build a shim around Apple&#8217;s JSON API to preserve the convenience I&#8217;m after than it would be to appease the linker gods.  </p>
<p>So in case anyone else has been avoiding Apple&#8217;s JSON implementation because it&#8217;s too clunky to work with (or too painful to migrate away from SBJson), here&#8217;s my 5-minute shim:</p>
<p><b>NSObject+SimpleJson.h</b></p>
<pre class="brush: cpp; title: ; notranslate">#import &lt;Foundation/Foundation.h&gt;

@interface NSObject (SimpleJson)

- (NSString *)JSONRepresentation;  //turns an object into a JSON string
- (id)JSONValue;                           //turns a JSON string back into an object

@end</pre>
<p><b>NSObject+SimpleJson.m</b></p>
<pre class="brush: cpp; title: ; notranslate">#import &quot;NSObject+SimpleJson.h&quot;

@implementation NSObject (SimpleJson)

- (NSString*)JSONRepresentation {
    //write ourself to a JSON string; only works if we're a type that 'NSJSONSerialization' supports
    NSError* error = nil;
    NSData* tempData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&amp;error];
    if (error) {
        return nil;
    }
    
    return [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
}


- (id) JSONValue {
    //converts from a string back into a proper object; only works if we're an NSString or NSData instance
    if (! [self isKindOfClass:[NSString class]] &amp;&amp; ! [self isKindOfClass:[NSData class]]) {
        return nil;
    }
    
    NSData* jsonData = nil;
    if ([self isKindOfClass:[NSData class]]) {
        jsonData = (NSData*)self;
    }
    else {
        //we must be an NSString
        jsonData = [((NSString*)self) dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    return [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
}

@end</pre>
<p>If you have code that uses SBJson&#8217;s &#8216;<i>NSObject+SBJson</i>&#8216; category, the above category should be drop-in compatible.  And just as importantly (in my case) does not invoke linker hell when used as part of an iOS framework.</p>
<p>Note that the above code assumes you are using ARC.  If not, you&#8217;ll want to add an &#8216;<i>autorelease</i>&#8216; call in there.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/924/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[JavaScript] Finding Equidistant Lat/Long Coordinates</title>
		<link>https://codethink.no-ip.org/archives/746</link>
		<comments>https://codethink.no-ip.org/archives/746#comments</comments>
		<pubDate>Sat, 03 Dec 2011 08:17:52 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[location]]></category>
		<category><![CDATA[maps]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=746</guid>
		<description><![CDATA[Here&#8217;s a quick one that was inspired by a StackOverflow question and built using the references posted here. It allows you to compute the position of an arbitrary number of points (expressed as latitude/longitude pairs) equidistant from a given centerpoint &#8230; <a href="https://codethink.no-ip.org/archives/746">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a quick one that was inspired by a <a href="http://stackoverflow.com/questions/6789992/need-to-find-lats-long-of-a-location-which-is-about-50km-away-from-a-location" target="_blank">StackOverflow question</a> and built using the references posted <a href="http://www.movable-type.co.uk/scripts/latlong.html" target="_blank">here</a>.  It allows you to compute the position of an arbitrary number of points (expressed as latitude/longitude pairs) equidistant from a given centerpoint (using a given radius/distance, of course) on the surface of the Earth.  The crux of the code goes like so:</p>
<pre class="brush: jscript; title: ; notranslate">window.pointsAround = function(centerLat, centerLng, radius, numInterpolations) {
    var result = [];

    //do annoying trig maths to work out the delta in latitude between our start and end points
    var targetD = radius;          //km
    var fractionalDistance = (targetD / radiusOfEarth) / 2;
    var sqrtA = Math.sin(fractionalDistance);
    var a = sqrtA * sqrtA;
    var sinHalfDLat = Math.sqrt(a);
    var dLat = Math.asin(sinHalfDLat) * 2;
    var dLatDegrees = degrees(dLat);
    
    var minLat = centerLat - dLatDegrees;              //furthest valid latitude above the origin
    var maxLat = centerLat + dLatDegrees;            //furthest valid latitude below the origin
    
    var centerLatRadians = radians(centerLat); 
    
    //topmost and bottommost points in the circle
    result.push({lat: minLat, lng: centerLng});
    result.push({lat: maxLat, lng: centerLng});
    
    //step from minLat to maxLat, interpolating coordinates that lie upon the circle
    numInterpolations = numInterpolations ? numInterpolations : 360;
    var step = (maxLat - minLat) / (numInterpolations / 2.0);
    for (var count = 0; count &lt; (numInterpolations / 2) - 1; count++) {
        minLat += step;
        var minLatRadians = radians(minLat);
        dLat = radians(centerLat - minLat);
        
        //more annoying trig to work out the delta in longitude for our interpolated coordinate
        var dLon = 2 * Math.asin(Math.sqrt((a - (Math.sin(dLat/2) * Math.sin(dLat/2))) / (Math.cos(minLatRadians) * Math.cos(centerLatRadians))));
        var dLonDegrees = degrees(dLon);
        
        var newLng = centerLng + dLonDegrees;
        var deltaLng = newLng - centerLng;
        result.push({lat: minLat, lng: newLng});
        result.push({lat: minLat, lng: centerLng - deltaLng});
    }
    
    return result;
};</pre>
<p>This code works out the northernmost and southernmost points that are the specified distance away from the given centerpoint.  It then steps between the minimum and maximum latitude of these two points, interpolating the appropriate longitudinal value(s) to satisfy the equidistant constraint.  The total number of coordinates returned can be controlled using the optional &#8216;<em>numInterpolations</em>&#8216; parameter.  When not specified a total of 360 points will be returned by default, because that is a nice, round number.</p>
<p>If you use something like the following code to plot some points on a map:</p>
<pre class="brush: jscript; title: ; notranslate">window.map = new GMap2(document.getElementById(&quot;mapDiv&quot;));
    var centerPoint = new GLatLng(37.4419, -122.1419);
    map.setCenter(centerPoint, 8);
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GMapTypeControl());
    
    var marker = new GMarker(centerPoint);
    var markerText = &quot;Center @ 37.4419, -122.1419&quot;;
    GEvent.addListener(marker, &quot;click&quot;, markerClickHandler(marker, markerText));
    map.addOverlay(marker);
    
    var points = pointsAround(37.4419, -122.1419, 50);
    for (var index = 0; index &lt; points.length; index++) {
        var point = points[index];
        var latlng = new GLatLng(point.lat, point.lng);
        marker = new GMarker(latlng);
        markerText = &quot;Marker @ &quot; + point.lat + &quot;, &quot; + point.lng;
        GEvent.addListener(marker, &quot;click&quot;, markerClickHandler(marker, markerText));
        map.addOverlay(marker);
    }</pre>
<p>&#8230;you will get a nice circle of points around the hard-coded centerpoint.  You can see a working example of this here:  <a href="http://jsfiddle.net/HmchC/27/" target="_blank">http://jsfiddle.net/HmchC/27/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/746/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[JavaScript] Creating an Animated Hurricane Tracker</title>
		<link>https://codethink.no-ip.org/archives/773</link>
		<comments>https://codethink.no-ip.org/archives/773#comments</comments>
		<pubDate>Sat, 10 Sep 2011 15:09:21 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[hack]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=773</guid>
		<description><![CDATA[Here&#8217;s a fun little diversion I came up with when the news was all abuzz with information about Hurricane Irene. Now I use Wikipedia almost exclusively for keeping track of this sort of thing as I find that it consistently &#8230; <a href="https://codethink.no-ip.org/archives/773">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a fun little diversion I came up with when the news was all abuzz with information about <a href="http://en.wikipedia.org/wiki/Hurricane_Irene_(2011)" target="_blank">Hurricane Irene</a>.  Now I use Wikipedia almost exclusively for keeping track of this sort of thing as I find that it consistently provides the most up to date data in the cleanest and most easy to digest format, but I also noticed a large volume of comments on other news sites complaining about the accuracy of hurricane forecasting.  And this got me to wondering, just how accurate are the historical forecasts when overlaid with the actual storm track?</p>
<p>Well Wikipedia doesn&#8217;t provide this information directly, but interestingly enough Wikipedia does in fact keep all the <a href="http://en.wikipedia.org/w/index.php?title=File:09L_2011_5day.gif&#038;limit=500#filehistory" target="_blank">historical data</a> necessary to answer this question.  Thanks to Chrome&#8217;s awesome JavaScript console (and the fact that Wikipedia uses jQuery on all of its pages) it is a very simple matter to extract this historical information in a format that is easy to work with later.  The following code will do the trick:</p>
<pre class="brush: jscript; title: ; notranslate">var result = []; 
jQuery.each($(&quot;.filehistory a[href$=5day.gif]&quot;), function(){
    result.push(this.href)
}); 
result;</pre>
<p>This simply constructs an array containing the URL&#8217;s of every historical forecast/storm track graphic (ordered by date from newest to oldest) and outputs it to the console.  We can then copy/paste the console output to wherever we like, such as <a href="http://jsfiddle.net" target="_blank">jsFiddle</a> for instance.  Combine this with some basic HTML structure:</p>
<pre class="brush: xml; title: ; notranslate">&lt;div class=&quot;title&quot;&gt;
    Hurricane Irene Animated Forecast Map
&lt;/div&gt;
&lt;img id=&quot;display&quot; src=&quot;http://fcf.teambeachbody.com/fcf/images/spinner5.gif&quot; /&gt;
&lt;div id=&quot;status&quot;&gt;
    (&lt;span id=&quot;numLoaded&quot;&gt;&lt;/span&gt; of &lt;span id=&quot;total&quot;&gt;&lt;/span&gt; frames loaded)
&lt;/div&gt;</pre>
<p>&#8230;and some simple JavaScript to handle the actual rendering:</p>
<pre class="brush: jscript; title: ; notranslate">document.getElementById(&quot;numLoaded&quot;).innerHTML = &quot;0&quot;;
document.getElementById(&quot;total&quot;).innerHTML = data.length;

//preload all the images so that they are cached for the animation
window.imagesLoaded = 0;
for (var index = data.length - 1; index &gt;= 0; index--) {
    var node = document.createElement(&quot;img&quot;);
    node.style.display = &quot;none&quot;;
    document.body.appendChild(node);
    $(node).bind('load', function() {  
        window.imagesLoaded++;  
    });
    $(node).attr('src', data[index]);
    //node.src = data[index];
}

//run the animation
window.currentImage = data.length - 1;
window.updateAnimation = function() {
    if (window.imagesLoaded &lt; data.length) {
        //keep waiting
        document.getElementById(&quot;numLoaded&quot;).innerHTML = window.imagesLoaded;
        return;
    }
    $(&quot;#status&quot;).hide();
    document.getElementById(&quot;display&quot;).src = data[currentImage];
    currentImage--;
    if (currentImage &lt; 0) {
        currentImage = data.length - 1;
    }
};

setInterval(updateAnimation, 200);</pre>
<p>&#8230;and you get an animated map of the entire forecast history, including the actual storm track.  The result looks something like this:</p>
<p><iframe src="http://fiddle.jshell.net/TqmVg/6/show/" width="425" height="380" frameBorder="0"><br />
</iframe></p>
<p>Not too bad for a few dozen lines of code and about 30 minutes worth of effort.  You can also access a full-scale, editable version of this animated storm history <a href="http://jsfiddle.net/TqmVg/5/" target="_blank">here</a>.</p>
<p>So what does this say about the accuracy of the hurricane forecasting for Irene?  Personally I think it shows that the forecasts are pretty damn accurate.  In fact, if you focus just on the solid white portion of the predicted storm track it appears that the storm never deviates from its forecast path.  It&#8217;s only when looking at the dashed white portion of the forecast that any significant deviation can be noted.  And the dashed white portion indicates forecasts that are more than 72 hours in the future.  </p>
<p>Of course we should always be working to improve our ability to predict and forecast these things, but I have to think that being able to accurately predict a storm&#8217;s movement for up to 72 hours into the future is adequate for most purposes.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/773/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[Java] Override HTTP Request Parameters</title>
		<link>https://codethink.no-ip.org/archives/634</link>
		<comments>https://codethink.no-ip.org/archives/634#comments</comments>
		<pubDate>Sun, 15 May 2011 07:25:39 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[hack]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=634</guid>
		<description><![CDATA[Often in a Java web-application I come across cases where it would be useful to directly override or modify one or more HTTP request parameters. To be clear, by &#8220;request parameter&#8221; I am referring to the value that is returned &#8230; <a href="https://codethink.no-ip.org/archives/634">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Often in a Java web-application I come across cases where it would be useful to directly override or modify one or more HTTP request parameters.  To be clear, by &#8220;request parameter&#8221; I am referring to the value that is returned by the <a href="http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletRequest.html" target="_blank">ServletRequest</a>&#8216;s &#8216;<em>getParameter()</em>&#8216; method.  For whatever reason the architects of the Servlet spec decided that direct modification of request parameters was not to be supported, despite the number of use-cases that can benefit from such a feature.</p>
<p>For example, say that you have a <a href="http://download.oracle.com/javaee/5/api/javax/servlet/Filter.html" target="_blank">Filter</a> that you are using to sanitize input parameters and guard against things like <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" target="_blank">XSS attacks</a> by ensuring that obviously invalid values like &#8220;&lt;script&gt;alert(&#8216;hacked!&#8217;);&lt;/script&gt;&#8221; are filtered out.  Wouldn&#8217;t it be great if you could implement your Filter such that when it finds one or more forbidden values it flags the request as potentially malicious (using a request attribute), removes any parameters that contain potentially unsafe data, and relocates the potentially unsafe data to a predetermined quarantine area (also accessible via a request attribute)?  This would protect your webapp code from ever receiving a malicious parameter, while still allowing parts of the code that might permit seemingly malicious parameters (for instance, there is no reason to prevent a user from registering with a password of &#8220;&lt;script&gt;alert(&#8216;hacked!&#8217;);&lt;/script&gt;&#8221; if that is what they want to use, particularly if you are hashing user passwords like you should be) to still access them if desired by going through the quarantine area.  </p>
<p>Of course, two-thirds of the functionality described above can be implemented without being able to override request parameters.  With the standard API you can certainly check for potentially malicious parameters, set an attribute if you find any, and copy their values into a quarantine area.  But what you cannot do is remove the parameters from the request, so any application code that directly accesses a request parameter value may still be at risk, particularly if its author forgets to check to see if the request has been flagged as suspect.  The real beauty of being able to override parameter values is that you can do things like completely prevent a malicious parameter from ever being visible to your application code unless your application code goes out of its way to look for it (and if you do that, and you do it incorrectly, then that&#8217;s your own fault).  </p>
<p>Anyways, the code to enable this kind of functionality is a fairly straightforward (if tedious) exercise in writing an HttpServletRequest wrapper and then overriding a few choice methods (and adding a couple new ones):  </p>
<pre class="brush: java; title: ; notranslate">import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class OverridableHttpRequest implements HttpServletRequest {
        
	private HttpServletRequest wrappedRequest;
	private Map&lt;String, String&gt; newParams;
	private Set&lt;String&gt; removedParams;

	public OverridableHttpRequest(HttpServletRequest requestToWrap) {
		this.wrappedRequest = requestToWrap;
		this.newParams = new HashMap&lt;String, String&gt;();
		this.removedParams = new HashSet&lt;String&gt;();
	}

	// these things we add so that params can be overridden
	public void setParameter(String name, String value) {
		this.removedParams.remove(name);
		this.newParams.put(name, value);
	}

	public void removeParameter(String name) {
		this.newParams.remove(name);
		this.removedParams.add(name);
	}

	// these things we need to override so that the correct state is exposed through the standard API
	@SuppressWarnings(&quot;rawtypes&quot;)
	@Override
	public Enumeration getParameterNames() {
		Set&lt;String&gt; result = new HashSet&lt;String&gt;();
		Enumeration requestParams = this.wrappedRequest.getParameterNames();
		while (requestParams.hasMoreElements()) {
			Object param = requestParams.nextElement();
			if (!removedParams.contains(param)) {
				result.add((String) param);
			}
		}
		result.addAll(newParams.keySet());

		return Collections.enumeration(result);
	}

	@Override
	public String[] getParameterValues(String arg0) {
		//NOTE:  not strictly to spec
		String[] result = new String[1];
		result[0] = this.getParameter(arg0);

		return result;
	}

	@Override
	public String getParameter(String arg0) {
		if (removedParams.contains(arg0)) {
			return null;
		}
		if (newParams.containsKey(arg0)) {
			return newParams.get(arg0);
		}
		return this.wrappedRequest.getParameter(arg0);
	}

	@SuppressWarnings(&quot;rawtypes&quot;)
	@Override
	public Map getParameterMap() {
		Map&lt;String, String[]&gt; result = new HashMap&lt;String, String[]&gt;();
		for (Object key : this.wrappedRequest.getParameterMap().keySet()) {
			result.put((String)key, (String[])this.wrappedRequest.getParameterMap().get(key));
		}
		for (String key : this.newParams.keySet()) {
			result.put(key, new String[] {this.newParams.get(key)});
		}
		for (String key : this.removedParams) {
			result.remove(key);
		}
		
		return result;
	}

	// these things we should probably override but don't right now
	@Override
	public String getRequestURI() {
		// FIXME: should return a modified URI based upon current state
		return this.wrappedRequest.getRequestURI();
	}

	@Override
	public StringBuffer getRequestURL() {
		// FIXME: should return a modified URL based upon current state
		return this.wrappedRequest.getRequestURL();
	}

	@Override
	public String getQueryString() {
		// FIXME: should return a modified String based upon current state
		return this.wrappedRequest.getQueryString();
	}

	// everything else just passes through
	@Override
	public Object getAttribute(String arg0) {
		return this.wrappedRequest.getAttribute(arg0);
	}

	@SuppressWarnings(&quot;rawtypes&quot;)
	@Override
	public Enumeration getAttributeNames() {
		return this.wrappedRequest.getAttributeNames();
	}

	@Override
	public String getCharacterEncoding() {
		return this.wrappedRequest.getCharacterEncoding();
	}

	@Override
	public int getContentLength() {
		return this.wrappedRequest.getContentLength();
	}

	@Override
	public String getContentType() {
		return this.wrappedRequest.getContentType();
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		return this.wrappedRequest.getInputStream();
	}

	@Override
	public String getLocalAddr() {
		return this.wrappedRequest.getLocalAddr();
	}

	@Override
	public String getLocalName() {
		return this.wrappedRequest.getLocalName();
	}

	@Override
	public int getLocalPort() {
		return this.wrappedRequest.getLocalPort();
	}

	@Override
	public Locale getLocale() {
		return this.wrappedRequest.getLocale();
	}

	@SuppressWarnings(&quot;rawtypes&quot;)
	@Override
	public Enumeration getLocales() {
		return this.wrappedRequest.getLocales();
	}

	@Override
	public String getProtocol() {
		return this.wrappedRequest.getProtocol();
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return this.wrappedRequest.getReader();
	}

	@SuppressWarnings(&quot;deprecation&quot;)
	@Override
	public String getRealPath(String arg0) {
		return this.wrappedRequest.getRealPath(arg0);
	}

	@Override
	public String getRemoteAddr() {
		return this.wrappedRequest.getRemoteAddr();
	}

	@Override
	public String getRemoteHost() {
		return this.wrappedRequest.getRemoteHost();
	}

	@Override
	public int getRemotePort() {
		return this.wrappedRequest.getRemotePort();
	}

	@Override
	public RequestDispatcher getRequestDispatcher(String arg0) {
		return this.wrappedRequest.getRequestDispatcher(arg0);
	}

	@Override
	public String getScheme() {
		return this.wrappedRequest.getScheme();
	}

	@Override
	public String getServerName() {
		return this.wrappedRequest.getServerName();
	}

	@Override
	public int getServerPort() {
		return this.wrappedRequest.getServerPort();
	}

	@Override
	public boolean isSecure() {
		return this.wrappedRequest.isSecure();
	}

	@Override
	public void removeAttribute(String arg0) {
		this.wrappedRequest.removeAttribute(arg0);
	}

	@Override
	public void setAttribute(String arg0, Object arg1) {
		this.wrappedRequest.setAttribute(arg0, arg1);
	}

	@Override
	public void setCharacterEncoding(String arg0)
			throws UnsupportedEncodingException {
		this.wrappedRequest.setCharacterEncoding(arg0);
	}

	@Override
	public String getAuthType() {
		return this.wrappedRequest.getAuthType();
	}

	@Override
	public String getContextPath() {
		return this.wrappedRequest.getContextPath();
	}

	@Override
	public Cookie[] getCookies() {
		return this.wrappedRequest.getCookies();
	}

	@Override
	public long getDateHeader(String arg0) {
		return this.wrappedRequest.getDateHeader(arg0);
	}

	@Override
	public String getHeader(String arg0) {
		return this.wrappedRequest.getHeader(arg0);
	}

	@SuppressWarnings(&quot;rawtypes&quot;)
	@Override
	public Enumeration getHeaderNames() {
		return this.wrappedRequest.getHeaderNames();
	}

	@SuppressWarnings(&quot;rawtypes&quot;)
	@Override
	public Enumeration getHeaders(String arg0) {
		return this.wrappedRequest.getHeaders(arg0);
	}

	@Override
	public int getIntHeader(String arg0) {
		return this.wrappedRequest.getIntHeader(arg0);
	}

	@Override
	public String getMethod() {
		return this.wrappedRequest.getMethod();
	}

	@Override
	public String getPathInfo() {
		return this.wrappedRequest.getPathInfo();
	}

	@Override
	public String getPathTranslated() {
		return this.wrappedRequest.getPathTranslated();
	}

	@Override
	public String getRemoteUser() {
		return this.wrappedRequest.getRemoteUser();
	}

	@Override
	public String getRequestedSessionId() {
		return this.wrappedRequest.getRequestedSessionId();
	}

	@Override
	public String getServletPath() {
		return this.wrappedRequest.getServletPath();
	}

	@Override
	public HttpSession getSession() {
		return this.wrappedRequest.getSession();
	}

	@Override
	public HttpSession getSession(boolean arg0) {
		return this.wrappedRequest.getSession(arg0);
	}

	@Override
	public Principal getUserPrincipal() {
		return this.wrappedRequest.getUserPrincipal();
	}

	@Override
	public boolean isRequestedSessionIdFromCookie() {
		return this.wrappedRequest.isRequestedSessionIdFromCookie();
	}

	@Override
	public boolean isRequestedSessionIdFromURL() {
		return this.wrappedRequest.isRequestedSessionIdFromURL();
	}

	@SuppressWarnings(&quot;deprecation&quot;)
	@Override
	public boolean isRequestedSessionIdFromUrl() {
		return this.wrappedRequest.isRequestedSessionIdFromUrl();
	}

	@Override
	public boolean isRequestedSessionIdValid() {
		return this.wrappedRequest.isRequestedSessionIdValid();
	}

	@Override
	public boolean isUserInRole(String arg0) {
		return this.wrappedRequest.isUserInRole(arg0);
	}

}</pre>
<p>So the new methods being added here are &#8216;<em>removeParameter(String name)</em>&#8216; and &#8216;<em>setParameter(String name)</em>&#8216;, which do pretty much what their name implies.  If you are familiar with the standard &#8216;<em>removeAttribute(String name)</em>&#8216; and &#8216;<em>setAttribute(String name)</em>&#8216; methods, then you should feel right at home with these new additions.  They simply let you manipulate request parameters in a way that&#8217;s identical to how you can already manipulate request attributes.  </p>
<p>One minor deviation from the Servlet specification that is worth noting is that I have overridden &#8216;<em>getParameterValues(String name)</em>&#8216; such that it only returns the first value associated with a given parameter.  This means that if for some reason your webapp uses URL&#8217;s like &#8220;http://mysite.com/api?user=bob&#038;user=jane&#038;user=paul&#8221; then you will only see &#8220;bob&#8221; as a value for the &#8216;user&#8217; parameter.  In practice I have not ever come across a web application that intentionally relied on a single parameter name having multiple values associated with it, and if you are designing your web application in such a way then you should probably just stop and pick a less confusing pattern.  I see no value in a feature that allows a single parameter to have multiple values that you only get to see if you use a different API method to get them (&#8216;<em>getParameterValues</em>&#8216; instead of &#8216;<em>getParameter</em>&#8216;), and so I have removed this feature from the implementation.  If someone can come up with a solid justification for having such a feature, I will add it back in.</p>
<p>Also, left as an exercise is overriding &#8216;<em>getRequestURI()</em>&#8216;, &#8216;<em>getRequestURL()</em>&#8216;, and &#8216;<em>getQueryString()</em>&#8216; to return the correct values based upon the modified request state.  It&#8217;s fairly rare to have application code that depends upon the values of these calls, so in most cases you will not need to do this.</p>
<p>In any case, to make use of the OverridableHttpRequest class, you can do the following:</p>
<pre class="brush: java; title: ; notranslate">public class ExampleFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//do initialization things here
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest httpReq = (HttpServletRequest) response;
		OverridableHttpRequest newRequest = new OverridableHttpRequest(httpReq);
     
		//do work and modify the request as desired
		newRequest.removeParameter(&quot;someBadXssParam&quot;);

		//pass the modified request on to the webapp, anyone downstream will see 
		//the modified state with no 'someBadXssParam' in it
		filterChain.doFilter(newRequest, response);
	}

	@Override
	public void destroy() {
		//do shutdown things here
	}
}</pre>
<p>Simple, but powerful.  I just wish the Servlet spec included this kind of functionality out of the box so that it wouldn&#8217;t be necessary to implement a complete HttpServletRequest wrapper just to add a couple of basic mutator methods.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/634/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>[Objective-C + Cocoa] Runtime Performance Profiling</title>
		<link>https://codethink.no-ip.org/archives/563</link>
		<comments>https://codethink.no-ip.org/archives/563#comments</comments>
		<pubDate>Fri, 01 Apr 2011 07:25:47 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objc]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=563</guid>
		<description><![CDATA[The iPhone SDK and XCode provide some very useful tools for application profiling, particularly with respect to tracking memory consumption and pinpointing memory leaks and other similar issues, but one thing which I have found lacking in the default toolset &#8230; <a href="https://codethink.no-ip.org/archives/563">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The iPhone SDK and XCode provide some very useful tools for application profiling, particularly with respect to tracking memory consumption and pinpointing memory leaks and other similar issues, but one thing which I have found lacking in the default toolset is the ability to track the execution time of this-or-that specific bit of code, be it a function call, a loop within a function, or some arbitrary series of API calls made in quick succession.  </p>
<p>Typically I would deal with such cases by adding some one-off code around the section that I was interested in profiling to measure and log its execution time.  But this approach quickly becomes unwieldy when there are several different places that you are interested in profiling, and particularly when it comes time to track down and remove all of these bits of code so that they stop spamming the log with timing data that is no longer needed.  </p>
<p>In any case, here is my solution to this minor annoyance, patterned after a similar utility I implemented in ActionScript some time ago:</p>
<pre class="brush: cpp; title: ; notranslate">//PerformanceTimer.h
#import &lt;Foundation/Foundation.h&gt;


@interface PerformanceTimer : NSObject {
    NSMutableArray* startTimes;
    NSMutableArray* names;
}

+ (void) startTimerWithName: (NSString*) name;
+ (clock_t) stopLastTimer;
+ (clock_t) stopTimerWithName: (NSString*) name;

@end


//PerformanceTimer.m
#import &quot;PerformanceTimer.h&quot;

static PerformanceTimer* timerInstance = nil;

@implementation PerformanceTimer

- (id) init {
    self = [super init];
    if (self) {
        startTimes = [[NSMutableArray alloc] initWithCapacity:16];
        names = [[NSMutableArray alloc] initWithCapacity:16];
    }
    
    return self;
}

- (void) dealloc {
    [startTimes release];
    startTimes = nil;
    
    [names release];
    names = nil;
    
    [super dealloc];
}

- (void) startTimer: (NSString*) name {
    @synchronized(startTimes) {
        clock_t start = clock();
        NSNumber* startNum = [NSNumber numberWithUnsignedLong:start];
        [startTimes addObject:startNum];
        [names addObject:name];
    }
}

- (clock_t) stopTimerNamed: (NSString*) name {
    @synchronized(startTimes) {
        int index = 0;
        for (NSString* timerName in names) {
            if ([timerName isEqualToString:name]) {
                break;
            }
            index++;
        }
        if (index &gt;= [names count]) {
            //couldn't find it
            return 0;
        }
        clock_t start = [[startTimes objectAtIndex:index] unsignedLongValue];
        clock_t end = (clock() - start) / (CLOCKS_PER_SEC / 1000.0);
        
        #ifdef DEBUG
        //if debugging, always print, otherwise let the caller decide what to do
        NSLog(@&quot;PerformanceTimer:  Total execution time for task named '%@':  %lu ms&quot;, name, end);
        #endif
        
        [startTimes removeObjectAtIndex:index];
        [names removeObjectAtIndex:index];
        
        return end;
    }
}

- (clock_t) stopTimer {
    @synchronized(startTimes) {
        if ([names count] &lt; 1) {
            //no timer is running
            return 0;
        }
        
        NSString* name = [names objectAtIndex:[names count] - 1];
        return [self stopTimerNamed:name];
    }
}

+ (void) startTimerWithName: (NSString*) name {
    if (! timerInstance) {
        timerInstance = [[PerformanceTimer alloc] init];
    }
    [timerInstance startTimer:name];
}

+ (clock_t) stopLastTimer {
    if (! timerInstance) {
        timerInstance = [[PerformanceTimer alloc] init];
    }
    return [timerInstance stopTimer];
}

+ (clock_t) stopTimerWithName: (NSString*) name {
    if (! timerInstance) {
        timerInstance = [[PerformanceTimer alloc] init];
    }
    return [timerInstance stopTimerNamed:name];
}

@end</pre>
<p>This adds a static utility class that can be used to spawn multiple independent named timers.  It is used like:</p>
<pre class="brush: cpp; title: ; notranslate">[PerformanceTimer startTimer:@&quot;myTimerName&quot;];
//do some things that you want to time
clock_t elapsedTimeMillis = [PerformanceTimer stopTimerWithName: @&quot;myTimerName&quot;];
//print or log the elapsed time</pre>
<p>The default behavior of this class when run in debug mode is to print out the elapsed time automatically when &#8216;stopTimer&#8217; is called, so it&#8217;s not generally necessary to capture or inspect the value returned from &#8216;stopTimer&#8217; unless you are either running in release mode or if you want to do something more involved than simply logging the timing data to the console.</p>
<p>Note that although a &#8216;stopLastTimer&#8217; method is provided for convenience, its use is generally not recommended unless you are absolutely sure that nobody else has started a timer somewhere else in the code.  Otherwise you can end up inadvertently stopping the wrong timer.  Inside of a small, simple, single-threaded application there is little to worry about.  But for any more complex/multi-threaded projects it is much safer to always specify a timer by name.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/563/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[Objective-C + Cocoa] Screen Capture, Multiplexing, and More</title>
		<link>https://codethink.no-ip.org/archives/541</link>
		<comments>https://codethink.no-ip.org/archives/541#comments</comments>
		<pubDate>Mon, 28 Mar 2011 11:45:02 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[objc]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=541</guid>
		<description><![CDATA[It&#8217;s been a bit quiet on the coding-front lately, so I thought I&#8217;d share a small handful of various utilities that I&#8217;ve developed over the past few weeks. None of them are particularly revolutionary, but they can certainly prove useful &#8230; <a href="https://codethink.no-ip.org/archives/541">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s been a bit quiet on the coding-front lately, so I thought I&#8217;d share a small handful of various utilities that I&#8217;ve developed over the past few weeks.  None of them are particularly revolutionary, but they can certainly prove useful in the right situations.  Anyways, in no particular order, I give you:</p>
<p><strong>ScreenCaptureView</strong></p>
<p>This bit of code allows you to easily capture the contents of any arbitrary UIView:</p>
<pre class="brush: cpp; title: ; notranslate">//  ScreenCaptureView.h
#import &lt;UIKit/UIKit.h&gt;

@interface ScreenCaptureView : UIView {
}

@property(retain) UIImage* currentScreen;
@property(assign) float frameRate;

@end


//  ScreenCaptureView.m
#import &quot;ScreenCaptureView.h&quot;
#import &lt;QuartzCore/QuartzCore.h&gt;

@implementation ScreenCaptureView

@synthesize currentScreen, frameRate;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.contentMode = UIViewContentModeRedraw;
        self.frameRate = 20.0f;//20 frames per seconds
    }
    return self;
}

- (void) drawRect:(CGRect)rect {
    CGContextRef context =  UIGraphicsGetCurrentContext();
    [self.layer renderInContext:context];
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage* background = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);
    self.currentScreen = background;
    
    [self performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:(1.0 / self.frameRate)];   //redraw at the specified framerate
}

- (void)dealloc {
    [super dealloc];
}
@end</pre>
<p>The &#8216;<em>ScreenCaptureView</em>&#8216; class automatically captures its current contents (including any nested subviews) to a UIImage which it exposes through the &#8216;<em>currentScreen</em>&#8216; property.  You can use this functionality to do things like generate screenshots of your application for use in help/tutorial (or promotional) content, and you can even pass the data as frames to an `<em>AVCaptureSession</em>` to create a live video of your app in action.</p>
<p><strong>Update:</strong>  An enhanced version of this class that includes the ability to record video is <a href="http://codethink.no-ip.org/wordpress/archives/673">now available</a>.</p>
<p><strong>MultiplexingDelegate</strong></p>
<p>For those rare cases when you want multiple delegate objects to be notified of a change/event in some object:</p>
<pre class="brush: cpp; title: ; notranslate">//  MultiplexingDelegate.h
#import &lt;Foundation/Foundation.h&gt;

@interface MultiplexingDelegate : NSObject {
    NSMutableArray* delegates;
}

- (void) addDelegate: (id) theDelegate;
- (void) removeDelegate: (id) theDelegate;
- (void) sendSelectorToDelegates: (SEL)selector withObject: (id)param1 andSecondObject: (id)param2
@end

//  MultiplexingDelegate.m
@implementation MultiplexingDelegate
- (id) init {
    if ((self = [super init])) {
        delegates = [[NSMutableArray alloc] initWithCapacity: 16];
    }
}

- (void) dealloc {
    [delegates release];
    [super dealloc]
}

- (void) addDelegate: (id) theDelegate {
    @synchronized(delegates) {
        if (theDelegate &amp;&amp; ! [delegates containsObject: theDelegate]) {
            [delegates addObject: theDelegate];
        }
    }
}

- (void) removeDelegate: (id) theDelegate {
    @synchronized(delegates) {
        if (theDelegate &amp;&amp; [delegates containsObject: theDelegate]) {
            [delegates removeObject: theDelegate];
        }
    }
}

- (void) sendSelectorToDelegates: (SEL)selector withObject: (id)param1 andSecondObject: (id)param2 {
    @synchronized(delegates) {
        for (id theDelegate in delegates) {
            if (param2) {
                [theDelegate performSelector:selector withObject:param1 withObject:param2];
            }
            else if (param1) {
                [theDelegate performSelector:selector withObject:param1];
            }
            else {
                [theDelegate performSelector:selector];
            }
        }
    }
}
@end</pre>
<p>The &#8216;<em>MultiplexingDelegate</em>` class provides a generic starting point for creating delegates that conform to various protocols and support the multiplexing of events to any number of attached listeners.  To use it you just need to create a new subclass of &#8216;<em>MultiplexingDelegate</em>&#8216; that implements whatever protocol you are interested in.  For instance, here is a partial example of a multiplexing UISearchBarDelegate implementation:</p>
<pre class="brush: cpp; title: ; notranslate">//  MultiplexingSearchBarDelegate.h
#import &lt;UIKit/UIKit.h&gt;
#import &quot;MultiplexingDelegate.h&quot;

@interface MultiplexingSearchBarDelegate : MultiplexingDelegate&lt;UISearchBarDelegate&gt; {
}
@end

//  MultiplexingSearchBarDelegate.m
@implementation MultiplexingSearchBarDelegate
//add UISearchBarDelegate methods here, following a pattern like this:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self sendSelectorToDelegates: @selector(searchBar:textDidChange:) withObject: searchBar andSecondObject: searchText];
}

//or alternately/equivalently, a pattern like this:
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    @synchronized(delegates) {
        for (id&lt;UISearchBarDelegate&gt; theDelegate in delegates) {
            [theDelegate searchBar:searchBar shouldChangeTextInRange: range replacementText: text];
        }
    }
}
@end</pre>
<p>To use the &#8216;<em>MultiplexingSearchBarDelegate</em>&#8216; class you would create a single instance and add it as the delegate of your UISearchBar.  Then you just register every other object that you want to receive UISearchBar events with the &#8216;<em>MultiplexingSearchBarDelegate</em>&#8216; (by using the &#8216;<em>addDelegate:</em>&#8216; method), and they will all receive event notifications from the UISearchBar.  Simple, but powerful.</p>
<p><strong>NSString+JavaAPI</strong></p>
<p>There&#8217;s no getting around it, the standard NSString API just kind of sucks.  Wouldn&#8217;t it be great if NSString supported an API that was more like what Java provides through its String class?  Well now it can:</p>
<pre class="brush: cpp; title: ; notranslate">//  NSString+JavaAPI.h
#import &lt;Foundation/Foundation.h&gt;

@interface NSString (NSString_JavaAPI)
- (int) compareTo: (NSString*) comp;
- (int) compareToIgnoreCase: (NSString*) comp;
- (bool) contains: (NSString*) substring;
- (bool) endsWith: (NSString*) substring;
- (bool) startsWith: (NSString*) substring;
- (int) indexOf: (NSString*) substring;
- (int) indexOf:(NSString *)substring startingFrom: (int) index;
- (int) lastIndexOf: (NSString*) substring;
- (int) lastIndexOf:(NSString *)substring startingFrom: (int) index;
- (NSString*) substringFromIndex:(int)from toIndex: (int) to;
- (NSString*) trim;
- (NSArray*) split: (NSString*) token;
- (NSString*) replace: (NSString*) target withString: (NSString*) replacement;
- (NSArray*) split: (NSString*) token limit: (int) maxResults;
@end

//  NSString+JavaAPI.m
#import &quot;NSString+JavaAPI.h&quot;

@implementation NSString (NSString_JavaAPI)
- (int) compareTo: (NSString*) comp {
    NSComparisonResult result = [self compare:comp];
    if (result == NSOrderedSame) {
        return 0;
    }
    return result == NSOrderedAscending ? -1 : 1;
}

- (int) compareToIgnoreCase: (NSString*) comp {
    return [[self lowercaseString] compareTo:[comp lowercaseString]];
}

- (bool) contains: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location != NSNotFound;
}

- (bool) endsWith: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location == [self length] - [substring length];
}

- (bool) startsWith: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location == 0;
}

- (int) indexOf: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location == NSNotFound ? -1 : range.location;
}

- (int) indexOf:(NSString *)substring startingFrom: (int) index {
    NSString* test = [self substringFromIndex:index];
    return [test indexOf:substring];
}

- (int) lastIndexOf: (NSString*) substring {
    if (! [self contains:substring]) {
        return -1;
    }
    int matchIndex = 0;
    NSString* test = self;
    while ([test contains:substring]) {
        if (matchIndex &gt; 0) {
            matchIndex += [substring length];
        }
        matchIndex += [test indexOf:substring];
        test = [test substringFromIndex: [test indexOf:substring] + [substring length]];
    }
    
    return matchIndex;
}

- (int) lastIndexOf:(NSString *)substring startingFrom: (int) index {
    NSString* test = [self substringFromIndex:index];
    return [test lastIndexOf:substring];
}

- (NSString*) substringFromIndex:(int)from toIndex: (int) to {
    NSRange range;
    range.location = from;
    range.length = to - from;
    return [self substringWithRange: range];
}

- (NSString*) trim {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSArray*) split: (NSString*) token {
    return [self split:token limit:0];
}

- (NSArray*) split: (NSString*) token limit: (int) maxResults {
    NSMutableArray* result = [NSMutableArray arrayWithCapacity: 8];
    NSString* buffer = self;
    while ([buffer contains:token]) {
        if (maxResults &gt; 0 &amp;&amp; [result count] == maxResults - 1) {
            break;
        }
        int matchIndex = [buffer indexOf:token];
        NSString* nextPart = [buffer substringFromIndex:0 toIndex:matchIndex];
        buffer = [buffer substringFromIndex:matchIndex + [token length]];
        if (nextPart) {
            [result addObject:nextPart];
        }
    }
    if ([buffer length] &gt; 0) {
        [result addObject:buffer];
    }
    
    return result;
}

- (NSString*) replace: (NSString*) target withString: (NSString*) replacement {
    return [self stringByReplacingOccurrencesOfString:target withString:replacement];
}
@end</pre>
<p>Note that this isn&#8217;t the complete Java String API (and also that `<em>split()</em>` does not support regular-expressions as it does in Java).  It is just a subset consisting of the most useful Java API functions that do not have convenient analogs in the standard NSString API.  Still, it makes a lot of common string manipulations a lot more straightforward than they otherwise would be.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/541/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>[JavaScript + CSS] Fun with Google Maps</title>
		<link>https://codethink.no-ip.org/archives/472</link>
		<comments>https://codethink.no-ip.org/archives/472#comments</comments>
		<pubDate>Fri, 11 Mar 2011 13:06:01 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[hack]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=472</guid>
		<description><![CDATA[Here are a couple of quick Google Maps hacks that I came up with quite awhile ago; several years ago, in fact. While not hugely useful or profound, they do expose some fairly large holes in the Google Maps API. &#8230; <a href="https://codethink.no-ip.org/archives/472">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here are a couple of quick Google Maps hacks that I came up with quite awhile ago; several years ago, in fact.  While not hugely useful or profound, they do expose some fairly large holes in the Google Maps API.  Holes that I would have expected a company like Google to have patched up by now.  </p>
<p>First, let&#8217;s say that for whatever reason you need to remove the &#8220;Powered by Google&#8221; logo and the other copyright and similar boilerplate that normally appears along the bottom of the map.  Why would you want to do this?  Perhaps because you are displaying your map inside of a small area of the page where space is constrained to the point that the logo and other things are adding too much noise.  Or perhaps because you feel (quite justifiably) that Google Maps have become iconic to the point that nobody needs to see a &#8220;Powered by Google&#8221; logo in the corner to know that the map is being powered by Google.  </p>
<p>Whatever your reason for wanting to unclutter the map&#8217;s footer section, the task can be accomplished using a smidgen of CSS:</p>
<pre class="brush: css; title: ; notranslate">		.terms-of-use-link {
		    display: none;
		}

		#myMapContainerId div span {
			display: none;
		}</pre>
<p>&#8230;and a handful of JavaScript:</p>
<pre class="brush: jscript; title: ; notranslate">			//call this after setting up your GMap2 instance
			window.unclutter = function() {
				var executed = false;
				var images = document.getElementsByTagName('img');
				for (var index = 0; index &lt; images.length; index++) {
					var node = images[index];
					if (node.src &amp;&amp; node.src.indexOf(&quot;mapfiles/poweredby.png&quot;) &gt; 0) {
						node.style.display = 'none';
						executed = true;
					}
				}

				if (! executed) {
					setTimeout(window.unclutter, 250);
				}
			};</pre>
<p>It&#8217;s pretty straightforward, really.  The CSS gets rid of the &#8220;Terms of Use&#8221; link, as well as the spans that are used to display copyright text (note that you should replace the &#8216;<em>myMapContainerId</em>&#8216; with whatever your actual map div-id is).  The JavaScript is used to get rid of the &#8220;Powered by Google&#8221; logo, which is added to the map after it loads.  To use this code, you just need to call &#8216;<em>unclutter()</em>&#8216; after setting up your Google Map instance.</p>
<p>Of course, doing this is a blatant violation of the Google Maps Terms of Service.  You know, the terms Google made you agree to when you generated your API key.  Whether or not there is any merit in having Terms of Service mandate things which do nothing whatsoever to benefit end users such as the display of logos and copyright gibberish is a topic for another day.  The topic for today is, if Google Maps can be used without an API key, and hence without agreeing to the Terms of Service, what does it matter what the terms are anyways?  </p>
<p>That&#8217;s right, the Google Maps API can be used, at least for basic tasks, completely without an API key.  It&#8217;s quite simple really, just a tiny bit more JavaScript:</p>
<pre class="brush: jscript; title: ; notranslate">			//be sure to do this *before* you source in the Google Maps javascript
			window._alert = window.alert;
			window.alert = function() {return;};</pre>
<p>&#8230;and then you can include the Google Maps JavaScript without specifying an API key, like so:</p>
<pre class="brush: xml; title: ; notranslate">&lt;script src=&quot;http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=true&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<p>The added JavaScript simply moves the browser&#8217;s built-in &#8216;<em>alert()</em>&#8216; function to &#8216;<em>_alert()</em>&#8216; so that the map can&#8217;t use it to display a message complaining about the missing API key.  For whatever reason, apart from this alert message Google does nothing to prevent their API from being used without a valid key.  So by simply suppressing the error message you can get a fully functional Google map without registering for a key or agreeing to the Terms of Service.</p>
<p>Put all of this together and you can get an anonymous, unbranded, uncluttered map the works just as well as the original version.  The source code (verified in current versions of IE, Firefox, and Chrome) might look something like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Google Maps API Example Hack&lt;/title&gt;
		&lt;style&gt;
			.terms-of-use-link {
		    		display: none;
			}

			#myMapContainerId div span {
			     display: none;
			}
		&lt;/style&gt;
		&lt;script type=&quot;text/javascript&quot;&gt;
			window._alert = window.alert;
			window.alert = function() {return;};

			window.setupMap = function() {
				window.map = new GMap2(document.getElementById(&quot;myMapContainerId&quot;));
				map.setCenter(new GLatLng(37.4419, -122.1419), 13);
				map.addControl(new GLargeMapControl3D());
				map.addControl(new GMapTypeControl());
			};

			window.unclutter = function() {
				var executed = false;
				var images = document.getElementsByTagName('img');
				for (var index = 0; index &lt; images.length; index++) {
					var node = images[index];
					if (node.src &amp;&amp; node.src.indexOf(&quot;mapfiles/poweredby.png&quot;) &gt; 0) {
						node.style.display = 'none';
						executed = true;
					}
				}

				if (! executed) {
					setTimeout(window.unclutter, 250);
				}
			};

			window.onload = function() {setupMap(); unclutter();};
		&lt;/script&gt;
		&lt;script src=&quot;http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=true&amp;amp;&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	&lt;/head&gt;
	&lt;body&gt;
		Note the lack of branding/logos, terms of use links, and copyright footer text in the map below.&lt;br /&gt;
		Also note the lack of any Google Maps API key in the document source.&lt;br /&gt;
		And the lack of any annoying &lt;a href=&quot;#&quot; onclick=&quot;_alert('I can still create alerts, but the Google Map can\'t.'); return false;&quot;&gt;alert&lt;/a&gt; popups complaining about the API key.&lt;br /&gt;&lt;br /&gt;
		&lt;div id=&quot;myMapContainerId&quot; style=&quot;width: 600px; height: 400px;&quot;&gt;&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>&#8230;which gives you a page like <a href="http://codethink.no-ip.org/mapHacks.html" target="_blank">this one</a>.  It&#8217;s enough to make one wonder why anyone would bother signing up for a Google Maps API key the proper way, when the entire thing can be subverted so easily.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/472/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>[Cocoa + iPhone] Avoiding &#8216;_handleMemoryWarning:&#8217; Crashes</title>
		<link>https://codethink.no-ip.org/archives/455</link>
		<comments>https://codethink.no-ip.org/archives/455#comments</comments>
		<pubDate>Sat, 05 Mar 2011 02:28:42 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[objc]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=455</guid>
		<description><![CDATA[Spend enough time developing iPhone applications (particularly if you go to the trouble of collecting crash logs from your apps), and eventually you are bound to come across something like the following: This error occurs most frequently when suspending an &#8230; <a href="https://codethink.no-ip.org/archives/455">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Spend enough time developing iPhone applications (particularly if you go to the trouble of collecting crash logs from your apps), and eventually you are bound to come across something like the following:</p>
<pre class="brush: plain; title: ; notranslate">2011-03-04 14:17:48.872 myApp[15129:307] -[UIImageView _handleMemoryWarning:]: unrecognized selector sent to instance 0x2b2060
[Switching to process 11523 thread 0x0]
2011-03-04 14:17:57.034 myApp[15129:307] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView _handleMemoryWarning:]: unrecognized selector sent to instance 0x2b2060'
*** Call stack at first throw:
(
	0   CoreFoundation                      0x3759dc7b __exceptionPreprocess + 114
	1   libobjc.A.dylib                     0x32d9bee8 objc_exception_throw + 40
	2   CoreFoundation                      0x3759f3e3 -[NSObject(NSObject) doesNotRecognizeSelector:] + 98
	3   CoreFoundation                      0x37544467 ___forwarding___ + 506
	4   CoreFoundation                      0x37544220 _CF_forwarding_prep_0 + 48
	5   Foundation                          0x351663b5 _nsnote_callback + 156
	6   CoreFoundation                      0x37520971 __CFXNotificationPost_old + 396
	7   CoreFoundation                      0x37520611 _CFXNotificationPostNotification + 128
	8   Foundation                          0x351556a3 -[NSNotificationCenter postNotificationName:object:userInfo:] + 70
	9   Foundation                          0x3515edbd -[NSNotificationCenter postNotificationName:object:] + 20
	10  UIKit                               0x35a32354 -[UIApplication _performMemoryWarning] + 68
	11  UIKit                               0x35a33450 -[UIApplication _receivedMemoryNotification] + 184
	12  UIKit                               0x35a2ef24 _memoryStatusChanged + 64
	13  CoreFoundation                      0x37552333 __CFNotificationCenterDarwinCallBack + 26
	14  CoreFoundation                      0x37537e37 __CFMachPortPerform + 218
	15  CoreFoundation                      0x3752f5cb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 28
	16  CoreFoundation                      0x3752f589 __CFRunLoopDoSource1 + 164
	17  CoreFoundation                      0x37521835 __CFRunLoopRun + 580
	18  CoreFoundation                      0x3752150b CFRunLoopRunSpecific + 226
	19  CoreFoundation                      0x37521419 CFRunLoopRunInMode + 60
	20  GraphicsServices                    0x33e76d24 GSEventRunModal + 196
	21  UIKit                               0x3591d57c -[UIApplication _run] + 588
	22  UIKit                               0x3591a558 UIApplicationMain + 972
	23  myApp                             0x00002649 main + 96
	24  myApp                             0x000025b0 start + 52
)
terminate called after throwing an instance of 'NSException'</pre>
<p>This error occurs most frequently when suspending an app to the background, but it can also happen randomly at other times as well.  Of course, the problem here should be obvious; the crash happens entirely outside of my application code.  After the call to &#8216;<em>main()</em>&#8216; the stack-trace that leads to the crash lies entirely within framework code.  The problem appears to be that some CoreFoundation class is attempting to invoke a &#8216;<em>_handleMemoryWarning:</em>&#8216; selector on objects that do not support it.  </p>
<p>So how to prevent a crash that happens completely outside of your application code?  You might say &#8220;use less memory&#8221;, but that is not a reliable answer here.  The &#8216;<em>_performMemoryWarning</em>&#8216; selector may still be invoked no matter how streamlined your memory usage is.  The answer, or at least the only answer I&#8217;ve found that works reliably, is to use a custom UIApplication subclass and excise the functionality that causes this error, like so:</p>
<pre class="brush: cpp; title: ; notranslate">//
//  SafeUIApplication.h
//  myApp
//
#import &lt;Foundation/Foundation.h&gt;

@interface SafeUIApplication : UIApplication {
}

@end


//
//  SafeUIApplication.m
//  myApp
//
#import &quot;SafeUIApplication.h&quot;

@implementation SafeUIApplication

//these selectors cause crashes in random Foundation classes when the default implementation is called, so instead of crashing our app 
//we ignore these messages, hold on to the memory that has already been allocated to us, and let some other less-clever app crash instead
- (void) _performMemoryWarning {
    NSLog(@&quot;Received a '_performMemoryWarning' call, consider using less memory...&quot;);
    return;
}
- (void) _receivedMemoryNotification {
    NSLog(@&quot;Received a '_receivedMemoryNotification' call, consider using less memory...&quot;);
    return;
}

@end</pre>
<p>Now before the purists and the pedants go jumping down my throat:  Yes, this is a hack.  Yes, it disables built-in memory-management functionality.  Yes, it can mask legitimate problems if your app does in fact have a memory leak (or if it just makes inefficient use of memory).  But having built-in memory-management functionality that crashes the app when called is completely unacceptable in my book, and so disabling it is fair game.  Further, even with this bit of code disabled, the application will still continue to receive low memory warnings (&#8216;<em>didReceiveMemoryWarning</em>&#8216; calls) as normal.  Hanging on to memory that is already allocated to the app cannot cause the app to crash or behave incorrectly, it just means that less memory is available for other apps that are also running.  That seems fair enough to me, at least so long as the default implementation of these methods causes apps to crash.</p>
<p>Anyways, once you&#8217;ve added the SafeUIApplication class to your project, using it is as simple as modifying your application&#8217;s &#8216;main.m&#8217; file like so:</p>
<pre class="brush: cpp; title: ; notranslate">//
//  main.m
//  myApp
//
#import &lt;UIKit/UIKit.h&gt;

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, @&quot;SafeUIApplication&quot;, @&quot;MyAppDelegateClassName&quot;);
    [pool release];
    return retVal;
}</pre>
<p>Just specify the SafeUIApplication classname and your UIApplicationDelegate classname, and you no longer need to worry about obscure &#8216;<em>_handleMemoryWarning:</em>&#8216; crashes.  As noted above, be aware that this will do little to nothing to help applications that have legitimate memory usage issues.  But if you are confident that your application&#8217;s memory usage is correct and you are still experiencing crashes like the one shown above then this little hack will go a very long way towards keeping your application running and stable.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/455/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[JavaScript] setTimeout() and Closures</title>
		<link>https://codethink.no-ip.org/archives/407</link>
		<comments>https://codethink.no-ip.org/archives/407#comments</comments>
		<pubDate>Sun, 20 Feb 2011 03:46:38 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=407</guid>
		<description><![CDATA[If you&#8217;ve done any amount of non-trivial JavaScript coding then you have probably come across the &#8216;setTimeout()&#8216; function before. In case you haven&#8217;t, this function takes a JavaScript expression and evaluates/executes it after a set delay (specified in milliseconds). For &#8230; <a href="https://codethink.no-ip.org/archives/407">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;ve done any amount of non-trivial JavaScript coding then you have probably come across the &#8216;<em>setTimeout()</em>&#8216; function before.  In case you haven&#8217;t, this function takes a JavaScript expression and evaluates/executes it after a set delay (specified in milliseconds).  For instance:</p>
<pre class="brush: jscript; title: ; notranslate">setTimeout(&quot;alert('test')&quot;, 5000);</pre>
<p>&#8230;will display an alert box containing the text &#8220;test&#8221; after a 5-second delay.  Simple enough.  But what you may not know is that &#8216;<em>setTimeout()</em>&#8216; also supports an alternate and much more useful usage mode where instead of literal javascript text you can pass a function reference/closure and a variable number of parameters, like so:</p>
<pre class="brush: jscript; title: ; notranslate">setTimeout(alert, 5000, &quot;test&quot;);</pre>
<p>This will produce the same results as the first call, but the syntax is much more readable and much less prone to errors when coding.  Why this variant is barely even mentioned in the <a href="http://www.w3schools.com/js/js_timing.asp" target="_blank">documentation</a> I cannot say, but anyone who has worked with Flash/ActionScript is <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#setTimeout()" target="_blank">probably familiar</a> with this syntax. </p>
<p>There is one major limitation to this approach, however; it does not work correctly in Internet Explorer.  That&#8217;s a pretty serious drawback, considering Internet Explorer&#8217;s market share.  But we can fix it by overriding the default &#8216;<em>setTimeout()</em>&#8216; implementation as follows:</p>
<pre class="brush: jscript; title: ; notranslate">window._oldSetTimeout = window.setTimeout;
window.setTimeout = function(closureOrText, delay) {
    if (arguments.length &lt;= 2 || typeof closureOrText != &quot;function&quot;) {
        _oldSetTimeout(closureOrText, delay);
    }
    else {
        var funcArgs = new Array(); 
        for (var index = 2; index &lt; arguments.length; index++) {
            funcArgs.push(arguments[index]);
        }
        _oldSetTimeout(_timeoutCallback(closureOrText, funcArgs), delay);
    }
};
window._timeoutCallback = function(closure, argArray) {
    return function() {
        closure.apply(this, argArray);
    };
};</pre>
<p>Now the behavior will be consistent between Internet Explorer and other browsers.  Note that although the default implementation only needs to be overridden in Internet Explorer, the above code will work correctly in other browsers as well.  Also note that there is one more caveat to be aware of here as well.  In Internet Explorer, functions provided by the system (such as &#8216;<em>alert()</em>&#8216;, &#8216;<em>escape()</em>&#8216;, &#8216;<em>parseInt()</em>&#8216;, etc.) are of a different type than user-defined functions.  Now this wouldn&#8217;t be a huge problem, except that whatever type Internet Explorer uses for its system functions does not support the &#8216;<em>apply()</em>&#8216; method (thanks, Microsoft).  </p>
<p>So even with the above code, if you use &#8216;<em>setTimeout()</em>&#8216; with a system function in Internet Explorer, you will still get incorrect behavior.  We can fix this by revising the code as follows:</p>
<pre class="brush: jscript; title: ; notranslate">window._oldSetTimeout = window.setTimeout;
window.setTimeout = function(closureOrText, delay) {
    var funcArgs = new Array(); 
    for (var index = 2; index &lt; arguments.length; index++) {
        funcArgs.push(arguments[index]);
    }
    if (arguments.length &lt;= 2 || typeof closureOrText != &quot;function&quot;) {
        if (arguments.length &lt;= 2 || typeof closureOrText == &quot;string&quot;) {
            _oldSetTimeout(closureOrText, delay);
        }
        else {
            //hack for IE system functions
            _oldSetTimeout(_timeoutCallbackForSystemFunction (closureOrText, funcArgs), delay);
        }
    }
    else {
        _oldSetTimeout(_timeoutCallback(closureOrText, funcArgs), delay);
    }
};
window._timeoutCallback = function(closure, argArray) {
    return function() {
        closure.apply(this, argArray);
    };
};
window._timeoutCallbackForSystemFunction = function(closure, argArray) {
    return function() {
        if (argArray.length == 1) {
            closure(argArray[0]);
        }
        else if (argArray.length == 2) {
            closure(argArray[0], argArray[1]);
        }
        else {
            alert(&quot;WARN:  Too many arguments passed to system function; timeout callback not executed!&quot;);
        }
    };
};</pre>
<p>This code will produce the correct behavior in Internet Explorer, and is still compatible with all other major browsers.  In Internet Explorer it is limited to supporting system functions with a maximum of 2 parameters, but I&#8217;m not aware of any that require more than that anyways.  An alternate workaround is to define your own function that wraps the system function, and then use the wrapper function in the &#8216;<em>setTimeout()</em>&#8216; call, like so:</p>
<pre class="brush: jscript; title: ; notranslate">var myAlert = function(text) {
    alert(text);
};
setTimeout(myAlert, &quot;5000&quot;, &quot;test&quot;);</pre>
<p>It&#8217;s a bit less convenient to do it this way if you will be working with several different system functions, but this approach will also yield correct behavior in Internet Explorer (and is compatible with other browsers as well).  </p>
<p>In any case, either approach can be used to get the closure-based &#8216;<em>setTimeout()</em>&#8216; syntax working consistently across all major browsers.  And once you have that, there is very little reason to ever prefer the text-based version.  </p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/407/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
