A break from (sexy) learning

January 21, 2010

For the past month, I’ve been unable to study anything new and sexy. Rather, I’ve been preparing for the ICPC 2010 World Finals.

Most recently, I’ve been working on this:

ICPC Challenge Screenshot

Essentially, contestants build an AI to battle it out in an FPS-esque arena. It was really quite interesting, although it required serious time input.

For more info, look here. My team really only had one good pre-submission, but our final product should be competitive.

If you’re interested in participating in AI battling tournaments, you might want to check out the newly created ACM Queue Challenge.

XSLT: How you should be transforming XML into HTML.

January 5, 2010

XSLT is a method of transforming XML with a set of rules, functions, and selectors. Transformations can be complex or simple, but the benefit of using XSLT is immediately obvious after first use.

Consider the following:

<posts>
   <post>
      <title>XSLT!</title>
      <description>A short post about XSLT</description>
      <content date = "01/03/2009">
      Lorum ipsum
      </content>
   </post>
<posts>

The naive approach of displaying this to the user is to manually parse the data with an XML parser of some kind. I’ve done this in previous projects; it works, but it’s generally stuck in code, which means that changes to the output format require recompilation or some other elaborate build and deployment. This is inherently wrong given the process that’s taking place. A transformation of XML can and should be independent from the XML itself.

Here’s some pseudocode for the rendering of an XML document into HTML:

html = '<html><body>'
for node in document.find( 'post' )
    title = node.find( 'title' ).text
    descriptionNode = node.find( 'description' )
    postDate = descriptionNode.attribute( 'date' )
    descriptionText = descriptionNode.text

    html += '<div>'
    html += '<h1>' + title + '</h1>'
    html += '<p>' + descriptionText + '</p>'
    html += '<p><em>' + postData + '</em></p>'
    html += '</div>'

html += '</body></html>'
render(html)

While this is straightforward enough in the trivial example, it falls apart when parsing large, complex documents. Consider now the XSLT equivalent:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:template match="/">
        <html>
            <body>
                <xsl:apply-templates />
            </body>
        </html>
    </xsl:template>
    <xsl:template match = "post">
        <div>
            <xsl:apply-templates />
        </div>
    </xsl:template>
    <xsl:template match = "title|description">
        <p><xsl:apply-templates /></p>
    </xsl:template>
    <xsl:template match = "content">
        <p><xsl:apply-templates /></p>
        <p><em><xsl:value-of select="@date" /></em></p>
    </xsl:template>
</xsl:stylesheet>

Although the trivial example is longer in terms of characters, there are numerous benefits to this approach.

  1. The transformation is externalized. If you decide that all post divs now need a “post” class, you don’t need to recompile, and you know exactly where to make the change.
  2. Presumably, your XSLT editor can validate XML, or at least tell you when you’re missing a closing angle bracket or two. Most IDEs will not see unclosed angle brackets within strings as a problem, so in you get a proper environment in which to craft your output HTML. Sure, you could use an XML library that hides this implementation from you, but you still run the risk of missing an element or forgetting to append nodes to one another. This wastes time. With a XSLT document, you can very clearly easily about your output before testing. This emphasizes another issue.
  3. Good XSLT editors will let you quickly and easily run XSLT against XML. Using oXygen, I was able to develop the above document in under a minute. Actually testing manually-manipulated XML, on the other hand, takes much more time.

All of this said, there are still reasons to avoid XSLT in certain situations. All browsers do not support XSLT, and there are few XSLT 2.0 processors at the moment. Ergo, you must perform your transformations on the server, rather than on the client, but you should probably be doing that anyway. Furthermore, maintenance programmers will need to know XSLT to debug and extend your application, so if you’re worried about limited knowledge handling your software, it may be best to simply avoid XSLT altogether.

I’ve quickly found that XSLT is often the right tool for the job, however, so it would be a sin to not learn enough of the technology to recognize when its applicable and when it isn’t. Don’t craft your HTML by hand, but only use XSLT when it’s appropriate.

