Archive for the ‘Programming’ Category

Fair Dice (for Settlers of Catan and other games using dice)

Sunday, July 8th, 2007

I love games, but I hate dice. They vex me so. Especially while playing Settlers of Catan. If you’re twice as likely to roll a seven as you are a four, then why in the hell has four come up five turns out of the last six? Etc etc. You get the idea.

Inspired by Erich’s dice-by-cards Catan variant (and also by not having a spare deck of playing cards, and also by having recently taken pictures of a six-sided die) I put together Fair Dice. It’s a goofy little JavaScript application that will roll all thirty-six combinations of two dice once in random order. When it’s done, it will do it again.

Now, is this sort of thing useful? Who knows. Probably half the fun of a game like Settlers is watching people fume when threes and elevens come up over and over and over again while those sixes and eights that they so wisely choose at the beginning of the game go fallow. So you know me: I like to destroy fun.

A random non-gaming aside: How do people write web pages without FireBug? I looked briefly at making sure that this works correctly on IE and Safari, and I couldn’t tell what in the world was going on. For the longest time the page didn’t do anything because apparently Safari and IE (IE 6, at least) don’t understand the “const” keyword in JavaScript. Infuriating! Anyway, if you’re having to contend with JavaScript, I can’t recommend FireBug quite enough.

(Fair Dice)

Applying lessons from journalism to UI design

Saturday, June 23rd, 2007

flow|state has a very good UI design piece up currently. Its simple recommendation: make sure the important bits of the UI are front and center.

Can you see the disaster in progress? Most users can’t either.

This dialog has buried the lede. It focuses the user’s attention on the fact that there is another file with the same name in the destination folder. It fails to point out a much, much more interesting condition: The user is about to overwrite a newer file with an older file.

[...]

The above dialog’s text fails at this, as does its layout and typography. There are numerous pieces of text competing for attention, but among the most prominent are the bolded file names. That’s a bit odd, since the entire premise of the dialog is that these two file names will be the same. The dialog has carefully drawn the user’s attention to information which is guaranteed to be redundant. (If the user is moving multiple files, only some of which have conflicts, the file names are relevant—but that case can and should be handled specially.)

I’ve never thought consciously of following the inverted pyramid while laying out a UI, but it makes a lot of sense. I’m curious to look in on some of the screens I’m working on currently to see how well I stick to this principle.

An open letter to JPL

Wednesday, June 20th, 2007

Sirs and Madams,

Thank you for releasing your CLARAty software to the public. That is a wonderful move that we can all appreciate. However, I have one comment regarding your installation procedures: Csh? Really?

Good Day.

Calling Java applets from JavaScript

Monday, June 4th, 2007

I ran in to a situation recently where I had a big mess of code written in Java that I really wanted to call from a client-side web application. I could wrap said code up in a servlet, but that would be a lot of work. As it turns out, you can call methods on Applets directly from JavaScript, so all I have to do is wrap my code in one of those. Bonus!

Here’s a brief example

DoublerApplet.java

package org.obfuscated.example;

import java.applet.Applet;

public class DoublerApplet extends Applet {
    public double f(double x) {
        return x + x;
    }
}

Nothing special there. Note that I’ve not yet tried passing classes or the like to an applet. I imagine that they might be trouble.

index.html

<html>
  <head>
    <title>Applet Test</title>
    <script src="prototype.js"></script>
    <script src="doubleit.js"></script>
  </head>
  <body>
    <object id="doubler"
       classid="java:org.obfuscated.example.DoublerApplet.class" 
       type="application/x-java-applet"
       archive="DoublerApplet.jar" 
       height="1" width="1" >
      <param name="scriptable" value="true"/>
    </object>

    <b>Double me!</b>
    <br/>
    2 * <input size="5" type="text" id="x"/> = <span id="answer">???</span>
    <br/>
    <input type="submit" id="go"/>
  </body>
</html>