Why I chose Linode as a webhost

November 24, 2009

Linode.com offers linux virtual private server (VPS) systems that you can use to do anything. Now, when I say anything, I don’t mean we’ll-give-you-unlimited-databases anything, I mean ANYTHING anything. If you google search correctly, you can find reports of customers using their Linode to host Left4Dead servers, within the terms of use. So, then, here are my reasons for using Linode as a server solution.

Flexibility

As mentioned, Linode lets you do anything. Currently, I use my server to host subversion, tomcat, apache, MySQL, postfix email, and random files. But surely, you say, the hardware must be oversold, or you’re restricted in some crippling manner? Well, not really. I come nowhere close to my guaranteed bandwidth, CPU, or memory allotment with the smallest package available:

Linode 360:

  • 360MB RAM
  • 16GB Disk Storage
  • 200GB/mo transfer
  • $19.99/mo

The only perceivable downside to this flexibility…is the flexibility. When you create a server, you start with a flat, uninteresting linux distribution. You must manually install apache, tomcat, subversion, and whatever other services you wish to run. This configuration, however, lets you fine-tune the system to your exact specifications, and it lets you learn how to do all that in the process. With SSH at your side, you too can become a Linux ninja and master the lore of old. You’ll probably wind up a more efficient developer, and at the very least you’ll learn a neat Unix command or two.

Price

$19.99/mo for a web server seems pricey, but it really isn’t. You’re buying power, guaranteed reliability, and ownership of your server. By Linode’s own FAQ, hardware resources are guaranteed, and when the system is able, bursts of usage beyond are allowed. With a general web host, you’re stuck to whatever you’re given. The only other competition in this arena, really, is Slicehost. Their base $20/mo package only includes 256MB of RAM, however, which is simply unacceptable when a 384 solution exists for the same price.

Reliability

In the 5 months I’ve owned my Linode account, my server has only gone down once, for a 1-hour period. I was rather upset at the outage, as I use my server nightly, but I was not riled enough to seek a $0.66 refund. Performance, too, has always been top-notch. Not once have I ever noticed latency, which is simply incredible compared to general web hosts.

Conclusion

Linode is amazing, and if you believe me, click the referral link I hid in the first word of this post. If you stay on 3 months with my referral code, I get a month free.

Cheers. :)

Spring 2.5 with SpringMVC

November 19, 2009

This month, I decided to go more in-depth with Spring and SpringMVC and model the web services for a CMS/Shopping Cart system. With Spring, Tomcat, XOM, and JUnit, I was able to speedily throw together a modular, DI-driven web service that implemented a simple web service interface without needing to worry about database details or request mapping.

Specifically, Spring’s MultiActionController and XOM’s XML building utilities let me write the minimal AccountController given below.

public class AccountController extends MultiActionController
{
private AccountManagementService accountManagementService;

public ModelAndView login( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
   String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
   String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
   Document xmlDoc = accountManagementService.login( username, password );

   response.getWriter().println( xmlDoc.toXML() );

   return null;
}

public ModelAndView register( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
   String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
   String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
   Document xmlDoc = accountManagementService.register( username, password );

   response.getWriter().println( xmlDoc.toXML() );

   return null;
}

public void setAccountManagementService( AccountManagementService accountManagementService )
{
   this.accountManagementService = accountManagementService;
}
}

The URL mapping for service requests was also dead-simple:

<bean id="urlMappingDeployment" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
      <property name="mappings">
         <props>
             <prop key="/login.do">accountController</prop>
             <prop key="/register.do">accountController</prop>
             <prop key="/getInventory.do">inventoryController</prop>
             <prop key="/updateInventory.do">inventoryController</prop>
          </props>
      </property>
   </bean>

By utilizing Spring, I saved reams of code, although using a more expressive language like Groovy with Grails may have been quicker and more expressive. At any rate, I’m off to go learn about XSLT. Cheers. :)

Scala – fun, powerful JVM fun

October 12, 2009

If you’re like me, you heard about this language on the Java Posse Pod-cast (link), and you’re just now trying to figure out what all the hubbub is about. Well, Scala is functional, declaration, strongly typed (although it doesn’t feel like it), and most importantly, a JVM language. it compiles to Java classes, and with the inclusion of a single library, you can work Scala quite easily into your web application, either by design or postfixed.

Aside from ease of integration, Scala also offers many functional concepts: first-class functions, curried functions, partially applied functions, and in simple cases, tail recursion! Object-Oriented purists can continue to work as they would in Java, but those of us willing to dabble in the dark-arts can do things like this:

class MyApplication extends Application {
   println( "Hello, World!" )
}

See what’s happening? The closure between the braces is passed as a constructor argument to MyApplication, which then executes the function. It’s not that much of a convenience, but for small applications, public static void main( String[] args ) is just annoying.

Tomcat

Remember how I said Scala could run under Tomcat as easily as Java? Well, I setup a servlet on my server to proxy file downloads. Try this:

http://stefankendall.com:8080/download?url=http://stefankendall.com/files/test.txt

It’s not much to see, but the code is pretty simple!

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import javax.servlet.ServletOutputStream
import java.net.URL
import java.io.{BufferedInputStream, PrintStream, StringWriter, PrintWriter }

class ProxyDownloadServlet extends HttpServlet
{
	override def doGet( request: HttpServletRequest,	response: HttpServletResponse )
	{
		//get the file url to download from the GET request parameter
		val fileUrl = request.getParameter( "url" );

		//if no url was provided, write that to the user
		if( fileUrl == null )
		{
			response.getWriter().println( "<html><body><p>No download url!</p></body></html>" )
			return
		}

		try
		{
			//download the file
			val inputStream = new BufferedInputStream( new URL( fileUrl ).openStream() )

			//set the content type of the response so the
			//user will be prompted to download
			response.addHeader( "Content-Type","application/octet-stream");

			//get the output stream
			val outputStream = response.getOutputStream();

                                  //data buffer
			var buffer = new Array[byte](4 * 1024)

			var bytesRead = inputStream.read( buffer )
			while( bytesRead != -1 )
			{
				outputStream.write( buffer, 0, bytesRead )
				bytesRead = inputStream.read( buffer )
			}
		}
		catch
		{
			case e => {
				println( "Attempted to download:" )
				println( fileUrl )
				e.printStackTrace()
				response.setContentType("text/html")
				outputStream.println( "<html><body><p>Bad file url!</p>" )
				outputStream.println( "<p>File: " )
				outputStream.println( fileUrl );
				outputStream.println( "</p>" )
				outputStream.println( "</body></html>" )
			}
		}
		finally
		{
			inputStream.close()
			outputStream.close()
		}
	}
}

I had some trouble getting things like String concatenation working under Tomcat (Yeah, I know.), and the tools for Scala are rather weak right now (at least the eclipse plugin), but it’s definitely not Java! There’s probably a more Scala way to do this, but that just illustrates the point: you can use as much, or little, Java-isms as you see fit. Remember that this compiles to .class files, so it can mingle with other Java servlets as easily as other Java could.

[[Objective-C prog] with: iPhone and: iTunes release]

September 16, 2009

Doesn’t that subject line look crazy? Well, in Objective-C, methods, properties, and members are accessed with maniacal brackets. This is fine, aside from the fact that you need to know how deep you’re going to chain a method call BEFORE you actually do it, as otherwise you have to go back and add the correct number of left brackets. Objective-C 2.0, as supported on the iPhone, supports dot notation, but when in Rome, I hear you use crazy bracket syntax. So, then, how does this all play out? Well, iPhone development can really be sectioned off into its constituting parts: Objective-C programming, Interface Builder, and release to the app store on iTunes.

Objective-C