The important part is the “scriptable” parameter. It tells the applet to listen to the JavaScript.

doubleit.js

var init = function() {
    Event.observe('go', 'click', function() {
        var x = Number($('x').value);
        var applet = $('doubler');
        $('answer').innerHTML = applet.f(x);
        return false;
    });
};

Event.observe(window, 'load', init);

The “$” magic that makes the JavaScript code quite so terse is Prototype, which I can’t quite recommend enough.

Anyway, I’m quite pleased that I’m able to use this technique, as dragging out Tomcat, keeping it running, etc., would be a whole lot of work just to be able to call one function. (Which is all I need to do in this particular case.) I’m sure the server-based solution would be more correct if I needed to do more in Java-land, but for quick and dirty things or one-off’s, JavaScript to Applet communication is nice.

Using Parsec in simple Haskell programs

Saturday, May 26th, 2007

I read two very useful articles about Haskell recently. First is Haskell IO for Imperative Programmers which explains how to do simple IO. (It’s less obvious than you’d think, especially if you’re coming from one of the more popular languages like Java or Ruby.) The second is called JSON Parser in Haskell. It covers in a brief yet very informative way the exceptionally useful Parsec library that ships with many Haskell implementations.

Each of these articles are incredibly useful. You have to know how to get data in and out of your program, and there aren’t a lot of tasks that don’t require parsing data. The two techniques together, as you might expect, are crazy useful.

To summarize perhaps too quickly, you can do simple stdin/stdout IO using the “interact” function. Here’s the Haskell implementation of the popular “tac” utility:

main = interact $ unlines . (map reverse) . lines

The “lines” method turns a large string (stdin) in to a list of strings, “unlines” turns a list of strings in to one large string (stdout), “interact” ties the whole process together, and “(map reverse)” is where you would put your code.

In place of “lines” you can usefully drop Parsec in such that you can work directly on data structures instead of fussing with lines of text. (Haskell isn’t Perl, after all.) Here’s a quick example that reads pairs of integers:

module Main where
import Text.Printf
import Text.ParserCombinators.Parsec

atoi :: String -> Int
atoi = read