Objective-C 2.0 has properties, strong typing, and memory management. Objective-C for the iPhone only has the first two. For this reason, we’re forced to deal with memory management or deal with the terrible results. In making a simple business calculator, I was able to leak 6 UI elements each time the program was run and take my 3GS iPhone down to a few MB of remaining ram in only 7 or so test runs. The solution, of course, was simply releasing the UI objects when the application was closing, but this is a significant annoyance when trying rapidly design software.

True properties, of course, with synthesized property methods, save a decent amount of time and just look nicer than having your IDE generate getters and setters.

Consider the following:

//Tester.h
@interface Tester
{
   MyClass * myClass;
}
@property MyClass * myClass;
@end

//Tester.m
@implementation Tester
@synthesize myClass;
@end

Now, [testObj myClass] calls the implicitly created getter of Tester, and [testObj setMyClass: myClass] calls the implicitly generated setter. Isn’t that cool?

iPhone Development

Aside from the Objective-C nonsense, the iPhone SDKs and Interface Builder make life pretty easy for app development. Interface Builder provides a full visual interface for designing iPhone applications, and XCode even provides an iPhone emulator with which to test applications. Sure, the emulator won’t tell you if you have a memory leak, or anything of that nature, but there are other tools to monitor such.
/* TODO: add screenshots */

iTunes and iTunes Connect

The release process to iTunes, while relatively painless, requires a wealth of information and takes about two weeks to process (at least it did for FoodWatcher, my “Hello World” iTunes application to measure weightwatchers points).

The following is required to submit an application to the app store:

  • application name
  • application version
  • 512×512 image to represent the application. This is used if the application gets “featured.”
  • 57×57 iPhone icon for the application. You can either add your own gloss or let the iPhone render it for you.
  • At least 1 screenshot of the application in progress
  • A support website for the application
  • A support email for the application
  • A list of user names/passwords if your application requires it

and for non-free applications, you need to provide full tax/bank information. The process is a bit of a hassle, but the requirements make sense given the context of iTunes and the App Store.

jQuery: Plugins.

August 19, 2009

jQuery has plugins.

Lots of them, in fact. The jQuery plugin page lists hundreds of additions to the base jquery package. These plugins make web development even easier and more glamorous than jQuery alone, doing splendid things like Show dialogs.

Now isn’t that cool? jQuery plugins let external authors write neat libraries to extend the language, much as firefox extensions improve the core of firefox. As jQuery has become the javascript go-to tool of choice, jQuery plugins have become the library tools of choice for productive, external-library-oriented developers, such as you and me. So fly, ye’ programmer, and explore the world of jQuery plugins.


iPhone Development and Objective-C

August 6, 2009

I’m getting an iPhone!

For development, of course! However, I do not yet own a macbook of any kind, so I was mostly stuck in what to do. Apparently, KDevelop supports Objective-C, but it seems as if the mac platform is THE platform for obj-c development. I generally despise OSX, but I’m learning to accept its windowing system and even ENJOY it in certain circumstances! First-class windows in all apps seems unwieldy at first, but you really begin to appreciate the ability to put ANY window from ANY application ANYWHERE. Such just isn’t feasible in Windows, but Windows 7 seems to aid this with proper docking of windows.

So, then, how am I learning Objective-C with Xcode to lead into iPhone dev? Simply put, VMWare.

Here’s how I did it:

  1. Obtain iPC OSx86 10.5.6 Universal PPF5 (Final).iso and the latest version of VMWare.
  2. Set up the hard disk for OSX. Allocate AT LEAST 25GB. I allocated as much and currently have 8GB remaining. Use the default SCSI hard drive option. Also make sure to choose
    FreeBSD 64-bit as the guest OS and select “bridged networking.”
  3. Before booting the VM for the first time, edit the disk image’s .vmx configuration file. Change guestOS=freebsd-64 to guestOS=darwin-64
  4. Mount the OSX image in D-tools or your mounter of choice and set the CD drive in vmware to the mounted image. Do NOT use vmware to mount the image; this won’t work.
  5. Boot the VM. Go to Disk Utilities and select erase. The hard drive will be formatted for installation of OSX.
  6. Back out of disk utilities and continue the install as normal. You can select various installation customizations, but I chose none and was successful in installation.
  7. DO NOT UNMOUNT THE DISC IMAGE, despite OSX’s plea. Restart normally. You will NEED to have the DVD image mounted to boot OSX. If you do not have the image on boot, you’ll get an “Operating System Not Found” error and won’t be able to continue the boot.
  8. Set the network connection type to “NAT.”
  9. Configure OSX, and enjoy :) . You should be able to run Software Updater to move to 10.5.7 without issue.