intsList :: Parser [(Int,Int)]
intsList = do
  intsList' <|> (eof >> return [])
      where intsList' = do
              a <- many1 digit
              many1 space
              b <- many1 digit
              newline
              r <- ( many space >> (intsList' <|> return []))
              return ((atoi a, atoi b) : r)

parseInput :: String -> [(Int,Int)]
parseInput s = case parse intsList "stdin" s of
                 Left err -> []
                 Right cs -> cs

rpt :: (Int,Int) -> String
rpt (a,b) = let c = maximum $ map ( length . cyc ) [a..b]
            in printf "%d %d %d" a b c
    where cyc n | 1 == n       = [1]
                | 1 == mod n 2 = n : cyc (1 + 3 * n)
                | otherwise    = n : cyc  (div n 2)

main = interact $ unlines . (map rpt) . parseInput

And just like that you can move input parsing in to a parser where it belongs and not worry about it in the rest of your system. Certainly a lot more work than the same thing in, for instance, Ruby:

STDIN.each { |l| a,b = l.split.map {|x| x.to_i} ; puts whatever(a, b) }

However, dropping Parsec works the same way for arbitrarily complex data structures. This same code structure workspairs of integers, HTTP, JSON, whatever. Needless to say, I find this very pleasing.

Dave Thomas on Paying Back

Tuesday, May 22nd, 2007

Dave Thomas has a fine idea for improving conferences by adding a focus on charitable giving:

Just imagine the difference we could make if, as an industry, we turned each of these conferences into a chance to raise much needed money for worthy charities. Imagine if, rather than getting yet one more burlap bag with a sponsor’s name on it, you instead got a slip of paper saying that the price of that bag was being used to buy vaccine for 5 kids, or a book for a literacy project. Imagine what could happen if a conference with 5,000 attendees raised just $20 per attendee. Then imagine $50, or $100. It starts to get serious.

As somebody who falls squarely in to the “I’m not going to use your Complete Enterprise Solution even if you give me a tote bag and a glow-in-the-dark yo-yo” camp, I think this is a great idea. Nobody needs another Sun-branded pen or Google Frisbee; there are lots of people out there who could make good use of a nerd’s pocket change.

Things to do when you’re a nerd and you can’t type

Sunday, May 20th, 2007

I spent Thursday and Friday at work essentially without fingers. Well, I had fingers, but only one useful hand of them. Interestingly enough, I learned that I’m at least in the short term incapable of hunt-and-peck typing. Finger muscle memory takes over when I try and everything goes all crazy-go-nuts. Not a good time.

My original plan for my convalescence was to go charge a book on JavaScript to the company account and see if I couldn’t learn a bit about a language that I’m likely going to use for an upcoming project. However I don’t know what the good JavaScript books are, and walking to the book store is a lot more work than surfing the internet, so I checked for good online resources.

It turns out that there are many. In particular, Yahoo!’s YUI team has put together large collection of videos about JavaScript. I watched videos of three of Douglas Crockford’s lectures: “The JavaScript Programming Language,” “An Inconvenient API: The Theory of the DOM” and “Advanced JavaScript.” All three were good lectures. They were, for shots of a lecture about a programming language, well produced, and Crockford’s talks were well structured. I got a lot more out of the first talk than the other two, but that could arguably be couched more as a compliment for the introduction video than a knock on the other two, as I felt like I knew the language pretty well after it. (I’d never used the language seriously before.)

I didn’t get too far in to any of the other videos, but there are a ton of them there, so there’s got to be at least a few more good ones. If you’re looking to pick up JavaScript, I can recommend the YUI Theater as a good place to start.

Disturbingly Concise

Sunday, May 6th, 2007
import Control.Monad

powerset :: [a] -> [[a]]
powerset = filterM (const [True, False])

I saw this over on a rather good introduction to dynamic programming. It does exactly what you’d expect it to do. (i.e., powerset [1,2] = [[1,2],[1],[2],[]].)

Outstanding.

Thought for the day (nerd edition)

Friday, March 30th, 2007
Though the debates will forever rage about which JVM dynlang should carry us into the future, the same facts that have guided programming for half a century still apply today: No one language will be enough to carry us forward; no languages will survive indefinitely; and the language you’ll use in ten years you’ve probably not even heard of yet

From Ruby on Grails? Why the hell not?

Testing Java with JRuby

Tuesday, March 27th, 2007

Chris chided me in the Java only gets 10mpg comments for not giving Groovy or Rhino a go. Chris has a fondness for busting my chops equaled by few. However, he does it because he cares, so I thought a bit about using non-Java languages on the JVM.

I still think that in general, I have little use for the Java platform. If I want to write code in something like Ruby or Python, I’ll just use Ruby or Python or whatever as they’re originally distributed. Bolting them on to the JVM really doesn’t do anything for me. That said, if I can use them to get out of ugly, tedious work, maybe they’re worth my time.

As it happens, I recently inherited about a quarter million lines of Java code. There are chunks of it that are somewhat lacking in terms of unit tests, and I’m one of those mutants who really doesn’t like to fix code without exerciseing the problem with a test first. With this project, I’ve been having to write hundreds and hundreds of lines of test code to make very simple changes. It’s safe, but it’s not exactly efficient or fun.

So I took Chris up on his suggestion and gave JRuby a look for writing tests. It works surprisingly well. There’s not that much setup work that you need to do to get the environment up and running, and once you do it’s rather nice to not have to slog through the ugly world that is Java the language to get your tests written.

Here’s a very brief sample. What I wanted to do is have a very traditional ant-based project with the standard init->compile->test->dist dependency chain, but sub JUnit out for JRuby and Ruby’s unit test framework. First, the silly little Java class that I used for testing:

src/java/org/obfsucated/example/Overbearing.java

package org.obfuscated.example;

public class Overbearing {
    /** Javaize a string.
     **
     ** Everybody knows that Java people can't stand data unless
     ** it's XML or some sort of proprietary binary format that
     ** you have to pay Sun $10,000/seat to use.  Our Overbearing
     ** class should be able to take any pedestrian string and
     ** turn it in to something that any Java programmer would
     ** love and cherish forever.
     **
     ** @param original an ugly, non-Enterprise-compliant string.
     ** @returns a String that you could put in some sort of bean.
     */
    public String javaize(String original) {
    if(null == original)
        return null;
    StringBuilder sb = new StringBuilder();
    sb.append("<java-is-rad>< ![CDATA[");
    sb.append(original);
    sb.append("]]></java-is-rad>");
    return sb.toString();
    }
}

And here are the relevant Ruby source files:

src/jruby/test_all.rb

require 'test_overbearing'

src/jruby/test_overbearing.rb

require 'test/unit'
require 'java'

Overbearing = org.obfuscated.example.Overbearing

class TestOverbearing < Test::Unit::TestCase
  def setup
    @overbearing = Overbearing.new
  end

  def teardown
    @overbearing = nil
  end

  def test_creation
    assert_not_nil @overbearing, "We should be able to create an Overbearing object"
  end

  def test_simple_string
    original = "Hello World"
    expected = "<java-is-rad><![CDATA[Hello World]]></java-is-rad>"
    resultant = @overbearing.javaize(original)
    assert_equal resultant, expected
  end

  def test_nil_string
    original = nil
    expected = nil
    resultant = @overbearing.javaize(original)
    assert_equal resultant, expected, "Nil strings should stay that way"
  end
end

It’s all pretty staraightforward stuff. I like to run unit test suites by requiring all of my tests in one file and just calling that with the interpreter. (Thus the “test_all.rb” file.) There are without doubt better ways to do this. You get the general idea, though.

One gotcha is that if you have a package with calital letters, you can’t alias it as above. So let’s say you have a class with a fully-qualified name of org.obfuscated.BadPackageName.Whatever. JRuby — or Ruby itself, if I had to guess based on the way identifiers are usually handled — will not be able to find it if you just say

Whatever = org.obfuscated.BadPackageName.Whatever

Instead, use the include_class function to make sure it’s loaded.

include_class('org.obfuscated.BadPackageName.Whatever')

Long story short, though: don’t use capital letters in package names.

The Ant setup isn’t too difficult, either. Assume the following properties are available:

jruby.dir
The directory where JRuby is installed
jruby.test.dir
The directory where you keep your test scripts (testall.rb and testoverbearing.rb in this case)
The relevant parts of the build.xml file look like this:

  <path id="jruby.classpath">
    <fileset dir="${jruby.dir}/lib">
      <include name="*.jar"/>
    </fileset>
  </path>

  <target name="test" depends="compile">
    <java classname="org.jruby.Main" fork="true" failonerror="true">
      <classpath refid="project.classpath"/>
      <classpath refid="jruby.classpath"/>

      <sysproperty key="jruby.base" value="${jruby.dir}"/>
      <sysproperty key="jruby.home" value="${jruby.dir}"/>
      <sysproperty key="jruby.script" value="jruby"/>
      <sysproperty key="jruby.shell" value="/bin/sh"/>

      <arg value="-I"/>
      <arg value="${jruby.test.dir}"/>
      <arg value="${jruby.test.dir}/test_all.rb"/>
    </java>
  </target>

Type “ant test” and away you go. Now you now longer have to slog through things with Java, and you’ve removed the compile phase from your test cycle. Bonus.

So thanks, Chris. That was a fine idea.


This is a free Wordpress template provided by Mathew Browne | Web Design | SEO