Phew. I tried 2 10.5.7 images on vmware and hardware, and after deciding that enabling AHCI in an existing XP partition was impossible without a floppy drive, I conceded to the fact that VMWare was the only way to go. Now, though, I’m rocking out with OSX, and you should too! Make sure to actually get a mac at some point; while the VM is mostly stable, I’ve had some instability issues with Preview after installing Safari 4. To avoid such weirdness, just buy a mac!

jQuery plugins coming.

jQuery: Better web programming

July 24, 2009

Point 1. jQuery emphasizes brevity.


The title pretty much states it all. Nearly everything I used to hate about making web pages fancy and functional is alleviated with a few lines of jQuery. With a few dollar signs here and there, you can accomplish all kinds of madness. For instance, consider the following:

$('.toHide').hide('slow');

Try me! [Scroll Down]

This little code bit slowly hides all elements on the page with the ‘toHide’ class. Conceptually, this is simple, but what have we truly accomplished? In a single line, we achieved implicit iteration [all .toHide elements], an opacity transition [hide], and timed animation [slow]. Much of the features of jQuery are available in one-liners as such. In fact, most methods return the jQuery object itself so that calls may be chained with righteousness.

$('.toHide').css('color','red').hide('slow');

Try me!

This turns all our toHide elements red and then immediately begins the hiding animation. Neat, huh? In all facets, it seems, jQuery emphasizes conciseness. From the jQuery function itself [$] to the way selectors work $(’#myId’), everything is short. For code golfers, this should be a pleasant movement from document.getElementById(’puke’).

Admittedly, this is but a small portion of what jQuery can do to make your life easier, and in the next post I’ll discuss the plugins architecture and its place in the mystical world of $(). If you thought firefox’s plugins were useful, you haven’t used jQuery’s.

Example:

  • Example list item 1
  • Example list item 2
  • Example list item 3

Example h3

Hello, World! [real post]

July 6, 2009

Hello, World! In this post, I would just like to take a moment to outline my goals for this website. In learning different technologies, I’ve realized that certain paradigm shifts or concepts are de-facto hurdles to be overcome in the learning of a language or technology.  With this in mind, I wish to categorize and detail my experiences learning new technologies and programming languages to serve as a short guide to the problems I faced and challenges I needed to overcome in learning a given tech. Certainly, websites such as StackOverflow provide instant-answers to such problems, but I intend to provide the narrative behind the problem and hopefully expose some insight into the problem-solving process.

As per the website title, I’m challenging myself to learn one new technology a month. Less time for a programming language, framework, or concept [a "prog"] would give only cursory knowledge, but I hope to hit that sweet spot by which I could name a prog as the right tool for a problem and not restrict myself to only currently known progs.

So, what do do from here, you ask? Learn jQuery. I’ve always been opposed to the web as platform, mostly due to IE6, but flex has convinced me that there is a light, and jQuery seems to be another beacon in the treatorous sea that is supporting internet explorer. Granted, I now believe IE8 to be a valid browser contender and a solid improvement to both IE and web browsers as a whole, but IE6 continues to infest the waters of the web, and developers are forced to hack their way through the dragons and krakens.

Ranting aside, jQuery appears to offer a number of handy selectors and event handling mechanisms that make developing for IE less-painful than before. Someone else abstracted away the nonsense, and we as developers profit. :)

Onward, to jQuery!

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org