<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>Articles tagged java at null program</title>
  <link rel="alternate" type="text/html"
        href="https://nullprogram.com/tags/java/"/>
  <link rel="self" type="application/atom+xml"
        href="https://nullprogram.com/tags/java/feed/"/>
  <updated>2026-04-09T13:25:45Z</updated>
  <id>urn:uuid:8bee72c7-ad28-4fe4-b67d-ca24449a1c60</id>

  <author>
    <name>Christopher Wellons</name>
    <uri>https://nullprogram.com</uri>
    <email>wellons@nullprogram.com</email>
  </author>

  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Assertions should be more debugger-oriented</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2022/06/26/"/>
    <id>urn:uuid:22ae914c-971b-4cee-ba48-a189db1b6df6</id>
    <updated>2022-06-26T18:51:04Z</updated>
    <category term="c"/><category term="cpp"/><category term="go"/><category term="python"/><category term="java"/>
    <content type="html">
      <![CDATA[<p>Prompted by <a href="https://www.youtube.com/watch?v=r9eQth4Q5jg">a 20 minute video</a>, over the past month I’ve improved my
debugger skills. I’d shamefully acquired a bad habit: avoiding a debugger
until exhausting dumber, insufficient methods. My <em>first</em> choice should be
a debugger, but I had allowed a bit of friction to dissuade me. With some
thoughtful practice and deliberate effort clearing the path, my bad habit
is finally broken — at least when a good debugger is available. It feels
like I’ve leveled up and, <a href="/blog/2017/04/01/">like touch typing</a>, this was a skill I’d
neglected far too long. One friction point was the less-than-optimal
<code class="language-plaintext highlighter-rouge">assert</code> feature in basically every programming language implementation.
It ought to work better with debuggers.</p>

<p>An assertion verifies a program invariant, and so if one fails then
there’s undoubtedly a defect in the program. In other words, assertions
make programs more sensitive to defects, allowing problems to be caught
more quickly and accurately. Counter-intuitively, crashing early and often
makes for more robust and reliable software in the long run. For exactly
this reason, assertions go especially well with <a href="/blog/2019/01/25/">fuzzing</a>.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">assert</span><span class="p">(</span><span class="n">i</span> <span class="o">&gt;=</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">len</span><span class="p">);</span>   <span class="c1">// bounds check</span>
<span class="n">assert</span><span class="p">((</span><span class="kt">ssize_t</span><span class="p">)</span><span class="n">size</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">);</span>  <span class="c1">// suspicious size_t</span>
<span class="n">assert</span><span class="p">(</span><span class="n">cur</span><span class="o">-&gt;</span><span class="n">next</span> <span class="o">!=</span> <span class="n">cur</span><span class="p">);</span>    <span class="c1">// circular reference?</span>
</code></pre></div></div>

<p>They’re sometimes abused for error handling, which is a reason they’ve
also been (wrongfully) discouraged at times. For example, failing to open
a file is an error, not a defect, so an assertion is inappropriate.</p>

<p>Normal programs have implicit assertions all over, even if we don’t
usually think of them as assertions. In some cases they’re checked by the
hardware. Examples of implicit assertion failures:</p>

<ul>
  <li>Out-of-bounds indexing</li>
  <li>Dereferencing null/nil/None</li>
  <li>Dividing by zero</li>
  <li>Certain kinds of integer overflow (e.g. <code class="language-plaintext highlighter-rouge">-ftrapv</code>)</li>
</ul>

<p>Programs are generally not intended to recover from these situations
because, had they been anticipated, the invalid operation wouldn’t have
been attempted in the first place. The program simply crashes because
there’s no better alternative. Sanitizers, including Address Sanitizer
(ASan) and Undefined Behavior Sanitizer (UBSan), are in essence
additional, implicit assertions, checking invariants that aren’t normally
checked.</p>

<p>Ideally a failing assertion should have these two effects:</p>

<ul>
  <li>
    <p>Execution should <em>immediately</em> stop. The program is in an unknown state,
so it’s neither safe to “clean up” nor attempt to recover. Additional
execution will only make debugging more difficult, and may obscure the
defect.</p>
  </li>
  <li>
    <p>When run under a debugger — or visited as a core dump — it should break
exactly at the failed assertion, ready for inspection. I should not need
to dig around the call stack to figure out where the failure occurred. I
certainly shouldn’t need to manually set a breakpoint and restart the
program hoping to fail the assertion a second time. The whole reason for
using a debugger is to save time, so if it’s wasting my time then it’s
failing at its primary job.</p>
  </li>
</ul>

<p>I examined standard <code class="language-plaintext highlighter-rouge">assert</code> features across various language
implementations, and none strictly meet the criteria. Fortunately, in some
cases, it’s trivial to build a better assertion, and you can substitute
your own definition. First, let’s discuss the way assertions disappoint.</p>

<h3 id="a-test-assertion">A test assertion</h3>

<p>My test for C and C++ is minimal but establishes some state and gives me a
variable to inspect:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;assert.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">assert</span><span class="p">(</span><span class="n">i</span> <span class="o">&lt;</span> <span class="mi">5</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Then I compile and debug in the most straightforward way:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cc -g -o test test.c
$ gdb test
(gdb) r
(gdb) bt
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">r</code> in GDB stands for <code class="language-plaintext highlighter-rouge">run</code>, which immediately breaks because of the
<code class="language-plaintext highlighter-rouge">assert</code>. The <code class="language-plaintext highlighter-rouge">bt</code> prints a backtrace. On a typical Linux distribution
that shows this backtrace:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0  __GI_raise
#1  __GI_abort
#2  __assert_fail_base
#3  __GI___assert_fail
#4  main
</code></pre></div></div>

<p>Well, actually, it’s much messier than this, but I manually cleaned it up:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linu
x/raise.c:50
#1  0x00007ffff7df4537 in __GI_abort () at abort.c:79
#2  0x00007ffff7df440f in __assert_fail_base (fmt=0x7ffff7f5d
128 "%s%s%s:%u: %s%sAssertion `%s' failed.\n%n", assertion=0x
55555555600b "i &lt; 5", file=0x555555556004 "test.c", line=6, f
unction=&lt;optimized out&gt;) at assert.c:92
#3  0x00007ffff7e03662 in __GI___assert_fail (assertion=0x555
55555600b "i &lt; 5", file=0x555555556004 "test.c", line=6, func
tion=0x555555556011 &lt;__PRETTY_FUNCTION__.0&gt; "main") at assert
.c:101
#4  0x0000555555555178 in main () at test.c:6
</code></pre></div></div>

<p>That’s a lot to take in at a glance, and about 95% of it is noise that
will never contain useful information. Most notably, GDB didn’t stop at
the failing assertion. Instead there’s <em>four stack frames</em> of libc junk I
have to navigate before I can even begin debugging.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) up
(gdb) up
(gdb) up
(gdb) up
</code></pre></div></div>

<p>I must wade through this for every assertion failure. This is some of the
friction that made me avoid the debugger in the first place. glibc loves
indirection, so maybe the other libc implementations do better? How about
musl?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0  setjmp
#1  raise
#2  ??
#3  ??
#4  ??
#5  ??
#6  ??
#7  ??
#8  ??
#9  ??
#10 ??
#11 ??
</code></pre></div></div>

<p>Oops, without musl debugging symbols I can’t debug assertions at all
because GDB can’t read the stack, so it’s lost. If you’re on Alpine you
can install <code class="language-plaintext highlighter-rouge">musl-dbg</code>, but otherwise you’ll probably need to build your
own from source. With debugging symbols, musl is no better than glibc:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0  __restore_sigs
#1  raise
#2  abort
#3  __assert_fail
#4  main
</code></pre></div></div>

<p>Same with FreeBSD:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0  thr_kill
#1  in raise
#2  in abort
#3  __assert
#4  main
</code></pre></div></div>

<p>OpenBSD has one fewer frame:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0  thrkill
#1  _libc_abort
#2  _libc___assert2
#3  main
</code></pre></div></div>

<p>How about on Windows with Mingw-w64?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[Inferior 1 (process 7864) exited with code 03]
</code></pre></div></div>

<p>Oops, on Windows GDB doesn’t break at all on <code class="language-plaintext highlighter-rouge">assert</code>. You must first set
a breakpoint on <code class="language-plaintext highlighter-rouge">abort</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) b abort
</code></pre></div></div>

<p>Besides that, it’s the most straightforward so far:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0 msvcrt!abort
#1 msvcrt!_assert
#2 main
</code></pre></div></div>

<p>With MSVC (default CRT) I get something slightly different:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0 abort
#1 common_assert_to_stderr
#2 _wassert
#3 main
#4 __scrt_common_main_seh
</code></pre></div></div>

<p>RemedyBG leaves me at the <code class="language-plaintext highlighter-rouge">abort</code> like GDB does elsewhere. Visual Studio
recognizes that I don’t care about its stack frames and instead puts the
focus on the assertion, ready for debugging. The other stack frames are
there, but basically invisible. It’s the only case that practically meets
all my criteria!</p>

<p>I can’t entirely blame these implementations. The C standard requires that
<code class="language-plaintext highlighter-rouge">assert</code> print a diagnostic and call <code class="language-plaintext highlighter-rouge">abort</code>, and that <code class="language-plaintext highlighter-rouge">abort</code> raises
<code class="language-plaintext highlighter-rouge">SIGABRT</code>. There’s not much implementations can do, and it’s up to the
debugger to be smarter about it.</p>

<h3 id="sanitizers">Sanitizers</h3>

<p>ASan doesn’t break GDB on assertion failures, which is yet another source
of friction. You can work around this with an environment variable:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>export ASAN_OPTIONS=abort_on_error=1:print_legend=0
</code></pre></div></div>

<p>This works, but it’s the worst case of all: I get 7 junk stack frames on
top of the failed assertion. It’s also very noisy when it traps, so the
<code class="language-plaintext highlighter-rouge">print_legend=0</code> helps to cut it down a bit. I want this variable so often
that I set it in my shell’s <code class="language-plaintext highlighter-rouge">.profile</code> so that it’s always set.</p>

<p>With UBSan you can use <code class="language-plaintext highlighter-rouge">-fsanitize-undefined-trap-on-error</code>, which behaves
like the improved assertion. It traps directly on the defect with no junk
frames, though it prints no diagnostic. As a bonus, it also means you
don’t need to link <code class="language-plaintext highlighter-rouge">libubsan</code>. Thanks to the bonus, it fully supplants
<code class="language-plaintext highlighter-rouge">-ftrapv</code> for me on all platforms.</p>

<p><strong>Update November 2022</strong>: This “stop” hook eliminates ASan friction by
popping runtime frames — functions with the reserved <code class="language-plaintext highlighter-rouge">__</code> prefix — from
the call stack so that they’re not in the way when GDB takes control. It
requires Python support, which is the purpose of the feature-sniff outer
condition.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>if !$_isvoid($_any_caller_matches)
    define hook-stop
        while $_thread &amp;&amp; $_any_caller_matches("^__")
            up-silently
        end
    end
end
</code></pre></div></div>

<p>This is now part of my <code class="language-plaintext highlighter-rouge">.gdbinit</code>.</p>

<h3 id="a-better-assertion">A better assertion</h3>

<p>At least when under a debugger, here’s a much better assertion macro for
GCC and Clang:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#define assert(c) if (!(c)) __builtin_trap()
</span></code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">__builtin_trap</code> inserts a trap instruction — a built-in breakpoint. By
not calling a function to raise a signal, there are no junk stack frames
and no need to breakpoint on <code class="language-plaintext highlighter-rouge">abort</code>. It stops exactly where it should as
quickly as possible. This definition works reliably with GCC across all
platforms, too. On MSVC the equivalent is <code class="language-plaintext highlighter-rouge">__debugbreak</code>. If you’re really
in a pinch then do whatever it takes to trigger a fault, like
dereferencing a null pointer. A more complete definition might be:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#ifdef DEBUG
#  if __GNUC__
#    define assert(c) if (!(c)) __builtin_trap()
#  elif _MSC_VER
#    define assert(c) if (!(c)) __debugbreak()
#  else
#    define assert(c) if (!(c)) *(volatile int *)0 = 0
#  endif
#else
#  define assert(c)
#endif
</span></code></pre></div></div>

<p>None of these print a diagnostic, but that’s unnecessary when a debugger
is involved.</p>

<h3 id="other-languages">Other languages</h3>

<p>Unfortunately the situation <a href="https://github.com/rust-lang/rust/issues/21102">mostly gets worse</a> with other language
implementations, and it’s generally not possible to build a better
assertion. Assertions typically have exception-like semantics, if not
literally just another exception, and so they are far less reliable. If a
failed assertion raises an exception, then the program won’t stop until
it’s unwound the stack — running destructors and such along the way — all
the way to the top level looking for a handler. It only knows there’s a
problem when nobody was there to catch it.</p>

<p><a href="https://go.dev/doc/faq#assertions">Go officially doesn’t have assertions</a>, though panics are a kind of
assertion. However, panics have exception-like semantics, and so suffer
the problems of exceptions. A Go version of my test:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">func</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">defer</span> <span class="n">fmt</span><span class="o">.</span><span class="n">Println</span><span class="p">(</span><span class="s">"DEFER"</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">i</span> <span class="o">:=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="m">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span> <span class="p">{</span>
        <span class="k">if</span> <span class="n">i</span> <span class="o">&gt;=</span> <span class="m">5</span> <span class="p">{</span>
            <span class="nb">panic</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If I run this under Go’s premier debugger, <a href="https://github.com/go-delve/delve">Delve</a>, the unrecovered
panic causes it to break. So far so good. However, I get two junk frames:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#0 runtime.fatalpanic
#1 runtime.gopanic
#2 main.main
#3 runtime.main
#4 runtime.goexit
</code></pre></div></div>

<p>It only knows to stop because the Go runtime called <code class="language-plaintext highlighter-rouge">fatalpanic</code>, but the
backtrace is a fiction: The program continued to run after the panic,
enough to run all the registered defers (including printing “DEFER”),
unwinding the stack to the top level, and only then did it <code class="language-plaintext highlighter-rouge">fatalpanic</code>.
Fortunately it’s still possible to inspect all those stack frames even if
some variables may have changed while unwinding, but it’s more like
inspecting a core dump than a paused process.</p>

<p>The situation in Python is similar: <code class="language-plaintext highlighter-rouge">assert</code> raises AssertionError — a
plain old exception — and <code class="language-plaintext highlighter-rouge">pdb</code> won’t break until the stack has unwound,
exiting context managers and such. Only once the exception reaches the top
level does it enter “post mortem debugging,” like a core dump. At least
there are no junk stack frames on top. If you’re using asyncio then your
program may continue running for quite awhile before the right tasks are
scheduled and the exception finally propagates to the top level, if ever.</p>

<p>The worst offender of all is Java. First <code class="language-plaintext highlighter-rouge">jdb</code> never breaks for unhandled
exceptions. It’s up to you to set a breakpoint before the exception is
thrown. But it gets worse: assertions are disabled under <code class="language-plaintext highlighter-rouge">jdb</code>. The Java
<code class="language-plaintext highlighter-rouge">assert</code> statement is worse than useless.</p>

<h3 id="addendum-dont-exit-the-debugger">Addendum: Don’t exit the debugger</h3>

<p>The largest friction-reducing change I made is never exiting the debugger.
Previously I would enter GDB, run my program, exit, edit/rebuild, repeat.
However, there’s no reason to exit GDB! It automatically and reliably
reloads symbols and updates breakpoints on symbols. It remembers your run
configuration, so re-running is just <code class="language-plaintext highlighter-rouge">r</code> rather than interacting with
shell history.</p>

<p>My workflow on all platforms (<a href="/blog/2020/05/15/">including Windows</a>) is a vertically
maximized Vim window and a vertically maximized terminal window. The new
part for me: The terminal runs a long-term GDB session exclusively, with
<code class="language-plaintext highlighter-rouge">file</code> set to the program I’m writing, usually set by initial the command
line.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdb myprogram
gdb&gt;
</code></pre></div></div>

<p>Alternatively use <code class="language-plaintext highlighter-rouge">file</code> after starting GDB. Occasionally useful if my
project has multiple binaries, and I want to examine a different program.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; file myprogram
</code></pre></div></div>

<p>I use <code class="language-plaintext highlighter-rouge">make</code> and Vim’s <code class="language-plaintext highlighter-rouge">:mak</code> command for building from within the editor,
so I don’t need to change context to build. The quickfix list takes me
straight to warnings/errors. Often I’m writing something that takes input
from standard input. So I use the <code class="language-plaintext highlighter-rouge">run</code> (<code class="language-plaintext highlighter-rouge">r</code>) command to set this up
(along with any command line arguments).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; r &lt;test.txt
</code></pre></div></div>

<p>You can redirect standard output as well. It remembers these settings for
plain <code class="language-plaintext highlighter-rouge">run</code> later, so I can test my program by entering <code class="language-plaintext highlighter-rouge">r</code> and nothing
else.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; r
</code></pre></div></div>

<p>My usual workflow is edit, <code class="language-plaintext highlighter-rouge">:mak</code>, <code class="language-plaintext highlighter-rouge">r</code>, repeat. If I want to test a
different input or use different options, change the run configuration
using <code class="language-plaintext highlighter-rouge">run</code> again:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; r -a -b -c &lt;test2.txt
</code></pre></div></div>

<p>On Windows you cannot recompile while the program is running. If GDB is
sitting on a breakpoint but I want to build, use <code class="language-plaintext highlighter-rouge">kill</code> (<code class="language-plaintext highlighter-rouge">k</code>) to stop it
without exiting GDB.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; k
</code></pre></div></div>

<p>GDB has an annoying, flow-breaking yes/no prompt for this, so I recommend
<code class="language-plaintext highlighter-rouge">set confirm no</code> in your <code class="language-plaintext highlighter-rouge">.gdbinit</code> to disable it.</p>

<p>Sometimes a program is stuck in a loop and I need it to break in the
debugger. I try to avoid CTRL-C in the terminal it since it can confuse
GDB. A safer option is to signal the process from Vim with <code class="language-plaintext highlighter-rouge">pkill</code>, which
GDB will catch (except on Windows):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>:!pkill myprogram
</code></pre></div></div>

<p>I suspect many people don’t know this, but if you’re on Windows and
<a href="/blog/2021/03/11/">developing a graphical application</a>, you can <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey">press F12</a> in the
debuggee’s window to immediately break the program in the attached
debugger. This is a general platform feature and works with any native
debugger. I’ve been using it quite a lot.</p>

<p>On that note, you can run commands from GDB with <code class="language-plaintext highlighter-rouge">!</code>, which is another way
to avoid having an extra terminal window around:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; !git diff
</code></pre></div></div>

<p>In any case, GDB will re-read the binary on the next <code class="language-plaintext highlighter-rouge">run</code> and update
breakpoints, so it’s mostly seamless. If there’s a function I want to
debug, I set a breakpoint on it, then run.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; b somefunc
gdb&gt; r
</code></pre></div></div>

<p>Alternatively I’ll use a line number, which I read from Vim. Though GDB,
not being involved in the editing process, cannot track how that line
moves between builds.</p>

<p>An empty command repeats the last command, so once I’m at a breakpoint,
I’ll type <code class="language-plaintext highlighter-rouge">next</code> (<code class="language-plaintext highlighter-rouge">n</code>) — or <code class="language-plaintext highlighter-rouge">step</code> (<code class="language-plaintext highlighter-rouge">s</code>) to enter function calls — then
press enter each time I want to advance a line, often with my eye on the
context in Vim in the other window:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; n
gdb&gt;
gdb&gt;
</code></pre></div></div>

<p>(<del>I wish GDB could print a source listing around the breakpoint as
context, like Delve, but no such feature exists. The woeful <code class="language-plaintext highlighter-rouge">list</code> command
is inadequate.</del> <strong>Update</strong>: GDB’s TUI is a reasonable compromise for GUI
applications or terminal applications running under a separate tty/console
with either <code class="language-plaintext highlighter-rouge">tty</code> or <code class="language-plaintext highlighter-rouge">set new-console</code>. I can access it everywhere since
w64devkit now supports GDB TUI.)</p>

<p>If I want to advance to the next breakpoint, I use <code class="language-plaintext highlighter-rouge">continue</code> (<code class="language-plaintext highlighter-rouge">c</code>):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; c
</code></pre></div></div>

<p>If I’m walking through a loop, I want to see how variables change, but
it’s tedious to keep <code class="language-plaintext highlighter-rouge">print</code>ing (<code class="language-plaintext highlighter-rouge">p</code>) the same variables again and again.
So I use <code class="language-plaintext highlighter-rouge">display</code> (<code class="language-plaintext highlighter-rouge">disp</code>) to display an expression with each prompt,
much like the “watch” window in Visual Studio. For example, if my loop
variable is <code class="language-plaintext highlighter-rouge">i</code> over some string <code class="language-plaintext highlighter-rouge">str</code>, this will show me the current
character in character format (<code class="language-plaintext highlighter-rouge">/c</code>).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; disp/c str[i]
</code></pre></div></div>

<p>You can accumulate multiple expressions. Use <code class="language-plaintext highlighter-rouge">undisplay</code> to remove them.</p>

<p>Too many breakpoints? Use <code class="language-plaintext highlighter-rouge">info breakpoints</code> (<code class="language-plaintext highlighter-rouge">i b</code>) to list them, then
<code class="language-plaintext highlighter-rouge">delete</code> (<code class="language-plaintext highlighter-rouge">d</code>) the unwanted ones by ID.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gdb&gt; i b
gdb&gt; d 3 5 8
</code></pre></div></div>

<p>GDB has many more feature than this, but 10 commands cover 99% of use
cases: <code class="language-plaintext highlighter-rouge">r</code>, <code class="language-plaintext highlighter-rouge">c</code>, <code class="language-plaintext highlighter-rouge">n</code>, <code class="language-plaintext highlighter-rouge">s</code>, <code class="language-plaintext highlighter-rouge">disp</code>, <code class="language-plaintext highlighter-rouge">k</code>, <code class="language-plaintext highlighter-rouge">b</code>, <code class="language-plaintext highlighter-rouge">i</code>, <code class="language-plaintext highlighter-rouge">d</code>, <code class="language-plaintext highlighter-rouge">p</code>.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>The cost of Java's EnumSet</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2021/04/23/"/>
    <id>urn:uuid:ae95c24d-ab40-4f5f-a375-3e4c1ee58c27</id>
    <updated>2021-04-23T21:20:53Z</updated>
    <category term="java"/>
    <content type="html">
      <![CDATA[<p>It’s been about a decade since I last worked in Java and much has changed.
I thought I’d brush up by re-reading <em>Effective Java</em> by Joshua Bloch
which has since received a new edition. It was once my guiding star for
Java. However, after an additional decade of experience in a variety of
languages and platforms, this book frequently made me shake my head. I
strongly disagreed with 20% of <a href="https://github.com/nicolasmanic/effective-java-in-a-nutshell">its items</a>. One conflicting
topic was enumerations, particularly item 36: “Use EnumSet instead of bit
fields.”</p>

<p>This is not to say Bloch is necessarily wrong to make this recommendation,
or any of the others I don’t like. The book is conservative, playing it
safe by always erring on the side of Java idiom whether or not it makes
sense. The problem lies in Java idiom more than the book. To write your
Java like everyone else, do exactly as the book says. When in Rome, do as
the Romans do.</p>

<p>On the other hand, EnumSet is perhaps the most pointless class in the Java
standard library. It has two goals, but fails at both.</p>

<h3 id="background">Background</h3>

<p>Back in the old days Java programmers would build enumerations much like C
programmers. For example, here’s a C-style bitfield enumeration (these
Romans <em>love</em> their keywords):</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">Color</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">R</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">0</span><span class="o">;</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">G</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">1</span><span class="o">;</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">B</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">2</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<p>To build a <em>set</em> of these items, use the OR (<code class="language-plaintext highlighter-rouge">|</code>) operator, just like C:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="n">purple</span> <span class="o">=</span> <span class="nc">Color</span><span class="o">.</span><span class="na">R</span> <span class="o">|</span> <span class="nc">Color</span><span class="o">.</span><span class="na">B</span><span class="o">;</span>
</code></pre></div></div>

<p>The downside is lack of type safety. These are plain old integers, not a
dedicated type, and getting your integers and bitfields crossed won’t be
checked by the compiler. To solve this, early Java gained an enumeration
reference type:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="nc">Color</span> <span class="o">{</span> <span class="no">R</span><span class="o">,</span> <span class="no">G</span><span class="o">,</span> <span class="no">B</span> <span class="o">}</span>
</code></pre></div></div>

<p>Thankfully this is only slightly more verbose than the same syntax for a C
enumeration. While it would have been useful, these types don’t support
the OR operator. Instead you’re supposed to build a Set. Romans also love
ceremony:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Set</span><span class="o">&lt;</span><span class="nc">Color</span><span class="o">&gt;</span> <span class="n">purple</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashSet</span><span class="o">&lt;&gt;(</span><span class="nc">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="nc">Color</span><span class="o">.</span><span class="na">R</span><span class="o">,</span> <span class="nc">Color</span><span class="o">.</span><span class="na">B</span><span class="o">));</span>
</code></pre></div></div>

<p>As you might guess, compared to the original integer operation, this
HashSet is incredibly slow and inefficient. The type safety comes at a
serious cost. Attempting to mitigate this, Java provides a special Set
implementation for enumerations:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Set</span><span class="o">&lt;</span><span class="nc">Color</span><span class="o">&gt;</span> <span class="n">purple</span> <span class="o">=</span> <span class="nc">EnumSet</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="nc">Color</span><span class="o">.</span><span class="na">R</span><span class="o">,</span> <span class="nc">Color</span><span class="o">.</span><span class="na">B</span><span class="o">);</span>
</code></pre></div></div>

<p>Not as syntactically lean as the OR operator, but less ceremony and more
efficient than a HashSet. The efficiency comes from using a bitfield
internally just like the original pre-enumeration example. <em>But how much
more efficient is it?</em></p>

<h3 id="benchmarks">Benchmarks</h3>

<p>The original C-style bitfield was a primitive <code class="language-plaintext highlighter-rouge">int</code>: fast, efficient, no
allocations, and easy to optimize. Except for the lack of type safety it’s
essentially the best possible case. Since an EnumSet uses a bitfield
internally, isn’t it basically the same? Unfortunately not.</p>

<p>An EnumSet is a reference type, not a primitive, so creating an EnumSet
requires:</p>

<ul>
  <li>Memory allocation</li>
  <li>Running a constructor</li>
  <li>Run-time construction</li>
  <li>Reflection</li>
</ul>

<p>It’s the essence of <a href="https://www.youtube.com/watch?v=f4ioc8-lDc0&amp;t=4407s"><strong>individual element thinking</strong></a>. There’s little
reason to think an EnumSet is going to be efficient.</p>

<p>Wanting to get a feel for the relative costs, I put together some crude
benchmarks. In the benchmark I construct a set of values, then construct
the same set many more times and compare it to the original set. Here’s
the EnumSet benchmark:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">enum</span> <span class="nc">Flag</span> <span class="o">{</span> <span class="no">A</span><span class="o">,</span> <span class="no">B</span><span class="o">,</span> <span class="no">C</span><span class="o">,</span> <span class="no">D</span><span class="o">,</span> <span class="no">E</span><span class="o">,</span> <span class="no">F</span><span class="o">,</span> <span class="no">G</span> <span class="o">}</span>

<span class="c1">// ...</span>

<span class="kd">static</span> <span class="kt">void</span> <span class="nf">benchmarkEnumSet</span><span class="o">()</span> <span class="o">{</span>
    <span class="nc">System</span><span class="o">.</span><span class="na">gc</span><span class="o">();</span>
    <span class="kt">long</span> <span class="n">beg</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">nanoTime</span><span class="o">();</span>
    <span class="nc">Set</span><span class="o">&lt;</span><span class="nc">Flag</span><span class="o">&gt;</span> <span class="n">a</span> <span class="o">=</span> <span class="nc">EnumSet</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="nc">Flag</span><span class="o">.</span><span class="na">A</span><span class="o">,</span> <span class="nc">Flag</span><span class="o">.</span><span class="na">B</span><span class="o">,</span> <span class="nc">Flag</span><span class="o">.</span><span class="na">G</span><span class="o">);</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1_000_000_000</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="nc">Set</span><span class="o">&lt;</span><span class="nc">Flag</span><span class="o">&gt;</span> <span class="n">b</span> <span class="o">=</span> <span class="nc">EnumSet</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="nc">Flag</span><span class="o">.</span><span class="na">A</span><span class="o">,</span> <span class="nc">Flag</span><span class="o">.</span><span class="na">B</span><span class="o">,</span> <span class="nc">Flag</span><span class="o">.</span><span class="na">G</span><span class="o">);</span>
        <span class="k">assert</span> <span class="n">a</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">b</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="kt">long</span> <span class="n">end</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">nanoTime</span><span class="o">();</span>
    <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"EnumSet\t"</span> <span class="o">+</span> <span class="o">(</span><span class="n">end</span> <span class="o">-</span> <span class="n">beg</span><span class="o">)/</span><span class="mi">1</span><span class="n">e9</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>A benchmark for a classical bitfield:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">A</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">0</span><span class="o">;</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">B</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">1</span><span class="o">;</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">C</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">2</span><span class="o">;</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">D</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">3</span><span class="o">;</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">E</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">4</span><span class="o">;</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">F</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">5</span><span class="o">;</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">G</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">6</span><span class="o">;</span>

<span class="c1">// ...</span>

<span class="kd">static</span> <span class="kt">void</span> <span class="nf">benchmarkBitfield</span><span class="o">()</span> <span class="o">{</span>
    <span class="nc">System</span><span class="o">.</span><span class="na">gc</span><span class="o">();</span>
    <span class="kt">long</span> <span class="n">beg</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">nanoTime</span><span class="o">();</span>
    <span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="no">A</span> <span class="o">|</span> <span class="no">B</span> <span class="o">|</span> <span class="no">G</span><span class="o">;</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1_000_000_000</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="kt">int</span> <span class="n">b</span> <span class="o">=</span> <span class="no">A</span> <span class="o">|</span> <span class="no">B</span> <span class="o">|</span> <span class="no">G</span><span class="o">;</span>
        <span class="k">assert</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span><span class="o">;</span>
    <span class="o">}</span>
    <span class="kt">long</span> <span class="n">end</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">nanoTime</span><span class="o">();</span>
    <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"bitfield\t"</span> <span class="o">+</span> <span class="o">(</span><span class="n">end</span> <span class="o">-</span> <span class="n">beg</span><span class="o">)/</span><span class="mi">1</span><span class="n">e9</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>There’s also a HashSet benchmark, but it’s just a slight variation of the
EnumSet benchmark so I won’t show it here. Due to JIT warm-up costs, the
benchmark runs three times in a row in the same process (<code class="language-plaintext highlighter-rouge">for</code> loop). The
<code class="language-plaintext highlighter-rouge">-ea</code> option enables the assertions in the test:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>java -ea Benchmark
</code></pre></div></div>

<p>Full source: <a href="https://gist.github.com/skeeto/db52f44f99f94b222f35e2a771da3a71">Benchmark.java</a></p>

<p>The results on x86-64 Debian Buster with its OpenJDK 11 (the most recent
long-term support release of OpenJDK):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>HashSet    104.486260884
EnumSet      3.900099588
bitfield     0.003371834

HashSet    109.827488593
EnumSet      3.484818891
bitfield     0.003430366

HashSet    107.106317379
EnumSet      3.742689517
bitield      0.000000057
</code></pre></div></div>

<p>An EnumSet is two orders of magnitude faster than a HashSet. This sounds
pretty good until the next result: At their worst, bitfields are <em>three
orders of magnitude</em> faster than an EnumSet.</p>

<p>What’s even more interesting is that third run. It looks like a benchmark
failure, and in another context I might agree. Obviously the JIT compiler
wised up and optimized away the entire benchmark. Normally this is a
useless result, but it’s telling in contrast with the other two
benchmarks. The compiler failed to realize this same optimization with
both the HashSet and EnumSet benchmarks. <strong>Once warmed up, bitfields are
<em>more than</em> 1000x faster</strong> because they won’t inhibit optimizations.</p>

<h3 id="two-goals">Two goals</h3>

<p>So what’s the point of an EnumSet? I mentioned that it doesn’t accomplish
either of its two goals.</p>

<ol>
  <li>A bitfield lacks type safety. A Set (via generics) does not.</li>
  <li>The usual Set implementation, HashSet, is far less efficient than a
bitfield. An EnumSet attempts to bring this back in line with a
bitfield.</li>
</ol>

<p>An EnumSet is unnecessary for type safety since that’s already a property
of Set. We already have a more general Set implementation: HashSet.
Relative to a bitfield, an EnumSet isn’t meaningfully faster than a
HashSet. A hare isn’t meaningfully faster than a turtle in the context of
rockets.</p>

<p>The usual argument against bitfields is that “speed isn’t important” or
that it’s “premature optimization.” If that’s true, then what was wrong
with a HashSet? If speed <em>is</em> important, then you use a bitfield. Where’s
the need for an EnumSet? It’s extra API surface area for a non-existent
use case.</p>

<p>It’s also at odds with “Item 6: Avoid creating unnecessary objects.”
Unlike a Set, a bitfield is a primitive and doesn’t create an object. Per
the benchmark, the type safety of a Set comes at a high cost. The C
programmer within me cringes at that cost even where it truly doesn’t
matter.</p>

<p>This isn’t to say you should change the way you write Java. This is a
criticism of the ecosystem — its design and idioms — and one of the (many)
reasons why I haven’t missed it.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>On-the-fly Linear Congruential Generator Using Emacs Calc</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2019/11/19/"/>
    <id>urn:uuid:13e56720-ef3a-4fa4-a4ff-0a6fef914504</id>
    <updated>2019-11-19T01:17:50Z</updated>
    <category term="emacs"/><category term="crypto"/><category term="optimization"/><category term="c"/><category term="java"/><category term="javascript"/>
    <content type="html">
      <![CDATA[<p>I regularly make throwaway “projects” and do a surprising amount of
programming in <code class="language-plaintext highlighter-rouge">/tmp</code>. For Emacs Lisp, the equivalent is the
<code class="language-plaintext highlighter-rouge">*scratch*</code> buffer. These are places where I can make a mess, and the
mess usually gets cleaned up before it becomes a problem. A lot of my
established projects (<a href="/blog/2019/03/22/">ex</a>.) start out in volatile storage and
only graduate to more permanent storage once the concept has proven
itself.</p>

<p>Throughout my whole career, this sort of throwaway experimentation has
been an important part of my personal growth, and I try to <a href="/blog/2016/09/02/">encourage it
in others</a>. Even if the idea I’m trying doesn’t pan out, I usually
learn something new, and occasionally it translates into an article here.</p>

<p>I also enjoy small programming challenges. One of the most abused
tools in my mental toolbox is the Monte Carlo method, and I readily
apply it to solve toy problems. Even beyond this, random number
generators are frequently a useful tool (<a href="/blog/2017/04/27/">1</a>, <a href="/blog/2019/07/22/">2</a>), so I
find myself reaching for one all the time.</p>

<p>Nearly every programming language comes with a pseudo-random number
generation function or library. Unfortunately the language’s standard
PRNG is usually a poor choice (C, <a href="https://arvid.io/2018/06/30/on-cxx-random-number-generator-quality/">C++</a>, <a href="https://lowleveldesign.org/2018/08/15/randomness-in-net/">C#</a>, <a href="https://grokbase.com/t/gg/golang-nuts/155f6kbb7a/go-nuts-why-are-high-bits-used-by-math-rand-helpers-instead-of-low-ones">Go</a>).
It’s probably mediocre quality, <a href="/blog/2018/05/27/">slower than it needs to be</a>
(<a href="https://grokbase.com/t/gg/golang-nuts/155f6kbb7a/go-nuts-why-are-high-bits-used-by-math-rand-helpers-instead-of-low-ones">also</a>), <a href="https://lists.freebsd.org/pipermail/svn-src-head/2013-July/049068.html">lacks reliable semantics or behavior between
implementations</a>, or is missing some other property I want. So I’ve
long been a fan of <em>BYOPRNG:</em> Bring Your Own Pseudo-random Number
Generator. Just embed a generator with the desired properties directly
into the program. The <a href="/blog/2017/09/21/">best non-cryptographic PRNGs today</a> are
tiny and exceptionally friendly to embedding. Though, depending on what
you’re doing, you might <a href="/blog/2019/04/30/">need to be creative about seeding</a>.</p>

<h3 id="crafting-a-prng">Crafting a PRNG</h3>

<p>On occasion I don’t have an established, embeddable PRNG in reach, and
I have yet to commit xoshiro256** to memory. Or maybe I want to use
a totally unique PRNG for a particular project. In these cases I make
one up. With just a bit of know-how it’s not too difficult.</p>

<p>Probably the easiest decent PRNG to code from scratch is the venerable
<a href="https://en.wikipedia.org/wiki/Linear_congruential_generator">Linear Congruential Generator</a> (LCG). It’s a simple recurrence
relation:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>x[1] = (x[0] * A + C) % M
</code></pre></div></div>

<p>That’s trivial to remember once you know the details. You only need to
choose appropriate values for <code class="language-plaintext highlighter-rouge">A</code>, <code class="language-plaintext highlighter-rouge">C</code>, and <code class="language-plaintext highlighter-rouge">M</code>. Done correctly, it
will be a <em>full-period</em> generator — a generator that visits a
permutation of each of the numbers between 0 and <code class="language-plaintext highlighter-rouge">M - 1</code>. The seed —
the value of <code class="language-plaintext highlighter-rouge">x[0]</code> — is chooses a starting position in this (looping)
permutation.</p>

<p><code class="language-plaintext highlighter-rouge">M</code> has a natural, obvious choice: a power of two matching the range of
operands, such as 2^32 or 2^64. With this the modulo operation is free
as a natural side effect of the computer architecture.</p>

<p>Choosing <code class="language-plaintext highlighter-rouge">C</code> also isn’t difficult. It must be co-prime with <code class="language-plaintext highlighter-rouge">M</code>, and
since <code class="language-plaintext highlighter-rouge">M</code> is a power of two, any odd number is valid. Even 1. In
theory choosing a small value like 1 is faster since the compiler
won’t need to embed a large integer in the code, but this difference
doesn’t show up in any micro-benchmarks I tried. If you want a cool,
unique generator, then choose a large random integer. More on that
below.</p>

<p>The tricky value is <code class="language-plaintext highlighter-rouge">A</code>, and getting it right is the linchpin of the
whole LCG. It must be coprime with <code class="language-plaintext highlighter-rouge">M</code> (i.e. not even), and, for a
full-period generator, <code class="language-plaintext highlighter-rouge">A-1</code> must be divisible by four. For better
results, <code class="language-plaintext highlighter-rouge">A-1</code> should not be divisible by 8. A good choice is a prime
number that satisfies these properties.</p>

<p>If your operands are 64-bit integers, or larger, how are you going to
generate a prime number?</p>

<h4 id="primes-from-emacs-calc">Primes from Emacs Calc</h4>

<p>Emacs Calc can solve this problem. I’ve <a href="/blog/2009/06/23/">noted before</a> how
featureful it is. It has arbitrary precision, random number
generation, and primality testing. It’s everything we need to choose
<code class="language-plaintext highlighter-rouge">A</code>. (In fact, this is nearly identical to <a href="/blog/2015/10/30/">the process I used to
implement RSA</a>.) For this example I’m going to generate a 64-bit
LCG for the C programming language, but it’s easy to use whatever
width you like and mostly whatever language you like. If you wanted a
<a href="http://www.pcg-random.org/posts/does-it-beat-the-minimal-standard.html">minimal standard 128-bit LCG</a>, this will still work.</p>

<p>Start by opening up Calc with <code class="language-plaintext highlighter-rouge">M-x calc</code>, then:</p>

<ol>
  <li>Push <code class="language-plaintext highlighter-rouge">2</code> on the stack</li>
  <li>Push <code class="language-plaintext highlighter-rouge">64</code> on the stack</li>
  <li>Press <code class="language-plaintext highlighter-rouge">^</code>, computing 2^64 and pushing it on the stack</li>
  <li>Press <code class="language-plaintext highlighter-rouge">k r</code> to generate a random number in this range</li>
  <li>Press <code class="language-plaintext highlighter-rouge">d r 16</code> to switch to hexadecimal display</li>
  <li>Press <code class="language-plaintext highlighter-rouge">k n</code> to find the next prime following the random value</li>
  <li>Repeat step 6 until you get a number that ends with <code class="language-plaintext highlighter-rouge">5</code> or <code class="language-plaintext highlighter-rouge">D</code></li>
  <li>Press <code class="language-plaintext highlighter-rouge">k p</code> a few times to avoid false positives.</li>
</ol>

<p>What’s left on the stack is your <code class="language-plaintext highlighter-rouge">A</code>! If you want a random value for
<code class="language-plaintext highlighter-rouge">C</code>, you can follow a similar process. Heck, make it prime, too!</p>

<p>The reason for using hexadecimal (step 5) and looking for <code class="language-plaintext highlighter-rouge">5</code> or <code class="language-plaintext highlighter-rouge">D</code>
(step 7) is that such numbers satisfy both of the important properties
for <code class="language-plaintext highlighter-rouge">A-1</code>.</p>

<p>Calc doesn’t try to factor your random integer. Instead it uses the
<a href="https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test">Miller–Rabin primality test</a>, a probabilistic test that, itself,
requires random numbers. It has false positives but no false negatives.
The false positives can be mitigated by repeating the test multiple
times, hence step 8.</p>

<p>Trying this all out right now, I got this implementation (in C):</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">uint64_t</span> <span class="nf">lcg1</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="kt">uint64_t</span> <span class="n">s</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">*</span><span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x7c3c3267d015ceb5</span><span class="p">)</span> <span class="o">+</span> <span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x24bd2d95276253a9</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">s</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>However, we can still do a little better. Outputting the entire state
doesn’t have great results, so instead it’s better to create a
<em>truncated</em> LCG and only return some portion of the most significant
bits.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">uint32_t</span> <span class="nf">lcg2</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="kt">uint64_t</span> <span class="n">s</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">*</span><span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x7c3c3267d015ceb5</span><span class="p">)</span> <span class="o">+</span> <span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x24bd2d95276253a9</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">s</span> <span class="o">&gt;&gt;</span> <span class="mi">32</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This won’t quite pass <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">BigCrush</a> in 64-bit form, but the results
are pretty reasonable for most purposes.</p>

<p>But we can still do better without needing to remember much more than
this.</p>

<h3 id="appending-permutation">Appending permutation</h3>

<p>A <a href="http://www.pcg-random.org/">Permuted Congruential Generator</a> (PCG) is really just a
truncated LCG with a permutation applied to its output. Like LCGs
themselves, there are arbitrarily many variations. The “official”
implementation has a <a href="/blog/2018/02/07/">data-dependent shift</a>, for which I can
never remember the details. Fortunately a couple of simple, easy to
remember transformations is sufficient. Basically anything I used
<a href="/blog/2018/07/31/">while prospecting for hash functions</a>. I love xorshifts, so
lets add one of those:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">uint32_t</span> <span class="nf">pcg1</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="kt">uint64_t</span> <span class="n">s</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">*</span><span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x7c3c3267d015ceb5</span><span class="p">)</span> <span class="o">+</span> <span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x24bd2d95276253a9</span><span class="p">);</span>
    <span class="kt">uint32_t</span> <span class="n">r</span> <span class="o">=</span> <span class="n">s</span> <span class="o">&gt;&gt;</span> <span class="mi">32</span><span class="p">;</span>
    <span class="n">r</span> <span class="o">^=</span> <span class="n">r</span> <span class="o">&gt;&gt;</span> <span class="mi">16</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">r</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This is a big improvement, but it still fails one BigCrush test. As
they say, when xorshift isn’t enough, use xorshift-multiply! Below I
generated a 32-bit prime for the multiply, but any odd integer is a
valid permutation.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">uint32_t</span> <span class="nf">pcg2</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="kt">uint64_t</span> <span class="n">s</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">*</span><span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x7c3c3267d015ceb5</span><span class="p">)</span> <span class="o">+</span> <span class="n">UINT64_C</span><span class="p">(</span><span class="mh">0x24bd2d95276253a9</span><span class="p">);</span>
    <span class="kt">uint32_t</span> <span class="n">r</span> <span class="o">=</span> <span class="n">s</span> <span class="o">&gt;&gt;</span> <span class="mi">32</span><span class="p">;</span>
    <span class="n">r</span> <span class="o">^=</span> <span class="n">r</span> <span class="o">&gt;&gt;</span> <span class="mi">16</span><span class="p">;</span>
    <span class="n">r</span> <span class="o">*=</span> <span class="n">UINT32_C</span><span class="p">(</span><span class="mh">0x60857ba9</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">r</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This passes BigCrush, and I can reliably build a new one entirely from
scratch using Calc any time I need it.</p>

<h3 id="bonus-adapting-to-other-languages">Bonus: Adapting to other languages</h3>

<p>Sometimes it’s not so straightforward to adapt this technique to other
languages. For example, JavaScript has limited support for 32-bit
integer operations (enough for a poor 32-bit LCG) and no 64-bit
integer operations. Though <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt">BigInt</a> is now a thing, and should
make a great 96- or 128-bit LCG easy to build.</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">lcg</span><span class="p">(</span><span class="nx">seed</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">let</span> <span class="nx">s</span> <span class="o">=</span> <span class="nx">BigInt</span><span class="p">(</span><span class="nx">seed</span><span class="p">);</span>
    <span class="k">return</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="nx">s</span> <span class="o">*=</span> <span class="mh">0xef725caa331524261b9646cd</span><span class="nx">n</span><span class="p">;</span>
        <span class="nx">s</span> <span class="o">+=</span> <span class="mh">0x213734f2c0c27c292d814385</span><span class="nx">n</span><span class="p">;</span>
        <span class="nx">s</span> <span class="o">&amp;=</span> <span class="mh">0xffffffffffffffffffffffff</span><span class="nx">n</span><span class="p">;</span>
        <span class="k">return</span> <span class="nb">Number</span><span class="p">(</span><span class="nx">s</span> <span class="o">&gt;&gt;</span> <span class="mi">64</span><span class="nx">n</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Java doesn’t have unsigned integers, so how could you build the above
PCG in Java? Easy! First, remember is that Java has two’s complement
semantics, including wrap around, and that two’s complement doesn’t
care about unsigned or signed for multiplication (or addition, or
subtraction). The result is identical. Second, the oft-forgotten <code class="language-plaintext highlighter-rouge">&gt;&gt;&gt;</code>
operator does an unsigned right shift. With these two tips:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">long</span> <span class="n">s</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

<span class="kt">int</span> <span class="nf">pcg2</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">*</span><span class="mh">0x7c3c3267d015ceb5</span><span class="no">L</span> <span class="o">+</span> <span class="mh">0x24bd2d95276253a9</span><span class="no">L</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">r</span> <span class="o">=</span> <span class="o">(</span><span class="kt">int</span><span class="o">)(</span><span class="n">s</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">32</span><span class="o">);</span>
    <span class="n">r</span> <span class="o">^=</span> <span class="n">r</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">16</span><span class="o">;</span>
    <span class="n">r</span> <span class="o">*=</span> <span class="mh">0x60857ba9</span><span class="o">;</span>
    <span class="k">return</span> <span class="n">r</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<p>So, in addition to the Calc step list above, you may need to know some
of the finer details of your target language.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Duck Typing vs. Type Erasure</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2014/04/01/"/>
    <id>urn:uuid:d01a1d2e-2752-35f4-949a-ff69d7f78e22</id>
    <updated>2014-04-01T21:07:31Z</updated>
    <category term="java"/><category term="cpp"/><category term="lang"/><category term="compsci"/>
    <content type="html">
      <![CDATA[<p>Consider the following C++ class.</p>

<div class="language-c++ highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span>
<span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span>
<span class="k">struct</span> <span class="nc">Caller</span> <span class="p">{</span>
  <span class="k">const</span> <span class="n">T</span> <span class="n">callee_</span><span class="p">;</span>
  <span class="n">Caller</span><span class="p">(</span><span class="k">const</span> <span class="n">T</span> <span class="n">callee</span><span class="p">)</span> <span class="o">:</span> <span class="n">callee_</span><span class="p">(</span><span class="n">callee</span><span class="p">)</span> <span class="p">{}</span>
  <span class="kt">void</span> <span class="n">go</span><span class="p">()</span> <span class="p">{</span> <span class="n">callee_</span><span class="p">.</span><span class="n">call</span><span class="p">();</span> <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Caller can be parameterized to <em>any</em> type so long as it has a <code class="language-plaintext highlighter-rouge">call()</code>
method. For example, introduce two types, Foo and Bar.</p>

<div class="language-c++ highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="nc">Foo</span> <span class="p">{</span>
  <span class="kt">void</span> <span class="n">call</span><span class="p">()</span> <span class="k">const</span> <span class="p">{</span> <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"Foo"</span><span class="p">;</span> <span class="p">}</span>
<span class="p">};</span>

<span class="k">struct</span> <span class="nc">Bar</span> <span class="p">{</span>
  <span class="kt">void</span> <span class="n">call</span><span class="p">()</span> <span class="k">const</span> <span class="p">{</span> <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"Bar"</span><span class="p">;</span> <span class="p">}</span>
<span class="p">};</span>

<span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Caller</span><span class="o">&lt;</span><span class="n">Foo</span><span class="o">&gt;</span> <span class="n">foo</span><span class="p">{</span><span class="n">Foo</span><span class="p">()};</span>
  <span class="n">Caller</span><span class="o">&lt;</span><span class="n">Bar</span><span class="o">&gt;</span> <span class="n">bar</span><span class="p">{</span><span class="n">Bar</span><span class="p">()};</span>
  <span class="n">foo</span><span class="p">.</span><span class="n">go</span><span class="p">();</span>
  <span class="n">bar</span><span class="p">.</span><span class="n">go</span><span class="p">();</span>
  <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This code compiles cleanly and, when run, emits “FooBar”. This is an
example of <em>duck typing</em> — i.e., “If it looks like a duck, swims like
a duck, and quacks like a duck, then it probably is a duck.” Foo and
Bar are unrelated types. They have no common inheritance, but by
providing the expected interface, they both work with with Caller.
This is a special case of <em>polymorphism</em>.</p>

<p>Duck typing is normally only found in dynamically typed languages.
Thanks to templates, a statically, strongly typed language like C++
can have duck typing without sacrificing any type safety.</p>

<h3 id="java-duck-typing">Java Duck Typing</h3>

<p>Let’s try the same thing in Java using generics.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Caller</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="kd">final</span> <span class="no">T</span> <span class="n">callee</span><span class="o">;</span>
    <span class="nc">Caller</span><span class="o">(</span><span class="no">T</span> <span class="n">callee</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">callee</span> <span class="o">=</span> <span class="n">callee</span><span class="o">;</span>
    <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">go</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">callee</span><span class="o">.</span><span class="na">call</span><span class="o">();</span>  <span class="c1">// compiler error: cannot find symbol call</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">Foo</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">call</span><span class="o">()</span> <span class="o">{</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="s">"Foo"</span><span class="o">);</span> <span class="o">}</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">Bar</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">call</span><span class="o">()</span> <span class="o">{</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="s">"Bar"</span><span class="o">);</span> <span class="o">}</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span> <span class="n">args</span><span class="o">[])</span> <span class="o">{</span>
        <span class="nc">Caller</span><span class="o">&lt;</span><span class="nc">Foo</span><span class="o">&gt;</span> <span class="n">f</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Caller</span><span class="o">&lt;&gt;(</span><span class="k">new</span> <span class="nc">Foo</span><span class="o">());</span>
        <span class="nc">Caller</span><span class="o">&lt;</span><span class="nc">Bar</span><span class="o">&gt;</span> <span class="n">b</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Caller</span><span class="o">&lt;&gt;(</span><span class="k">new</span> <span class="nc">Bar</span><span class="o">());</span>
        <span class="n">f</span><span class="o">.</span><span class="na">go</span><span class="o">();</span>
        <span class="n">b</span><span class="o">.</span><span class="na">go</span><span class="o">();</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The program is practically identical, but this will fail with a
compile-time error. This is the result of <em>type erasure</em>. Unlike C++’s
templates, there will only ever be one compiled version of Caller, and
T will become Object. Since Object has no <code class="language-plaintext highlighter-rouge">call()</code> method, compilation
fails. The generic type is only for enabling additional compiler
checks later on.</p>

<p>C++ templates behave like a macros, expanded by the compiler once for
each different type of applied parameter. The <code class="language-plaintext highlighter-rouge">call</code> symbol is looked
up later, after the type has been fully realized, not when the
template is defined.</p>

<p>To fix this, Foo and Bar need a common ancestry. Let’s make this
<code class="language-plaintext highlighter-rouge">Callee</code>.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">interface</span> <span class="nc">Callee</span> <span class="o">{</span>
    <span class="kt">void</span> <span class="nf">call</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Caller needs to be redefined such that T is a subclass of Callee.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Caller</span><span class="o">&lt;</span><span class="no">T</span> <span class="kd">extends</span> <span class="nc">Callee</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<p>This now compiles cleanly because <code class="language-plaintext highlighter-rouge">call()</code> will be found in <code class="language-plaintext highlighter-rouge">Callee</code>.
Finally, implement Callee.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Foo</span> <span class="kd">implements</span> <span class="nc">Callee</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">Bar</span> <span class="kd">implements</span> <span class="nc">Callee</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<p>This is no longer duck typing, just plain old polymorphism. Type
erasure prohibits duck typing in Java (outside of dirty reflection
hacks).</p>

<h3 id="signals-and-slots-and-events-oh-my">Signals and Slots and Events! Oh My!</h3>

<p>Duck typing is useful for implementing the observer pattern without as
much boilerplate. A class can participate in the observer pattern
without <a href="http://raganwald.com/2014/03/31/class-hierarchies-dont-do-that.html">inheriting from some specialized class</a> or interface.
For example, see <a href="http://en.wikipedia.org/wiki/Signals_and_slots">the various signal and slots systems for C++</a>.
In constrast, Java <a href="http://docs.oracle.com/javase/7/docs/api/java/util/EventListener.html">has an EventListener type for everything</a>:</p>

<ul>
  <li>KeyListener</li>
  <li>MouseListener</li>
  <li>MouseMotionListener</li>
  <li>FocusListener</li>
  <li>ActionListener, etc.</li>
</ul>

<p>A class concerned with many different kinds of events, such as an
event logger, would need to inherit a large number of interfaces.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>My Grading Process</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2013/10/13/"/>
    <id>urn:uuid:8c5aecd0-c7f0-314d-d4a8-88014a195e08</id>
    <updated>2013-10-13T02:56:31Z</updated>
    <category term="java"/><category term="rant"/><category term="reddit"/>
    <content type="html">
      <![CDATA[<p>My GitHub activity, including this blog, has really slowed down for
the past month because I’ve spent a lot of free time grading homework
for a <a href="http://apps.ep.jhu.edu/courses/605/707">design patterns class</a>, taught by a colleague at the
<a href="http://engineering.jhu.edu/">Whiting School of Engineering</a>. Conveniently for me, all of my
interaction with the students is through e-mail. It’s been a great
exercise of <a href="/blog/2013/09/03/">my new e-mail setup</a>, which itself has definitely
made this job easier. It’s kept me very organized through the whole
process.</p>

<p><img src="/img/screenshot/github-dropoff.png" alt="" /></p>

<p>Each assignment involves applying two or three design patterns to a
crude (in my opinion) XML parsing library. Students are given a
tarball containing the source code for the library, in both Java and
C++. They pick a language, modify the code to use the specified
patterns, zip/archive up the result, and e-mail me their
zipfile/tarball.</p>

<p>It took me the first couple of weeks to work out an efficient grading
workflow, and, at this point, I can accurately work my way through
most new homework submissions rapidly. On my end I already know the
original code base. All I really care about is the student’s changes.
In software development this sort of thing is expressed a <em>diff</em>,
preferably in the <a href="http://en.wikipedia.org/wiki/Diff#Unified_format"><em>unified diff</em></a> format. This is called a
<em>patch</em>. It describes precisely what was added and removed, and
provides a bit of context around each change. The context greatly
increases the readability of the patch and, as a bonus, allows it to
be applied to a slightly different source. Here’s a part of a patch
recently submitted to Elfeed:</p>

<div class="language-diff highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gh">diff --git a/tests/elfeed-tests.el b/tests/elfeed-tests.el
index 31d5ad2..fbb78dd 100644
</span><span class="gd">--- a/tests/elfeed-tests.el
</span><span class="gi">+++ b/tests/elfeed-tests.el
</span><span class="p">@@ -144,15 +144,15 @@</span>
   (with-temp-buffer
     (insert elfeed-test-rss)
     (goto-char (point-min))
<span class="gd">-    (should (eq (elfeed-feed-type (xml-parse-region)) :rss)))
</span><span class="gi">+    (should (eq (elfeed-feed-type (elfeed-xml-parse-region)) :rss)))
</span>   (with-temp-buffer
     (insert elfeed-test-atom)
     (goto-char (point-min))
<span class="gd">-    (should (eq (elfeed-feed-type (xml-parse-region)) :atom)))
</span><span class="gi">+    (should (eq (elfeed-feed-type (elfeed-xml-parse-region)) :atom)))
</span>   (with-temp-buffer
     (insert elfeed-test-rss1.0)
     (goto-char (point-min))
<span class="gd">-    (should (eq (elfeed-feed-type (xml-parse-region)) :rss1.0))))
</span><span class="gi">+    (should (eq (elfeed-feed-type (elfeed-xml-parse-region)) :rss1.0))))
</span>
 (ert-deftest elfeed-entries-from-x ()
   (with-elfeed-test
</code></pre></div></div>

<p>I’d <em>really</em> prefer to receive patches like this as homework
submissions but this is probably too sophisticated for most students.
Instead, the first thing I do is create a patch for them from their
submission. Most students work off of their previous submission, so I
just run <code class="language-plaintext highlighter-rouge">diff</code> between their last submission and the current one.
While I’ve got a lot of the rest of the process automated with
scripts, I unfortunately cannot script patch generation. Each
student’s submission follows a unique format for that particular
student and some students are not even consistent between their own
assignments. About half the students also include generated files
alongside the source so I need to clean this up too. Generating the
patch is by far the messiest part of the whole process.</p>

<p>I grade almost entirely from the patch. 100% correct submissions are
usually only a few hundred lines of patch and I can spot all of the
required parts within a few minutes. Very easy. It’s the incorrect
submissions that consume most of my time. I have to figure out what
they’re doing, determine what they <em>meant</em> to do, and distill that
down into discrete discussion items along with point losses. In either
case I’ll also add some of my own opinions on their choice of style,
though this has no effect on the final grade.</p>

<p>For each student’s submission, I commit to a private Git repository
the raw, submitted archive file, the generated patch, and a grade
report written in Markdown. After the due date and once all the
submitted assignments are graded, I reply to each student with their
grade report. On a few occasions there’s been a back and forth
clarification dialog that has resulted in the student getting a higher
score. (That’s a hint to any students who happen to read this!)</p>

<p>Even ignoring the time it takes to generate a patch, there are still
disadvantages to not having students submit patches. One is the size:
about 60% of my current e-mail storage, which goes all the way back to
2006, is from this class alone from the past one month. It’s been a
lot of bulky attachments. I’ll delete all of the attachments once the
semester is over.</p>

<p>Another is that the students are unaware of the amount of changes they
make. Some of these patches contain a significant number of trivial
changes — breaking long lines in the original source, changing
whitespace within lines, etc. If students focused on crafting a tidy
patch they might try to avoid including these types of changes in
their submissions. I like to imagine this process being similar to
submitting a patch to an open source project. Patches should describe
a concise set of changes, and messy patches are rejected outright. The
Git staging area is all about crafting clean patches like this.</p>

<p>If there was something else I could change it would be to severely
clean up the original code base. When compiler warnings are turned on,
compiling it emits a giant list of warnings. The students are already
starting at an unnecessary disadvantage, missing out on a very
valuable feature: because of all the existing noise they can’t
effectively use compiler warnings themselves. Any new warnings would
be lost in the noise. This has also lead to many of those
trivial/unrelated changes: some students are spending time fixing the
warnings.</p>

<p>I want to go a lot further than warnings, though. I’d make sure the
original code base had absolutely no issues listed by <a href="http://pmd.sourceforge.net/">PMD</a>,
<a href="http://findbugs.sourceforge.net/">FindBugs</a>, or <a href="http://checkstyle.sourceforge.net/">Checkstyle</a> (for the Java
version, that is). Then I could use all of these static analysis tools
on student’s submissions to quickly spot issues. It’s as simple as
<a href="https://github.com/skeeto/sample-java-project/blob/master/build.xml">using my starter build configuration</a>. In fact, I’ve used
these tools a number of times in the past to perform detailed code
reviews for free (<a href="http://old.reddit.com/r/javahelp/comments/1inzs7/_/cb6ojr2">1</a>, <a href="http://old.reddit.com/r/reviewmycode/comments/1a2fty/_/c8tpme2">2</a>, <a href="http://old.reddit.com/r/javahelp/comments/1balsp/_/c958num">3</a>). Providing an
extensive code analysis for each student for each assignment would
become a realistic goal.</p>

<p>I’ve expressed all these ideas to the class’s instructor, my
colleague, so maybe some things will change in future semesters. If
I’m offered the opportunity again — assuming I didn’t screw this
semester up already — I’m still unsure if I would want to grade a
class again. It’s a lot of work for, optimistically, what amounts to
the same pay rate I received as an engineering intern in college. This
first experience at grading has been very educational, making me
appreciate those who graded my own sloppy assignments in college, and
that’s provided value beyond the monetary compensation. Next time
around wouldn’t be as educational, so my time could probably be better
spent on other activities, even if it’s writing open source software
for free.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>An HTML5 Canvas Design Pattern</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2013/06/16/"/>
    <id>urn:uuid:841e3d35-6d30-380d-ffdc-96b37f991ce7</id>
    <updated>2013-06-16T00:00:00Z</updated>
    <category term="javascript"/><category term="java"/><category term="lisp"/>
    <content type="html">
      <![CDATA[<p>I’ve been falling into a particular design pattern when using the
HTML5 Canvas element. By “design pattern” I don’t mean some pretty
arrangement but rather a <a href="http://en.wikipedia.org/wiki/Software_design_pattern">software design pattern</a>. This one’s a
very Lisp-like pattern, and I wonder if I would have come up with it
if I hadn’t first seen it in Lisp. It can also be applied to the Java
2D API, though less elegantly.</p>

<p>First, a review.</p>

<h3 id="drawing-basics">Drawing Basics</h3>

<p>A canvas is just another element in the page.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;canvas</span> <span class="na">id=</span><span class="s">"display"</span> <span class="na">width=</span><span class="s">"200"</span> <span class="na">height=</span><span class="s">"200"</span><span class="nt">&gt;&lt;/canvas&gt;</span>
</code></pre></div></div>

<p>To draw onto it, get a context and call drawing methods on it.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">ctx</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="dl">'</span><span class="s1">display</span><span class="dl">'</span><span class="p">).</span><span class="nx">getContext</span><span class="p">(</span><span class="dl">'</span><span class="s1">2d</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">fillStyle</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">blue</span><span class="dl">'</span><span class="p">;</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">beginPath</span><span class="p">();</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">arc</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">75</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">PI</span> <span class="o">*</span> <span class="mi">3</span> <span class="o">/</span> <span class="mi">2</span><span class="p">);</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">fill</span><span class="p">();</span>
</code></pre></div></div>

<p>This will result in a canvas that looks like this,</p>

<p><img src="/img/screenshot/canvas-arc.png" alt="" /></p>

<p>Here’s how to do the same thing with Java 2D. Very similar, except the
canvas is called a JComponent and the context is called a Graphics2D.
As you could imagine from this example, Java 2D API is much richer,
and more object-oriented than the Canvas API. The cast from Graphics
to Graphics2D is required due to legacy.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Example</span> <span class="kd">extends</span> <span class="nc">JComponent</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">paintComponent</span><span class="o">(</span><span class="nc">Graphics</span> <span class="n">graphics</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Graphics2D</span> <span class="n">g</span> <span class="o">=</span> <span class="o">(</span><span class="nc">Graphics2D</span><span class="o">)</span> <span class="n">graphics</span><span class="o">;</span>
        <span class="n">g</span><span class="o">.</span><span class="na">setColor</span><span class="o">(</span><span class="nc">Color</span><span class="o">.</span><span class="na">BLUE</span><span class="o">);</span>
        <span class="n">g</span><span class="o">.</span><span class="na">fill</span><span class="o">(</span><span class="k">new</span> <span class="nc">Arc2D</span><span class="o">.</span><span class="na">Float</span><span class="o">(</span><span class="mi">25</span><span class="o">,</span> <span class="mi">25</span><span class="o">,</span> <span class="mi">150</span><span class="o">,</span> <span class="mi">150</span><span class="o">,</span> <span class="mi">0</span><span class="o">,</span> <span class="mi">360</span><span class="o">,</span> <span class="nc">Arc2D</span><span class="o">.</span><span class="na">CHORD</span><span class="o">));</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>An important feature of both is the ability to globally apply
transforms — translate, scale, shear, and rotate — to all drawing
commands. For example, drawings on the canvas can be vertically scaled
using the <code class="language-plaintext highlighter-rouge">scale()</code> method. Graphics2D also has a <code class="language-plaintext highlighter-rouge">scale()</code> method.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// ...</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">scale</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">);</span>
<span class="c1">// ...</span>
</code></pre></div></div>

<p><img src="/img/screenshot/canvas-arc-scaled.png" alt="" /></p>

<p>For both JavaScript and Java the rendered image isn’t being
<em>stretched</em>. Instead, the input vertices are being transformed before
rendering to pixels. This is what makes it possible to decouple the
<em>screen</em> coordinate system from the program’s internal coordinate
system. Outside of rare performance concerns, the program’s internal
logic shouldn’t be written in terms of pixels. It should rely on these
transforms to convert between coordinate systems at rendering time,
allowing for a moving camera.</p>

<h3 id="the-transform-stack">The Transform Stack</h3>

<p>Both cases also allow the current transform to be captured and
restored. Not only does this make it easier for a function to clean up
after itself and properly share the canvas with other functions, but
also multiple different coordinate transforms can be <em>stacked</em> on top
of each other. For example, the bottom transform might convert between
internal coordinates and screen coordinates. When it comes time to
draw a minimap, another transform can be pushed on top and the same
exact drawing methods applied to the canvas.</p>

<p>This is where Canvas and Java 2D start to differ. Both got some aspect
right and some aspect wrong, and I wish I could easily have the best
of both.</p>

<p>In canvas, this is literally a stack, and there are a pair of methods,
<code class="language-plaintext highlighter-rouge">save()</code> and <code class="language-plaintext highlighter-rouge">restore()</code> for pushing and popping the transform matrix
on an internal stack. The above JavaScript example may be in a
function that is called more than once, so it should restore the
transform matrix before returning.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">ctx</span><span class="p">.</span><span class="nx">save</span><span class="p">();</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">scale</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">);</span>
<span class="c1">// ... draw ...</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">restore</span><span class="p">();</span>
</code></pre></div></div>

<p>In Java this stack is managed manually, and it (typically) sits inside
the call stack itself as a variable.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">AffineTransform</span> <span class="n">tf</span> <span class="o">=</span> <span class="n">g</span><span class="o">.</span><span class="na">getTransform</span><span class="o">();</span>
<span class="n">g</span><span class="o">.</span><span class="na">scale</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mf">0.5</span><span class="o">);</span>
<span class="c1">// ... draw ...</span>
<span class="n">g</span><span class="o">.</span><span class="na">setTransform</span><span class="o">(</span><span class="n">tf</span><span class="o">);</span>
</code></pre></div></div>

<p>I think Canvas’s built-in stack is more elegant than managing an
extraneous variable and object. However, what’s significant about Java
2D is that <strong>we actually have access to the transform matrix</strong>. It’s
that <a href="http://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html">AffineTransform</a> object. The Canvas transform matrix is an
internal, inaccessible data structure. It has an established external
representation, <a href="http://www.w3.org/TR/SVGTiny12/svgudom.html#svg__SVGMatrix">SVGMatrix</a>, but it won’t provide a copy. If one
of these is needed, a separate matrix must to be maintained in
parallel. What a pain!</p>

<p>Why would we need the transform matrix? <strong>So that we can transform
coordinates in reverse!</strong> When a user interacts with the display, the
program receives <em>screen</em> coordinates. To be useful, these need to be
converted into internal coordinates so that the program can determine
where in the world the user clicked. The Java AffineTransform class
has a <code class="language-plaintext highlighter-rouge">createInverse()</code> method for computing this inverse transform.
This is something I really miss having when using Canvas. It’s such an
odd omission.</p>

<h3 id="the-design-pattern">The Design Pattern</h3>

<p>So, back to the design pattern. When it comes time draw something, a
transform is established on the context, something is drawn to the
context, then finally the transform is removed. The word “finally”
should stand out here. If we’re being careful, we should put the
teardown step inside a <code class="language-plaintext highlighter-rouge">finally</code> block. If something goes wrong, the
context will be left in a clean state. This has personally helped me
in debugging.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">ctx</span><span class="p">.</span><span class="nx">save</span><span class="p">();</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">scale</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">);</span>
<span class="k">try</span> <span class="p">{</span>
    <span class="c1">// ... draw ...</span>
<span class="p">}</span> <span class="k">finally</span> <span class="p">{</span>
    <span class="nx">ctx</span><span class="p">.</span><span class="nx">restore</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In Lisp, this pattern is typically captured as a <code class="language-plaintext highlighter-rouge">with-</code> macro.</p>

<ol>
  <li>Perform setup</li>
  <li>Run body</li>
  <li>Teardown</li>
  <li>Return the body’s return value</li>
</ol>

<p>Instead of <code class="language-plaintext highlighter-rouge">finally</code>, the special form <code class="language-plaintext highlighter-rouge">unwind-protect</code> is used to
clean up regardless of any error condition. Here’s a simplified
version of Emacs’ <code class="language-plaintext highlighter-rouge">with-temp-buffer</code> macro, which itself is built on
another <code class="language-plaintext highlighter-rouge">with-</code> macro, <code class="language-plaintext highlighter-rouge">with-current-buffer</code>.</p>

<div class="language-cl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">defmacro</span> <span class="nv">with-temp-buffer</span> <span class="p">(</span><span class="k">&amp;rest</span> <span class="nv">body</span><span class="p">)</span>
  <span class="o">`</span><span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">temp-buffer</span> <span class="p">(</span><span class="nv">generate-new-buffer</span> <span class="s">" *temp*"</span><span class="p">)))</span>
     <span class="p">(</span><span class="nv">with-current-buffer</span> <span class="nv">temp-buffer</span>
       <span class="p">(</span><span class="k">unwind-protect</span>
           <span class="p">(</span><span class="k">progn</span> <span class="o">,@</span><span class="nv">body</span><span class="p">)</span>
         <span class="p">(</span><span class="nv">kill-buffer</span> <span class="nv">temp-buffer</span><span class="p">)))))</span>
</code></pre></div></div>

<p>The setup is to create a new buffer and switch to it. The teardown
destroys the buffer, regardless of what happens in the body. An
example from Common Lisp would be <code class="language-plaintext highlighter-rouge">with-open-file</code>.</p>

<div class="language-cl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">with-open-file</span> <span class="p">(</span><span class="nc">stream</span> <span class="s">"/etc/passwd"</span><span class="p">)</span>
  <span class="p">(</span><span class="nb">loop</span> <span class="nv">while</span> <span class="p">(</span><span class="nb">listen</span> <span class="nc">stream</span><span class="p">)</span>
     <span class="nv">collect</span> <span class="p">(</span><span class="nb">read-line</span> <span class="nc">stream</span><span class="p">)))</span>
</code></pre></div></div>

<p>This macro ensures that the stream is closed when the body exits, no
matter what. (Side note: this can be very surprising when combined
with Clojure’s laziness!)</p>

<p>There are no macros in JavaScript, let alone Lisp’s powerful macro
system, but the pattern can still be captured using closures. Replace
the body with a callback.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">Transform</span><span class="p">()</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>

<span class="c1">// ...</span>

<span class="nx">Transform</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">withDraw</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">ctx</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">ctx</span><span class="p">.</span><span class="nx">save</span><span class="p">();</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">applyTransform</span><span class="p">(</span><span class="nx">ctx</span><span class="p">);</span>
    <span class="k">try</span> <span class="p">{</span>
        <span class="nx">callback</span><span class="p">();</span>
    <span class="p">}</span> <span class="k">finally</span> <span class="p">{</span>
        <span class="nx">ctx</span><span class="p">.</span><span class="nx">restore</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<p>The callback is called once the context is in the proper state. Here’s
how it would be used.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">transform</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Transform</span><span class="p">().</span><span class="nx">scale</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">);</span>  <span class="c1">// (fluent API)</span>

<span class="kd">function</span> <span class="nx">render</span><span class="p">(</span><span class="nx">step</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">transform</span><span class="p">.</span><span class="nx">withDraw</span><span class="p">(</span><span class="nx">ctx</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="c1">// ... draw ...</span>
    <span class="p">});</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Since JavaScript has proper closures, that <code class="language-plaintext highlighter-rouge">step</code> variable is
completely available to the callback. This function-as-body pattern
comes up a lot (e.g. <a href="http://requirejs.org/docs/whyamd.html">AMD</a>), and seeing it work so well makes me
think of JavaScript as a “suitable Lisp.”</p>

<p>Java can just barely pull off the pattern using anonymous classes, but
it’s very clunky.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Transform</span> <span class="o">{</span>
    <span class="c1">// ...</span>

    <span class="nc">AffineTransform</span> <span class="n">transform</span><span class="o">;</span>

    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">withDraw</span><span class="o">(</span><span class="nc">Graphics2D</span> <span class="n">g</span><span class="o">,</span> <span class="nc">Runnable</span> <span class="n">callback</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">AffineTransform</span> <span class="n">original</span> <span class="o">=</span> <span class="n">g</span><span class="o">.</span><span class="na">getTransform</span><span class="o">();</span>
        <span class="n">g</span><span class="o">.</span><span class="na">transform</span><span class="o">(</span><span class="n">transform</span><span class="o">);</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">callback</span><span class="o">.</span><span class="na">run</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
            <span class="n">g</span><span class="o">.</span><span class="na">setTransform</span><span class="o">(</span><span class="n">original</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">Foo</span> <span class="o">{</span>
    <span class="c1">// ...</span>

    <span class="nc">Transform</span> <span class="n">transform</span><span class="o">;</span>

    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">render</span><span class="o">(</span><span class="nc">Graphics2D</span> <span class="n">g</span><span class="o">,</span> <span class="kt">double</span> <span class="n">step</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">transform</span><span class="o">.</span><span class="na">withDraw</span><span class="o">(</span><span class="n">g</span><span class="o">,</span> <span class="k">new</span> <span class="nc">Runnable</span><span class="o">()</span> <span class="o">{</span>
            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
                <span class="c1">// ... draw ...</span>
            <span class="o">}</span>
        <span class="o">});</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Java’s anonymous classes are closures, but, unlike Lisp and
JavaScript, they close over <em>values</em> rather than <em>bindings</em>. Purely in
attempt to hide this complexity, Java requires that variables accessed
from the anonymous class be declared as <code class="language-plaintext highlighter-rouge">final</code>. It’s awkward and
confusing enough that I probably wouldn’t try to apply it in Java.</p>

<p>I think this pattern works very well with JavaScript, and if you dig
around in some of my graphical JavaScript you’ll see that I’ve already
put it to use. JavaScript functions work pretty well as a stand in for
some kinds of Lisp macros.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Emacs Javadoc Lookups Get a Facelift</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2013/01/30/"/>
    <id>urn:uuid:18159666-2379-359b-35dd-edf5c4bdbf60</id>
    <updated>2013-01-30T00:00:00Z</updated>
    <category term="emacs"/><category term="java"/><category term="clojure"/>
    <content type="html">
      <![CDATA[<p>Ever since
<a href="/blog/2012/08/12/">I started using the Emacs package archive</a>,
specifically <a href="http://melpa.milkbox.net/">MELPA</a>, I’d been wanting to tidy up
<a href="/blog/2010/10/14/">my Emacs Java extensions</a>, java-mode-plus, into a
nice, official package. Observing my own attitude after the switch, I
noticed that if a package isn’t available on ELPA or MELPA, it
practically doesn’t exist for me. Manually installing anything now
seems like so much trouble in comparison, and getting a package on
MELPA is so easy that there’s little excuse for package authors not to
have their package in at least one of the three major Elisp
archives. This is exactly the attitude my own un-archived package
would be facing from other people, and rightfully so.</p>

<p>Before I dive in, this is what the user configuration now looks like,</p>

<div class="language-cl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">javadoc-add-artifacts</span> <span class="nv">[org.lwjgl.lwjg</span> <span class="nv">lwjgl</span> <span class="s">"2.8.2"</span><span class="nv">]</span>
                       <span class="nv">[com.nullprogram</span> <span class="nv">native-guide</span> <span class="s">"0.2"</span><span class="nv">]</span>
                       <span class="nv">[org.apache.commons</span> <span class="nv">commons-math3</span> <span class="s">"3.0"</span><span class="nv">]</span><span class="p">)</span>
</code></pre></div></div>

<p>That’s right: it knows how to find, fetch, and index documentation on
its own. Keep reading if this sounds useful to you.</p>

<h3 id="the-problem">The Problem</h3>

<p>The problem was that java-mode-plus was doing two unrelated things:</p>

<ul>
  <li>
    <p>Supporting Ant-oriented Java projects. Not
 <a href="http://kent.spillner.org/blog/work/2009/11/14/java-build-tools.html">being a fan of Maven</a>, I’ve used Ant for all of my own
 personal projects. (However, I really do like the Maven
 infrastructure, so I use Apache Ivy.) It seems Maven is a lot more
 popular, so this part isn’t useful for many people.</p>
  </li>
  <li>
    <p>Quick Javadoc referencing, which I was calling java-docs. I think
 this is generally useful for anyone writing Java in Emacs, even if
 they’re using another suite like JDEE or writing in another JVM
 language. It would be nice for people to be able to use this without
 pulling in all of java-mode-plus — which was somewhat intrusive.</p>
  </li>
</ul>

<p>I also didn’t like the names I had picked. java-mode-plus wasn’t even
a mode until recently and its name isn’t conventional. And “java-docs”
is just stupid. I recently solved all this by splitting the
java-mode-plus into two new packages,</p>

<ul>
  <li>
    <p><a href="https://github.com/skeeto/ant-project-mode"><em>ant-project-mode</em></a> — A minor mode that
 performs the duties of the first task above. Since I’ve
 <a href="/blog/2012/08/12/">phased Java out</a> from my own personal projects
 and no longer intend to write Java anymore, this part isn’t very
 useful to me personally at the moment. If I do need to write Java for
 work again I’ll probably dust this off. It’s by no means
 un-maintained, it’s just in maintenance mode for now. Because of
 this, this is not in any Emacs package archive</p>
  </li>
  <li>
    <p><a href="https://github.com/skeeto/javadoc-lookup"><em>javadoc-lookup</em></a> — This is java-docs renamed and
 <strong>with some new goodies!</strong> I also <strong>put this on MELPA</strong>, where it’s
 easy for anyone to use. This is continues to be useful for me as I
 use Clojure.</p>
  </li>
</ul>

<h3 id="javadoc-lookup">javadoc-lookup</h3>

<p>This is used like java-docs before it, just under a different
name. The function <code class="language-plaintext highlighter-rouge">javadoc-lookup</code> asks for a Java class for
documentation. I like to bind this to <code class="language-plaintext highlighter-rouge">C-h j</code>.</p>

<p>The function <code class="language-plaintext highlighter-rouge">javadoc-add-roots</code> provides filesystem paths to be
indexed for lookup.</p>

<div class="language-cl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">javadoc-add-roots</span> <span class="s">"/usr/share/doc/openjdk-6-jdk/api"</span>
                   <span class="s">"~/src/project/doc"</span><span class="p">)</span>
</code></pre></div></div>

<p>Also, as before, if you don’t provide a root for the core Java API, it
will automatically load an index of the official Javadoc hosted
online. This means it can be installed from MELPA and used immediately
without any configuration. Good defaults and minimal required
configuration <a href="/blog/2012/10/31/">is something I highly value</a>.</p>

<p>Back in the java-docs days, when I started using a new library I’d
track down the Javadoc jar, unzip it somewhere on my machine, and add
it to be indexed. I regularly do development on four different
computers, so this gets tedious fast. Since the Javadoc jars are
easily available from the Maven repository, I maintained a small Ant
project within my .emacs.d for awhile just to do this fetching, but it
was a dirty hack.</p>

<h4 id="finally-the-goodies">Finally, the Goodies</h4>

<p>Here’s the cool new part: I built this functionality into
javadoc-lookup. <strong>It can fetch all your documentation for you!</strong>
Instead of providing a path on your filesystem, you name an artifact
that Maven can find. javadoc-lookup will call Maven to fetch the
Javadoc jar, unzip it into a cache directory, and index it for
lookups. You will need Maven installed either on your <code class="language-plaintext highlighter-rouge">$PATH</code> or at
<code class="language-plaintext highlighter-rouge">maven-program-name</code> (Elisp variable).</p>

<p>Here’s a sample configuration. It’s group, artifact, version provided
as a sequence. I say “sequence” because it can be either a list or a
vector and those names can be either strings or symbols. I prefer the
vector/symbol method because it requires
<a href="/blog/2012/07/17/">the least quoting</a>, plus it looks Clojure-ish.</p>

<div class="language-cl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">javadoc-add-artifacts</span> <span class="nv">[org.lwjgl.lwjg</span> <span class="nv">lwjgl</span> <span class="s">"2.8.2"</span><span class="nv">]</span>
                       <span class="nv">[com.nullprogram</span> <span class="nv">native-guide</span> <span class="s">"0.2"</span><span class="nv">]</span>
                       <span class="nv">[org.apache.commons</span> <span class="nv">commons-math3</span> <span class="s">"3.0"</span><span class="nv">]</span><span class="p">)</span>
</code></pre></div></div>

<p>Put that in your initialization and all this documentation will appear
in the lookup index. It only needs to fetch from Maven once per
artifact per system — a very very slow process. After that it
operates entirely from its own cache which is very fast, so it won’t
slow down your startup.</p>

<p>This has been extremely convenient for me so I hope other people find
it useful, too.</p>

<p>As a final note, javadoc-lookup also exploits structural sharing in
its tables, using a lot less memory than java-docs. Not that it was a
problem before; it’s a feel-good feature.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Viewing Java Class Files in Emacs</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2012/08/01/"/>
    <id>urn:uuid:1bb9f8a9-61eb-34eb-bb62-83e93166cbea</id>
    <updated>2012-08-01T00:00:00Z</updated>
    <category term="emacs"/><category term="java"/>
    <content type="html">
      <![CDATA[<p>One of the users of <a href="/blog/2010/10/15/">my Emacs java extensions</a>
e-mailed me with a question/suggestion about viewing .class files in
Emacs. Emacs has automatic compression, encryption, and archive modes
which allow certain non-text files to be viewed within Emacs in a
sensible text form. He wanted to do the same with Java byte-compiled
.class files: when opening a .class file, Emacs should automatically
and transparently decompile the bytecode into Java source.</p>

<p>He mentioned
[JAD](http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler%29)
specifically, a popular, proprietary, but unmaintained and outdated
Java bytecode decompiler. I’ve never used it and honestly I see no
reason to start using it. Unfortunately there are no other decompilers
in the Debian package archives and I know nothing else about Java
decompiling, so this left me kind of stuck. Instead I decided to build
a proof-of-concept using <code class="language-plaintext highlighter-rouge">javap</code>, the Java disassembler, which comes
with JDKs.</p>

<p>Here it is: <a href="https://gist.github.com/3178747">javap-handler.el</a>. With
these forms evaluated, try opening a .class file in Emacs. Rather than
a screen full of junk, you’ll (hopefully) be presented with a
read-only buffer containing detailed information about the class.</p>

<div class="language-cl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nv">add-to-list</span> <span class="ss">'file-name-handler-alist</span> <span class="o">'</span><span class="p">(</span><span class="s">"\\.class$"</span> <span class="o">.</span> <span class="nv">javap-handler</span><span class="p">))</span>

<span class="p">(</span><span class="nb">defun</span> <span class="nv">javap-handler</span> <span class="p">(</span><span class="nv">op</span> <span class="k">&amp;rest</span> <span class="nv">args</span><span class="p">)</span>
  <span class="s">"Handle .class files by putting the output of javap in the buffer."</span>
  <span class="p">(</span><span class="nb">cond</span>
   <span class="p">((</span><span class="nb">eq</span> <span class="nv">op</span> <span class="ss">'get-file-buffer</span><span class="p">)</span>
    <span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">file</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">args</span><span class="p">)))</span>
      <span class="p">(</span><span class="nv">with-current-buffer</span> <span class="p">(</span><span class="nv">create-file-buffer</span> <span class="nv">file</span><span class="p">)</span>
        <span class="p">(</span><span class="nv">call-process</span> <span class="s">"javap"</span> <span class="no">nil</span> <span class="p">(</span><span class="nv">current-buffer</span><span class="p">)</span> <span class="no">nil</span> <span class="s">"-verbose"</span>
                      <span class="s">"-classpath"</span> <span class="p">(</span><span class="nv">file-name-directory</span> <span class="nv">file</span><span class="p">)</span>
                      <span class="p">(</span><span class="nv">file-name-sans-extension</span>
                       <span class="p">(</span><span class="nv">file-name-nondirectory</span> <span class="nv">file</span><span class="p">)))</span>
        <span class="p">(</span><span class="k">setq</span> <span class="nv">buffer-file-name</span> <span class="nv">file</span><span class="p">)</span>
        <span class="p">(</span><span class="k">setq</span> <span class="nv">buffer-read-only</span> <span class="no">t</span><span class="p">)</span>
        <span class="p">(</span><span class="nv">set-buffer-modified-p</span> <span class="no">nil</span><span class="p">)</span>
        <span class="p">(</span><span class="nv">goto-char</span> <span class="p">(</span><span class="nv">point-min</span><span class="p">))</span>
        <span class="p">(</span><span class="nv">java-mode</span><span class="p">)</span>
        <span class="p">(</span><span class="nv">current-buffer</span><span class="p">))))</span>
   <span class="p">((</span><span class="nv">javap-handler-real</span> <span class="nv">op</span> <span class="nv">args</span><span class="p">))))</span>

<span class="p">(</span><span class="nb">defun</span> <span class="nv">javap-handler-real</span> <span class="p">(</span><span class="nv">operation</span> <span class="nv">args</span><span class="p">)</span>
  <span class="s">"Run the real handler without the javap handler installed."</span>
  <span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">inhibit-file-name-handlers</span>
         <span class="p">(</span><span class="nb">cons</span> <span class="ss">'javap-handler</span>
               <span class="p">(</span><span class="nb">and</span> <span class="p">(</span><span class="nb">eq</span> <span class="nv">inhibit-file-name-operation</span> <span class="nv">operation</span><span class="p">)</span>
                    <span class="nv">inhibit-file-name-handlers</span><span class="p">)))</span>
        <span class="p">(</span><span class="nv">inhibit-file-name-operation</span> <span class="nv">operation</span><span class="p">))</span>
    <span class="p">(</span><span class="nb">apply</span> <span class="nv">operation</span> <span class="nv">args</span><span class="p">)))</span>
</code></pre></div></div>

<p><a href="/img/emacs/javap-junk.png"><img src="/img/emacs/javap-junk-thumb.png" alt="" /></a></p>

<p><a href="/img/emacs/javap-clear.png"><img src="/img/emacs/javap-clear-thumb.png" alt="" /></a></p>

<p>This was harder to do than I thought it would be. To make a new
“magic” file mode requires the use of a half-documented, hackish
file-name-handler API. There’s
<a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Magic-File-Names.html">a page on it</a>
in the <em>GNU Emacs Lisp Reference Manual</em> but I mostly figured it out
by reading the source code around auto-compression-mode and
auto-encryption-mode.</p>

<p>It works by installing a handler function in <code class="language-plaintext highlighter-rouge">file-name-handler-alist</code>
— similar to <code class="language-plaintext highlighter-rouge">auto-mode-alist</code>. The handler has complete control over
how a particularly-named class of files is handled by Emacs. For
example, the most useful part is instead of actually providing the
contents of a file, the handler can present any contents it wants. In
this case, rather than read in the actual bytecode, the handler
executes <code class="language-plaintext highlighter-rouge">javap</code> on the file and uses the output for the buffer
content.</p>

<p>The hackish part is when the handler wants to let Emacs handle an
operation the normal way, which is pretty much every case except for
<code class="language-plaintext highlighter-rouge">get-file-buffer</code>. The handler has to disable itself by temporarily
setting a dynamically-scoped variable (one of the many legacy areas
that prevents Emacs from being lexically-scoped by default), then ask
Emacs to try the operation again.</p>

<p>As I said, this is just a proof-of-concept so there are two issues
remaining. The first was something requested specifically: viewing
.class files inside .jar archives. It could do this if it was just a
little bit smarter about the classpath. I leave that as an exercise to
the reader. :-)</p>

<p>The second is finding a well-behaved, reasonable decompiler (GUI-less
Unix filter) and replacing <code class="language-plaintext highlighter-rouge">javap</code> with it. Given that assumption,
this should be as simple as replacing a couple of strings in the
<code class="language-plaintext highlighter-rouge">call-process</code>.</p>

<p>This is interesting enough that, if I were to fix it up for
correctness sometime, I may include it as part of java-mode-plus
someday.</p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Perlin Noise With Octave, Java, and OpenCL</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2012/06/03/"/>
    <id>urn:uuid:830cc950-634a-3661-135a-b932c8c5399e</id>
    <updated>2012-06-03T00:00:00Z</updated>
    <category term="java"/><category term="c"/><category term="octave"/><category term="video"/>
    <content type="html">
      <![CDATA[<p>I recently discovered that I’m an idiot and that my
<a href="/blog/2007/11/20/">old Perlin noise post</a> was not actually describing
Perlin noise at all, but fractional Brownian motion. Perlin noise is
slightly more complicated but much more powerful. To learn the correct
algorithm, I wrote three different implementations
(<a href="https://github.com/skeeto/perlin-noise">perlin-noise</a>).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone git://github.com/skeeto/perlin-noise.git
</code></pre></div></div>

<p>In short, Perlin noise is based on a grid of randomly-generated
gradient vectors which describe how the arbitrarily-dimensional
“surface” is sloped at that point. The noise at the grid points is
always 0, though you’d never know it. When sampling the noise at some
point between grid points, a weighted interpolation of the surrounding
gradient vectors is calculated. Vectors are reduced to a single noise
value by dot product.</p>

<p>Rather than waste time trying to explain it myself, I’ll link to an
existing, great tutorial: <a href="https://web.archive.org/web/20150304163452/http://webstaff.itn.liu.se/~stegu/TNM022-2005/perlinnoiselinks/perlin-noise-math-faq.html">The Perlin noise math FAQ</a>. There’s
also the original presentation by Ken Perlin, <a href="(http://www.noisemachine.com/talk1/)">Making Noise</a>,
which is more concise but harder to grok.</p>

<p>When making my own implementation, I started by with Octave. It’s my
“go to language” for creating a prototype when I’m doing something
with vectors or matrices since it has the most concise syntax for
these things. I wrote a two-dimensional generator and it turned out to
be a lot simpler than I thought it would be!</p>

<ul>
  <li><a href="https://github.com/skeeto/perlin-noise/blob/master/octave/perlin2d.m">perlin2d.m</a></li>
</ul>

<p>Because it’s 2D, there are four surrounding grid points to consider
and these are all hard-coded. This leads to an interesting property:
there are no loops. The code is entirely vectorized, which makes it
quite fast. It actually keeps up with my generalized Java solution
(next) when given a grid of points, such as from <code class="language-plaintext highlighter-rouge">meshgrid()</code>.</p>

<p>The grid gradient vectors are generated on the fly by a hash
function. The integer x and y positions of the point are hashed using
a bastardized version of Robert Jenkins’ 96 bit mix function (the one
I used in my <a href="/blog/2011/06/13/">infinite parallax starfield</a>) to
produce a vector. This turned out to be the trickiest part to write,
because any weaknesses in the hash function become very apparent in
the resulting noise.</p>

<p>Using Octave, this took two seconds to generate on my laptop. You
can’t really tell by looking at it, but, as with all Perlin noise,
there is actually a grid pattern.</p>

<p><img src="/img/noise/octave-perlin2d.png" alt="" /></p>

<p>I then wrote a generalized version, <code class="language-plaintext highlighter-rouge">perlin.m</code>, that can generate
arbitrarily-dimensional noise. This one is a lot shorter, but it’s not
vectorized, can only sample one point at a time, and is incredibly
slow. For a hash function, I use Octave’s <code class="language-plaintext highlighter-rouge">hashmd5()</code>, so this one
won’t work in Matlab (which provides no hash function
whatsoever). However, it <em>is</em> a lot shorter!</p>

<div class="language-matlab highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">%% Returns the Perlin noise value for an arbitrary point.</span>
<span class="k">function</span> <span class="n">v</span> <span class="o">=</span> <span class="n">perlin</span><span class="p">(</span><span class="n">p</span><span class="p">)</span>
  <span class="n">v</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="c1">%% Iterate over each corner</span>
  <span class="k">for</span> <span class="n">dirs</span> <span class="o">=</span> <span class="p">[</span><span class="nb">dec2bin</span><span class="p">(</span><span class="mi">0</span><span class="p">:(</span><span class="mi">2</span> <span class="o">^</span> <span class="nb">length</span><span class="p">(</span><span class="n">p</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">))</span> <span class="o">-</span> <span class="mi">48</span><span class="p">]</span><span class="o">'</span>
    <span class="n">q</span> <span class="o">=</span> <span class="nb">floor</span><span class="p">(</span><span class="n">p</span><span class="p">)</span> <span class="o">+</span> <span class="n">dirs</span><span class="s1">'; % This iteration'</span><span class="n">s</span> <span class="n">corner</span>
    <span class="n">g</span> <span class="o">=</span> <span class="n">qgradient</span><span class="p">(</span><span class="n">q</span><span class="p">);</span> <span class="c1">% This corner's gradient</span>
    <span class="n">m</span> <span class="o">=</span> <span class="nb">dot</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="n">p</span> <span class="o">-</span> <span class="n">q</span><span class="p">);</span>
    <span class="n">t</span> <span class="o">=</span> <span class="mf">1.0</span> <span class="o">-</span> <span class="nb">abs</span><span class="p">(</span><span class="n">p</span> <span class="o">-</span> <span class="n">q</span><span class="p">);</span>
    <span class="n">v</span> <span class="o">+=</span> <span class="n">m</span> <span class="o">*</span> <span class="nb">prod</span><span class="p">(</span><span class="mi">3</span> <span class="o">*</span> <span class="n">t</span> <span class="o">.^</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">t</span> <span class="o">.^</span> <span class="mi">3</span><span class="p">);</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="c1">%% Return the gradient at the given grid point.</span>
<span class="k">function</span> <span class="n">v</span> <span class="o">=</span> <span class="n">qgradient</span><span class="p">(</span><span class="n">q</span><span class="p">)</span>
  <span class="n">v</span> <span class="o">=</span> <span class="nb">zeros</span><span class="p">(</span><span class="nb">size</span><span class="p">(</span><span class="n">q</span><span class="p">));</span>
  <span class="k">for</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">:</span><span class="nb">length</span><span class="p">(</span><span class="n">q</span><span class="p">);</span>
      <span class="n">v</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="o">=</span> <span class="n">hashmd5</span><span class="p">([</span><span class="n">i</span> <span class="n">q</span><span class="p">])</span> <span class="o">*</span> <span class="mf">2.0</span> <span class="o">-</span> <span class="mf">1.0</span><span class="p">;</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>It took Octave an entire day to generate this “fire” video, which is
ridiculously long. An old graphics card could probably do this in real
time.</p>

<video src="https://nullprogram.s3.amazonaws.com/noise/fire.webm" width="300" height="300" controls="controls">
  Your browser doesn't support HTML5 video with WebM. :-(
</video>

<p>This was produced by viewing a slice of 3D noise. For animation, the
viewing area moves in two dimensions (z and y). One dimension makes
the fire flicker, the other makes it look like it’s rising. A simple
gradient was applied to the resulting noise to fade away towards the
top.</p>

<p>I wanted to achieve this same effect faster, so next I made a
generalized Java implementation, which is the bulk of the
repository. I wrote my own Vector class (completely unlike Java’s
depreciated Vector but more like Apache Commons Math’s RealVector), so
it looks very similar to the Octave version. It’s much, much faster
than the generalized Octave version. It doesn’t use a hash function
for gradients — instead randomly generating them as needed and
keeping track of them for later with a Map.</p>

<p>I wanted to go faster yet, so next I looked at OpenCL for the first
time. OpenCL is an API that allows you to run C-like programs on your
graphics processing unit (GPU), among other things. I was sticking to
Java so I used <a href="http://www.lwjgl.org/">lwjgl</a>’s OpenCL bindings. In
order to use this code you’ll need an OpenCL implementation available
on your system, which, unfortunately, is usually proprietary. My
OpenCL noise generator only generates 3D noise.</p>

<p>Why use the GPU? GPUs have a highly-parallel structure that makes them
faster than CPUs at processing large blocks of data in parallel. This
is really important when it comes to computer graphics, but it can be
useful for other purposes as well, like generating Perlin noise.</p>

<p>I had to change my API a little to make this effective. Before, to
generate noise samples, I passed points in individually to
PerlinNoise. To properly parallelize this for OpenCL, an entire slice
is specified by setting its width, height, step size, and
z-level. This information, along with pre-computed grid gradients, is
sent to the GPU.</p>

<ul>
  <li><a href="https://github.com/skeeto/perlin-noise/blob/opencl/src/com/nullprogram/noise/perlin3d.cl">perlin3d.cl</a></li>
</ul>

<p>This is all in the <code class="language-plaintext highlighter-rouge">opencl</code> branch in the repository. When run, it
will produce a series of slices of 3D noise in a manner similar to the
fire example above. For comparison, it will use the CPU by default,
generating a series of <code class="language-plaintext highlighter-rouge">simple-*.png</code>. Give the program one argument,
“opencl”, and it will use OpenCL instead, generating a series of
<code class="language-plaintext highlighter-rouge">opencl-*.png</code>. You should notice a massive increase in speed when
using OpenCL. In fact, it’s even faster than this. The vast majority
of the time is spent creating these output PNG images. When I disabled
image output for both, OpenCL was 200 times faster than the
(single-core) CPU implementation, still spending a significant amount
of time just loading data off the GPU.</p>

<p>And finally, I turned the OpenCL output into a video,</p>

<video src="https://nullprogram.s3.amazonaws.com/noise/opencl.webm" width="400" height="400" controls="controls">
  Your browser doesn't support HTML5 video with WebM. :-(
</video>

<p>That’s pretty cool!</p>

<p>I still don’t really have a use for Perlin noise, especially not under
constraints that require I use OpenCL to generate it. The big thing I
got out of this project was my first experience with OpenCL, something
that really <em>is</em> useful at work.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Rumor Simulation</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2012/03/09/"/>
    <id>urn:uuid:9fee2022-d273-34d6-0970-546b5e875460</id>
    <updated>2012-03-09T00:00:00Z</updated>
    <category term="java"/><category term="math"/><category term="media"/><category term="video"/><category term="reddit"/>
    <content type="html">
      <![CDATA[<p>A couple months ago someone posted
<a href="http://old.reddit.com/r/javahelp/comments/ngvp4/">an interesting programming homework problem</a> on reddit,
asking for help. Help had already been provided before I got there,
but I thought the problem was an interesting one.</p>

<blockquote>
  <p>Write a program that simulates the spreading of a rumor among a group
of people. At any given time, each person in the group is in one of
three categories:</p>

  <ul>
    <li>IGNORANT - the person has not yet heard the rumor</li>
    <li>SPREADER - the person has heard the rumor and is eager to spread it</li>
    <li>STIFLER - the person has heard the rumor but considers it old news
and will not spread it</li>
  </ul>

  <p>At the very beginning, there is one spreader; everyone else is
ignorant. Then people begin to encounter each other.</p>

  <p>So the encounters go like this:</p>

  <ul>
    <li>If a SPREADER and an IGNORANT meet, IGNORANT becomes a SPREADER.</li>
    <li>If a SPREADER and a STIFLER meet, the SPREADER becomes a STIFLER.</li>
    <li>If a SPREADER and a SPREADER meet, they both become STIFLERS.</li>
    <li>In all other encounters nothing changes.</li>
  </ul>

  <p>Your program should simulate this by repeatedly selecting two people
randomly and having them “meet.”</p>

  <p>There are three questions we want to answer:</p>

  <ul>
    <li>Will everyone eventually hear the rumor, or will it die out before
everyone hears it?</li>
    <li>If it does die out, what percentage of the population hears it?</li>
    <li>How long does it take? i.e. How many encounters occur before the
rumor dies out?</li>
  </ul>
</blockquote>

<p>I wrote a very thorough version to <a href="/blog/2011/11/28/">produce videos</a> of the
simulation in action.</p>

<ul>
  <li><a href="https://github.com/skeeto/rumor-sim">https://github.com/skeeto/rumor-sim</a></li>
</ul>

<p>It accepts some command line arguments, so you don’t need to edit any
code just to try out some simple things.</p>

<p>And here are a couple of videos. Each individual is a cell in a 2D
grid. IGNORANT is black, SPREADER is red, and STIFLER is white. Note
that this is <em>not</em> a cellular automata, because cell neighborship does
not come into play.</p>

<video src="https://s3.amazonaws.com/nullprogram/rumor/rumor-small.webm" controls="controls" width="400" height="250">
</video>

<video src="https://s3.amazonaws.com/nullprogram/rumor/rumor.webm" controls="controls" width="400" height="400">
</video>

<p>Here’s are the statistics for ten different rumors.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Rumor(n=10000, meetups=132380, knowing=0.789)
Rumor(n=10000, meetups=123944, knowing=0.7911)
Rumor(n=10000, meetups=117459, knowing=0.7985)
Rumor(n=10000, meetups=127063, knowing=0.79)
Rumor(n=10000, meetups=124116, knowing=0.8025)
Rumor(n=10000, meetups=115903, knowing=0.7952)
Rumor(n=10000, meetups=137222, knowing=0.7927)
Rumor(n=10000, meetups=134354, knowing=0.797)
Rumor(n=10000, meetups=113887, knowing=0.8025)
Rumor(n=10000, meetups=139534, knowing=0.7938)
</code></pre></div></div>

<p>Except for very small populations, the simulation always terminates
very close to 80% rumor coverage. I don’t understand (yet) why this
is, but I find it very interesting.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  <entry>
    <title>Cartoon Liquid Simulation</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2012/02/03/"/>
    <id>urn:uuid:3819c303-f785-3d90-7c85-af2ca32b7ee4</id>
    <updated>2012-02-03T00:00:00Z</updated>
    <category term="interactive"/><category term="java"/><category term="math"/><category term="media"/><category term="video"/>
    <content type="html">
      <![CDATA[<p><strong>Update June 2013</strong>: This program has been <a href="/blog/2012/02/03/">ported to WebGL</a>!!!</p>

<p>The other day I came across this neat visual trick:
<a href="http://www.patrickmatte.com/stuff/physicsLiquid/">How to simulate liquid</a> (Flash). It’s a really simple way to
simulate some natural-looking liquid.</p>

<ul>
  <li>Perform a physics simulation of a number of circular particles.</li>
  <li>Render this simulation in high contrast.</li>
  <li>Gaussian blur the rendering.</li>
  <li>Threshold the blur.</li>
</ul>

<p><img src="/img/liquid/liquid-thumb.png" alt="" /></p>

<p>I [made my own version][fun] in Java, using <a href="http://jbox2d.org/">JBox2D</a> for the
physics simulation.</p>

<ul>
  <li><a href="https://github.com/skeeto/fun-liquid">https://github.com/skeeto/fun-liquid</a></li>
</ul>

<p>For those of you who don’t want to run a Java applet, here’s a video
demonstration. Gravity is reversed every few seconds, causing the
liquid to slosh up and down over and over. The two triangles on the
sides help mix things up a bit. The video flips through the different
components of the animation.</p>

<video src="https://s3.amazonaws.com/nullprogram/liquid/liquid-overview.webm" poster="https://s3.amazonaws.com/nullprogram/liquid/liquid-poster.png" controls="controls" width="250" height="350">
</video>

<p>It’s not a perfect liquid simulation. The surface never settles down,
so the liquid is lumpy, like curdled milk. There’s also a lack of
cohesion, since JBox2D doesn’t provide cohesion directly. However, I
think I could implement cohesion on my own by writing a custom
contact.</p>

<p>JBox2D is a really nice, easy-to-use 2D physics library. I only had to
read the first two chapters of the <a href="http://box2d.org/">Box2D</a> manual. Everything
else can be figured out through the JBox2D Javadocs. It’s also
available from the Maven repository, which is the reason I initially
selected it. My only complaint so far is that the API doesn’t really
follow best practice, but that’s probably because it follows the Box2D
C++ API so closely.</p>

<p>I’m excited about JBox2D and I plan on using it again for some future
project ideas. Maybe even a game.</p>

<p>The most computationally intensive part of the process <em>isn’t</em> the
physics. That’s really quite cheap. It’s actually blurring, by far.
Blurring involves <a href="/blog/2008/02/22/">convolving a kernel</a> over the image —
O(n^2) time. The graphics card would be ideal for that step, probably
eliminating it as a bottleneck, but it’s unavailable to pure Java. I
could have <a href="/blog/2011/11/06/">pulled in lwjgl</a>, but I wanted to keep it simple,
so that it could be turned into a safe applet.</p>

<p>As a result, it may not run smoothly on computers that are more than a
couple of years old. I’ve been trying to come up with a cheaper
alternative, such as rendering a transparent halo around each ball,
but haven’t found anything yet. Even with that fix, thresholding would
probably be the next bottleneck — something else the graphics card
would be really good at.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Try Out My Java With Emacs Workflow Within Minutes</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/11/19/"/>
    <id>urn:uuid:0096ac53-9db1-3aa8-81ed-64497696bdcb</id>
    <updated>2011-11-19T00:00:00Z</updated>
    <category term="emacs"/><category term="java"/><category term="tutorial"/>
    <content type="html">
      <![CDATA[<p><strong>Update January 2013:</strong> I’ve learned more about Java dependency
management and no longer use my old .ant repository. As a result, I
have deleted it, so ignore any references to it below. The only thing
I keep in <code class="language-plaintext highlighter-rouge">$HOME/.ant/lib</code> these days is an up-to-date <code class="language-plaintext highlighter-rouge">ivy.jar</code>.</p>

<hr />

<p>Last month I started <a href="/blog/2011/10/19/">managing my entire Emacs configuration in
Git</a>, which has already paid for itself by saving
me time. I found out a few other people have been using it (including
<a href="http://www.50ply.com/">Brian</a>), so I also <a href="https://github.com/skeeto/.emacs.d#readme">wrote up a README
file</a> describing my
specific changes.</p>

<p>With Emacs being a breeze to synchronize between my computers, I
noticed a new bottleneck emerged: my <code class="language-plaintext highlighter-rouge">.ant</code>
directory. <a href="http://ant.apache.org/">Apache Ant</a> puts everything in
<code class="language-plaintext highlighter-rouge">$ANT_HOME/lib</code> and <code class="language-plaintext highlighter-rouge">$HOME/.ant/lib</code> into its classpath. So, for
example, if you wanted to use <a href="http://www.junit.org/">JUnit</a> with Ant,
you’d toss <code class="language-plaintext highlighter-rouge">junit.jar</code> in either of those directories. <code class="language-plaintext highlighter-rouge">$ANT_HOME</code>
tends to be a system directory, and I prefer to only modify system
directories indirectly through <code class="language-plaintext highlighter-rouge">apt</code>, so I put everything in
<code class="language-plaintext highlighter-rouge">$HOME/.ant/lib</code>. Unfortunately, that’s another directory to keep
track of on my own. Fortunately, I already know how to deal with
that. It’s now another Git repository,</p>

<p><a href="https://github.com/skeeto/.ant">https://github.com/skeeto/.ant</a>
(<a href="https://github.com/skeeto/.ant#readme">README</a>)</p>

<p>With that in place, settling into a new computer for development is
almost as simple as cloning those two repositories. Yesterday I took
the step to eliminate the only significant step that remained:
<a href="/blog/2010/10/14/">setting up <code class="language-plaintext highlighter-rouge">java-docs</code></a>. Before you could really
take advantage of my Java extension, you really needed to have a
Javadoc directory scanned by Emacs. The results of that scan not only
provided an easy way to jump into documentation, but also provided the
lists for class name completion. Now, <code class="language-plaintext highlighter-rouge">java-docs</code> now automatically
loads up the core Java Javadoc, linking to the official website, if
the user never sets it up.</p>

<p>So if you want to see exactly how my Emacs workflow with Java
operates, it’s just a few small steps away. This <em>should</em> work for any
operating system suitable for Java development.</p>

<p>Let’s start by getting Java set up. First, install a JDK and Apache
Ant. This is trivial to do on Debian-based systems,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo apt-get install openjdk-6-jdk ant
</code></pre></div></div>

<p>On Windows, the JDK is easy, but Ant needs some help. You probably
need to set <code class="language-plaintext highlighter-rouge">ANT_HOME</code> to point to the install location, and you
definitely need to add it to your <code class="language-plaintext highlighter-rouge">PATH</code>.</p>

<p>Next install Git. This should be straightforward; just make sure its
in your <code class="language-plaintext highlighter-rouge">PATH</code> (so Emacs can find it).</p>

<p>Clone my <code class="language-plaintext highlighter-rouge">.ant</code> repository in your home directory.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd
git clone https://github.com/skeeto/.ant.git
</code></pre></div></div>

<p>Except for Emacs, that’s really all I need to develop with Java. This
setup should allow you to compile and hack on just about any of my
Java projects. To test it out, anywhere you like clone one of my
projects, such as my
<a href="https://github.com/skeeto/sample-java-project">example project</a>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://github.com/skeeto/sample-java-project.git
</code></pre></div></div>

<p>You should be able to build and run it now,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd sample-java-project
ant run
</code></pre></div></div>

<p>If that works, you’re ready to set up Emacs. First, install Emacs. If
you’re not familiar with Emacs, now would be the time to go through
the tutorial to pick up the basics. Fire it up and type <code class="language-plaintext highlighter-rouge">CTRL + h</code> and
then <code class="language-plaintext highlighter-rouge">t</code> (in Emacs’ terms: <code class="language-plaintext highlighter-rouge">C-h t</code>), or select the tutorial from the
menu.</p>

<p>Move any existing configuration out of the way,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mv .emacs .old.emacs
mv .emacs.d .old.emacs.d
</code></pre></div></div>

<p>Clone my configuration,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://github.com/skeeto/.emacs.d.git
</code></pre></div></div>

<p>Then run Emacs. You should be greeted with a plain, gray window: the
wombat theme. No menu bar, no toolbar, just a minibuffer, mode line,
and wide open window. Anything else is a waste of screen real
estate. This initial empty buffer has a great aesthetic, don’t you
think?</p>

<p><a href="/img/emacs/init.png"><img src="/img/emacs/init-thumb.png" alt="" /></a></p>

<p>Now to go for a test drive: open up that Java project you cloned, with
<code class="language-plaintext highlighter-rouge">M-x open-java-project</code>. That will prompt you for the root directory
of the project. The only thing this does is pre-opens all of the
source files for you, exposing their contents to <code class="language-plaintext highlighter-rouge">dabbrev-expand</code> and
makes jumping to other source files as easy as changing buffers — so
it’s not <em>strictly</em> necessary.</p>

<p>Switch to a buffer with a source file, such as
<code class="language-plaintext highlighter-rouge">SampleJavaProject.java</code> if you used my example project. Change
whatever you like, such as the printed string. You can add import
statements at any time with <code class="language-plaintext highlighter-rouge">C-x I</code> (note: capital <code class="language-plaintext highlighter-rouge">I</code>), where
<code class="language-plaintext highlighter-rouge">java-docs</code> will present you with a huge list of classes from which to
pick. The import will be added at the top of the buffer in the correct
position in the import listing.</p>

<p><a href="/img/emacs/java-import.png"><img src="/img/emacs/java-import-thumb.png" alt="" /></a></p>

<p>Without needing to save, hit <code class="language-plaintext highlighter-rouge">C-x r</code> to run the program from Emacs. A
<code class="language-plaintext highlighter-rouge">*compilation-1*</code> buffer will pop up with all of the output from Ant
and the program. If you just want to compile without running it, type
<code class="language-plaintext highlighter-rouge">C-x c</code> instead. If there were any errors, Ant will report them in the
compilation buffer. You can jump directly to these with <code class="language-plaintext highlighter-rouge">C-x `</code>
(that’s a backtick).</p>

<p><a href="/img/emacs/java-run.png"><img src="/img/emacs/java-run-thumb.png" alt="" /></a></p>

<p>Now open a new source file in the same package (same directory) as the
source file you just edited. Type <code class="language-plaintext highlighter-rouge">cls</code> and hit tab. The boilerplate,
including package statement, will be filled out for you by
YASnippet. There are a bunch of completion snippets available. Try
<code class="language-plaintext highlighter-rouge">jal</code> for example, which completes with information from <code class="language-plaintext highlighter-rouge">java-docs</code>.</p>

<p>When I’m developing a library, I don’t have a main function, so
there’s nothing to “run”. Instead, I drive things from unit tests,
which can be run with <code class="language-plaintext highlighter-rouge">C-x t</code>, which runs the “test” target if there
is one.</p>

<p><a href="/img/emacs/junit-mock.png"><img src="/img/emacs/junit-mock-thumb.png" alt="" /></a></p>

<p>To see your changes, type <code class="language-plaintext highlighter-rouge">C-x g</code> to bring up Magit and type <code class="language-plaintext highlighter-rouge">M-s</code> in
the Magit buffer (to show a full diff). From here you can make
commits, push, pull, merge, switch branches, reset, and so on. To
learn how to do all this, see the
<a href="http://philjackson.github.com/magit/magit.html">Magit manual</a>. You
can type <code class="language-plaintext highlighter-rouge">q</code> to exit the Magit window, or use <code class="language-plaintext highlighter-rouge">S-&lt;arrow key&gt;</code> to move
to an adjacent buffer in any direction.</p>

<p><a href="/img/emacs/magit.png"><img src="/img/emacs/magit-thumb.png" alt="" /></a></p>

<p>And that’s basically my workflow. Developing in C is a very similar
process, but without the <code class="language-plaintext highlighter-rouge">java-docs</code> part.</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Introducing NativeGuide</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/11/06/"/>
    <id>urn:uuid:7aa0c9ab-b5c3-3924-0422-4ae51fb80822</id>
    <updated>2011-11-06T00:00:00Z</updated>
    <category term="java"/>
    <content type="html">
      <![CDATA[<p>See it in action:
<a href="https://github.com/downloads/skeeto/sample-java-project/CubeDemo.jar">CubeDemo.jar</a> (4.7 MB) (Linux, Windows, and Mac OS X) (<a href="https://github.com/skeeto/sample-java-project/tree/lwjgl-cube">source</a>)</p>

<p>NativeGuide is a Java utility library I wrote that makes native
libraries easier to manage. Really, it’s a very small and simple
library, but it provides some critical functionality I desire and I
feel many libraries are sorely lacking. Since I would absolutely love
for other Java libraries to start using it, I went through the <a href="http://docs.sonatype.org/x/SQBl">extra
effort</a> to have it placed
conveniently in the central Maven repository:
<a href="http://search.maven.org/#artifactdetails%7Ccom.nullprogram%7Cnative-guide%7C0.2%7Cjar">com.nullprogram:native-guide</a>.</p>

<p>As a side note, I actually worked out my own staging solution rather
than rely on Maven — I always go out of my way to avoid Maven. For
reuse-ability, I added it to my <a href="/blog/2010/10/04/">sample-java-project</a>
as the “bundle” target. It generates all of the required artifacts,
digitally signs them, and bundles them up.</p>

<p>The demo at the top of this post contains native libraries for running
OpenGL programs on seven platforms. NativeGuide takes care of getting
the proper library in place for the JVM to load. All of this is
hopefully transparent to you, the user, so that this appears to be a
regular run-anywhere Java application.</p>

<p>The issue that NativeGuide solves is a special case of the
distribution problem. Distribution is one of the major problems every
language/platform must solve. That is, how do you get your application
to the end user so that they can run it? In the case of a C or C++
application, you compile it for the user’s native system, either
statically link or pack up the dependencies, and wrap it all up <a href="http://nsis.sourceforge.net/Main_Page">in an
installer</a>. Python and Perl
have working solutions for different platforms. Ruby must have
something figured out, though I don’t know what it is.</p>

<p>I believe this is one of Lisp’s biggest problems, because there’s no
real solution yet. Assuming the user already has a Lisp system
installed — a very big assumption — what do you deliver? FASL files
aren’t compatible between Lisps and sometimes even between versions of
the same Lisp. You’re left either targeting their specific Lisp system
or distributing source — which either you can’t do or you really
can’t expect the user to compile. That’s a long ways away from a
simple double-click shortcut. If you somehow got that work, then how
to you make it convenient to launch?</p>

<p>If the user doesn’t have a Lisp system installed you then have to
package your own. <a href="http://maxima.sourceforge.net/">Maxima</a> does this,
but their solution takes a lot of work and maintenance. It’s
unreasonable for every application to do
this. <a href="http://www.sbcl.org/">SBCL</a> is pretty close to making that part
work well, through a feature to save executable images. However,
<a href="http://xach.livejournal.com/295584.html">until very recently</a> this
came with lots of overhead. A “Hello, World” program would be around
60 MB, since it includes an entire Common Lisp system. Another problem
is the program is entirely integrated to the particular SBCL with
which it was compiled. The user can’t install a newer, potentially
more secure, SBCL and run it with the new one.</p>

<p>I think Java’s method of application distribution is really nice. The
JRE is easy to install so it’s available almost
everywhere. Unfortunately, when it’s not installed and you try to
package a JRE with your application, the situation starts to look like
SBCL. Fortunately, that’s not a very common problem. Applications can
be packed up into a single <code class="language-plaintext highlighter-rouge">.jar</code> file, including all the art assets,
configuration XML, and so on, and distributed as a single file, which
is <em>usually</em> easy to launch. Java provides special support for
accessing those packed up resources right from the packaging:
[<code class="language-plaintext highlighter-rouge">Class.getResource()</code>](http://download.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String%29)
and
[<code class="language-plaintext highlighter-rouge">Class.getResourceAsStream()</code>](http://download.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String%29).</p>

<p><em>However</em>, the same courtesy is not provided for packed up native
libraries. There’s no support for loading them from within a <code class="language-plaintext highlighter-rouge">.jar</code>
file. What sometimes happens is these libraries end up being delivered
alongside the application. They have to be installed <em>somewhere</em> and
there has to be some kind of OS/architecture detection in the
launcher, the hardest place to do it, to determine the right libraries
to use. In a few cases they’re packed up with the application, which
copies them out to a temporary directory for loading. That’s even more
effort duplication, having to detect the OS and architecture again,
figuring out where exactly to copy them, what to do if they’ve already
been copied, maybe updating the <code class="language-plaintext highlighter-rouge">java.library.path</code> which isn’t as
sample as just setting the system property.</p>

<p>Libraries often don’t worry about that part, leaving it to the users
of the libraries to figure something out. Everyone using the library
makes their own solutions in parallel when it would have been better
if the work was done just once by the library. (A <a href="http://jline.sourceforge.net/#installation">few
libraries</a> <em>have</em> done the
right thing.)</p>

<p>The goal of NativeGuide is to make all of that mess go away. You pack
up your native libraries as resources and register them with
NativeGuide at run-time. NativeGuide detects which library the JRE can
use, copies the correct ones to a temporary directory, and appends
that directory to the <code class="language-plaintext highlighter-rouge">java.library.path</code> if needed. For example, this
is what registration looks like,</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">NativeGuide</span><span class="o">.</span><span class="na">prepare</span><span class="o">(</span><span class="nc">Arch</span><span class="o">.</span><span class="na">LINUX_32</span><span class="o">,</span> <span class="s">"/x86/libexample.so"</span><span class="o">);</span>
<span class="nc">NativeGuide</span><span class="o">.</span><span class="na">prepare</span><span class="o">(</span><span class="nc">Arch</span><span class="o">.</span><span class="na">LINUX_64</span><span class="o">,</span> <span class="s">"/amd64/libexample.so"</span><span class="o">);</span>
<span class="nc">NativeGuide</span><span class="o">.</span><span class="na">prepare</span><span class="o">(</span><span class="nc">Arch</span><span class="o">.</span><span class="na">WINDOWS_32</span><span class="o">,</span> <span class="s">"/x86/example.dll"</span><span class="o">);</span>
<span class="nc">NativeGuide</span><span class="o">.</span><span class="na">prepare</span><span class="o">(</span><span class="nc">Arch</span><span class="o">.</span><span class="na">WINDOWS_64</span><span class="o">,</span> <span class="s">"/amd64/example.dll"</span><span class="o">);</span>
</code></pre></div></div>

<p>Outside of this registration, the whole thing is transparent. I’ve
already used it with two projects allowing me to package them up into
a single <code class="language-plaintext highlighter-rouge">.jar</code> file as if no native library was being used. One is a
project at work which uses
<a href="http://rxtx.qbang.org/wiki/index.php/Main_Page">RXTX</a> and the other
is a branch of my sample-java-project:
<a href="https://github.com/skeeto/sample-java-project/tree/lwjgl">lwjgl</a>. This
allows me to produce a single <code class="language-plaintext highlighter-rouge">.jar</code> OpenGL application that users on
Linux, Windows, and Mac OS X can just double-click to run.</p>

<p>So my hope is to get libraries using NativeGuide to save everyone
time. The users of the library would probably be unaware that
NativeGuide is there. Just like all of my code, I made it public
domain, so there can be no license objections. However, if the library
maintainers don’t choose use it, I made it flexible enough that you
can work around them with little trouble.</p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  <entry>
    <title>Halftone</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/10/13/"/>
    <id>urn:uuid:99d32cd7-9102-3d62-01e5-a9dfee616fab</id>
    <updated>2011-10-13T00:00:00Z</updated>
    <category term="java"/>
    <content type="html">
      <![CDATA[<p>I recently toyed around with some halftone, a technique for simulating
continuous tone images using solid dots. I can’t remember what
specifically gave me the idea to try it out. Perhaps it was because it
provided a good use-case for my <a href="/blog/2011/08/30/">newly discovered hot code
replacement</a>.</p>

<p><a href="/img/halftone/halftone.png"><img src="/img/halftone/halftone-thumb.png" alt="" /></a></p>

<pre>
git clone <a href="https://github.com/skeeto/Halftone">git://github.com/skeeto/Halftone.git</a>
</pre>

<p>Halftone dates back to the 19th century and was the first low-cost
method for printing images because it didn’t require highly skilled
artists. What made it so inexpensive was that producing the relief
surface was an entirely mechanical process. Light is projected through
a negative, through a mesh screen, and onto a plate containing light
sensitive chemicals. Brighter parts of the image would form larger
spots and dimmer parts smaller dots. The chemical on the plate would
react to the light and rise up very slightly. The plate is then inked
and used for printing.</p>

<p>Halftone printing is still used today, but, of course, the process for
generating the halftone version of an image is all done with
computers. Digital halftoning. Digital halftoning provides several
different ways to arrange the dots: by size (amplitude modulation), by
spacing (frequency modulation), by shape, or any combination of
these. In my little demo above I took the simplest route, by size.</p>

<p><a href="/img/halftone/halftone-eye.png"><img src="/img/halftone/halftone-eye-thumb.png" alt="" /></a></p>

<p>I scale the image down using bicubic interpolation (thanks to the
handy
<a href="http://download.oracle.com/javase/6/docs/api/java/awt/geom/AffineTransform.html">AffineTransform</a>). With
it scaled down, each pixel becomes a single dot in my final
image. Since I want the dots to fully fill their space at the most
extreme, their maximum radius is the square root of two times the
spacing. That is, the dots will just touch on the diagonal when
full. To determine magnitude of the dot I used the [luma
coefficients](http://en.wikipedia.org/wiki/Luma_(video%29). That makes
the RGB values weighted more accurately to the way human sight
perceives brightness.</p>

<p>Rotating the image would be an improvement over the flat grid it is
now. A 45-degree rotation helps break up potential patterns. I tried
to do this, but I couldn’t get the math right along with the correct
parameters to the AffineTransform. Something was always getting
clipped or padded incorrectly. Adding CMYK color would also be
interesting, and would also require rotation of the dot grid — each
color gets its own angle.</p>

<p>I also thought about having it dump out the image in vector form as a
SVG or PostScript, which would make it start to behave like <a href="http://homokaasu.org/rasterbator/">The
Rasterbator</a>. With that output, it
would only need to split up that output into normal-sized pages and I
could use it to produce large images from a cheap printer.</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Java Hot Code Replacement</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/08/30/"/>
    <id>urn:uuid:fa8ed0d0-5edc-3f0b-a0bc-f6dce98378f7</id>
    <updated>2011-08-30T00:00:00Z</updated>
    <category term="java"/>
    <content type="html">
      <![CDATA[<p>I finally started taking advantage of a JVM feature that’s been around
for almost a decade: hot code replacement. HCR was introduced in 1.4
as part of the Java Platform Debugger Architecture (JPDA). It provides
the ability for code to be updated seamlessly in a running Java
program. This can really cut down on the development cycle because the
program doesn’t need to be started over from the beginning for every
little change.</p>

<p>This is not actually a new concept or development style for
me. Updating live, running code is fundamentally how Lisp programs are
developed. This is how I <a href="/blog/2009/05/17/">wrote my Emacs web
server</a>. I opened a socket to listen on 8080, which
originally did nothing but accept connections, and built up a web
server behind the socket without ever taking it down. It’s be unusual
to develop Lisp any other way.</p>

<p>Eclipse has directly supported HCR for some years now. I had heard
about it, but never investigated the issue until I saw Markus “Notch”
Persson using it while coding his
<a href="http://www.ludumdare.com/compo/">Ludum Dare</a>
<a href="http://s3.amazonaws.com/ld48/index.html">entry</a>
(<a href="https://s3.amazonaws.com/ld48/PoC_source.zip">source</a>) on a
live-stream. It was really neat to see it in use on a graphical
program.</p>

<p>If you know anything about my professional habits, you know I’m not a
fan of giant IDEs like Eclipse. I hack Java with a combination of Ant
and Emacs, <a href="/blog/2010/10/15/">with my own custom extensions</a>. So any
hotswap solution has to be built on that. Luckily, I found this great
Ant extension: <a href="http://code.google.com/p/hotswap/">hotswap</a>. It
provides a <code class="language-plaintext highlighter-rouge">hotswap</code> task for performing HCR.</p>

<p>It relies on Ant to prepare replacements and determine <em>which</em> files
are to be swapped. They provide an example target on their website
demonstrating how to set it up. Personally, I think it’s a sloppy way
to do it. It writes a timestamp to a string (the only Ant data
structure available for this), redundantly performs compilation, then
parses the time string to compare it to all of the files, picking out
new ones.</p>

<p>There’s actually an <code class="language-plaintext highlighter-rouge">modified</code> selector exactly for this type of
job. Here’s my solution (as seen in my
<a href="/blog/2010/10/04/">sample-java-project</a>),</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;target</span> <span class="na">name=</span><span class="s">"hotswap"</span> <span class="na">depends=</span><span class="s">"compile"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;taskdef</span> <span class="na">name=</span><span class="s">"hotswap"</span> <span class="na">classname=</span><span class="s">"dak.ant.taskdefs.Hotswap"</span><span class="nt">/&gt;</span>
  <span class="nt">&lt;hotswap</span> <span class="na">verbose=</span><span class="s">"true"</span> <span class="na">port=</span><span class="s">"9000"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;fileset</span> <span class="na">dir=</span><span class="s">"${build.classes.dir}"</span> <span class="na">includes=</span><span class="s">"**/*.class"</span><span class="nt">&gt;</span>
      <span class="nt">&lt;modified/&gt;</span>
    <span class="nt">&lt;/fileset&gt;</span>
  <span class="nt">&lt;/hotswap&gt;</span>
<span class="nt">&lt;/target&gt;</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">modified</code> filter is not timestamp based. It creates a
<code class="language-plaintext highlighter-rouge">cache.properties</code> file containing the hash of all of your class
files. Trivial changes, such as to comments or whitespace, will not
trigger for replacement. Because that’s taken care of without the
timestamp business, no need to write out the compile task again. We
can just call the original as a dependency of this target.</p>

<p>An easy way to try this out for yourself now is with the
<a href="https://github.com/skeeto/october-chess-engine/tree/hotswap-demo"><code class="language-plaintext highlighter-rouge">hotswap-demo</code>
branch</a>
of my chess engine. (This branch is special because it forces the GUI
to redraw every second, causing changes to take effect immediately.)
Check out that branch, run the program with the <code class="language-plaintext highlighter-rouge">run</code> target, then in
<code class="language-plaintext highlighter-rouge">BoardPanel.java</code> change the colors of the board in <code class="language-plaintext highlighter-rouge">paintComponent()</code>
— change <code class="language-plaintext highlighter-rouge">LIGHT</code> to <code class="language-plaintext highlighter-rouge">Color.WHITE</code> and <code class="language-plaintext highlighter-rouge">DARK</code> to <code class="language-plaintext highlighter-rouge">Color.GRAY</code>, for
example. Then, without stopping the program, run the <code class="language-plaintext highlighter-rouge">hotswap</code> target.
Ant will inject the new code into the running program and the board
will change before your eyes.</p>

<p>I look forward to making good use of this in the future. Expect it to
be a typical Ant target in all of my Java projects from now on.</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>October Chess Engine Updates</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/08/24/"/>
    <id>urn:uuid:438369c7-5406-3133-f427-237674b1e53e</id>
    <updated>2011-08-24T00:00:00Z</updated>
    <category term="java"/><category term="game"/>
    <content type="html">
      <![CDATA[<p>When I wrote a <a href="/blog/2010/10/17/">chess engine</a> a year ago, I left it
in a slightly incomplete state. The original intention was to try out
an old <a href="/blog/2007/10/24/">genetic algorithm idea</a> of mine, and
creating a chess engine was just a side effect of that. Well, that
didn’t work out so well since the vast majority of my engine’s games
against itself would end in ties, leaving me with very little data to
work with.</p>

<p>I was left with a working chess engine with some rough edges. Mainly,
there was an “undo move” option that didn’t work right, the graphics
could use a little work, and the only way to set the engine’s strength
was by editing a text file and injecting it into the classpath.</p>

<p>Six months later it got
<a href="/blog/2011/04/09/">some attention on a chess enthusiast forum</a>. I
gave some advice on how to tweak the engine a bit and it made me
realize how hard that is for many people to do. “Hey, there are some
people actually interested in using my unnamed chess engine. Cool! I
should probably fix some of those rough edges.” So I did.</p>

<p>First I gave it a name, since no one on that forum seemed to know what
to call it. Most of the work was done in October of 2010, so I went
with that: <strong>October</strong>. The October Chess Engine. It’s also now in the
public domain, no copyrights attached.</p>

<p>Next, since I’ve learned so much about Java 2D graphics in the last
year, I reworked the graphics. The graphics code is shorter and
simpler, the GUI looks nicer, and it now permits user resizing of the
window. It’s also a little larger by default.</p>

<p>I fixed the engine so that it can search an odd number of plies. All
it needed was a a sign change in one place. The hard part was figuring
out where exactly it needed to be done. With that fixed, I modified
the GUI so that the user can select the difficulty setting.</p>

<p><img src="/img/chess/difficulty.png" alt="" /></p>

<p>I’ve also advanced my knowledge of Java threading, cleaning up thread
management in the engine. There’s no difference from a user
perspective, except that it no longer triggers thread-related JVM bugs
— which I’ve seen occur when rapidly instantiating and tearing down
many threads.</p>

<p>As a side-effect of tidying threading, I made an experimental branch
(<a href="https://github.com/skeeto/october-chess-engine/tree/distributed"><code class="language-plaintext highlighter-rouge">distributed</code></a>)
that allows the AI to make use of other computers in the network. The
entire board state is serialized, along with a single unevaluated
move, and sent off to other machines. They analyze the move and report
back with the move’s score.</p>

<p>While investigating a move can be done independently, it misses out on
a serious optimization. Scores from previous moves can be used to
constrain the current search, allowing the AI to skip over entire
branches of the search tree
(<a href="http://en.wikipedia.org/wiki/Alpha-beta_pruning">alpha-beta pruning</a>).
When all 30-some possible moves are evaluated in parallel, that
optimization is completely lost. As a result, going from one machine
to two equal machines tends to have no real speedups, because
cumulatively they have to work harder than a single machine. It’s not
until several machines are added that the optimization loss is
overcome.</p>

<p>Also with the threading change, I added an AI time estimate, so the
user knows how long the AI will take. This is important with the new
difficulty settings, since high difficulties can take awhile to
compute. Sometimes it’s wildly off, particularly when the AI only
takes a few seconds, but, to my own surprise, it can be quite accurate
when the AI is taking several minutes to complete its turn. Because of
the previously-mentioned optimization, the AI speeds up as it
progresses, so newer timings are weighted more than older timings.</p>

<p>And finally, one of the most visible changes to the user, I created an
<a href="http://nsis.sourceforge.net/">NSIS installer</a> for the Windows users
(available in the downloads section of
<a href="https://github.com/skeeto/october-chess-engine">October’s website</a>). They
can click their way through a familiar install wizard, making the
chess engine a neatly-packaged product. I got the idea from
<a href="http://crawl.develz.org/wordpress/">DCSS</a>, which has a very well
organized build system and makes good use of NSIS.</p>

<p>In the future I’d like to tidy up the experimental distributed AI
stuff, possibly rebuild it on top of Java RMI. I’d also like to add
support for the Universal Chess Interface (UCI). That would allow me
to determine an accurate rating for October, and it would give me an
excellent excuse to not do any more GUI work because another GUI could
easily be used in its place.</p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  <entry>
    <title>Pendulum Waves</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/07/09/"/>
    <id>urn:uuid:55f2b1d8-a373-3b77-b7a8-1c638faba189</id>
    <updated>2011-07-09T00:00:00Z</updated>
    <category term="java"/>
    <content type="html">
      <![CDATA[<p>Project source,</p>

<ul>
  <li><a href="https://github.com/skeeto/PendulumWaves">https://github.com/skeeto/PendulumWaves</a></li>
</ul>

<p>My grandfather send me this video last week:
<a href="http://goo.gl/IcA5p">Harvard Natural Sciences Lecture Demonstrations: Pendulum Waves</a>.
Fifteen pendulums are tuned to oscillate at 51 cycles-per-minute to 65
cycles-per-minutes. It creates interesting aliasing effects for one
minute, after which the pendulums come back into sync and the system
starts over again.</p>

<p>I thought it was interesting enough to simulate in software, so I made
an applet for it,</p>

<p><a href="/PendulumWaves/"><img src="/img/screenshot/pendulum-waves.png" alt="" /></a></p>

<p>That should be exactly in sync with the video, so you can watch them
side-by-side and see the same patterns.</p>

]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Infinite Parallax Starfield</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/06/13/"/>
    <id>urn:uuid:6e9e0ad7-2a63-3c73-bdbc-ced783911f62</id>
    <updated>2011-06-13T00:00:00Z</updated>
    <category term="java"/><category term="video"/>
    <content type="html">
      <![CDATA[<p>In my free time I’ve been working on an unannounced line-art space
shooter game called Hypernova. It looks a little like <em>Asteroids</em>, but
the screen doesn’t wrap around at all. Space is infinite, and there will
be all sorts of things going on out there. Quests, loot, ship upgrades
and enhancements, hirelings.</p>

<p><a href="/img/hypernova/hypernova.png"><img src="/img/hypernova/hypernova-thumb.png" alt="" /></a></p>

<p>It will be using no bitmapped images. All the graphics are vector images
described by text files. I was originally intending to follow the same
path with sound effects, and rely mostly on MIDI. However, I quickly
found out that many computers have no MIDI support at all.</p>

<p>One of the early challenges was a nice starfield background. It has
several constraints:</p>

<ul>
  <li>Can’t use any bitmapped images.</li>
  <li>Must work over practically infinite space.</li>
  <li>I must be able to resize the display</li>
  <li>Must be fast.</li>
</ul>

<p>And in addition, there are some unnecessary, but desirable, properties,</p>

<ul>
  <li>
    <p>When leaving a particular location and returning, I’d like to see the
same starfield pattern again.</p>
  </li>
  <li>
    <p>At the same time, I never want to see that same pattern at a different
position.</p>
  </li>
</ul>

<p>When I was a kid I created the effect as a project, but it didn’t have
the both the desired properties above. It’s also the method I found over
and over when searching the Internet. There is an array of stars. Star
positions are translated as the camera moves. If a star ever exits the
display, replace it at a random position on the edge of the screen. To
create a parallax effect, each star’s translation is scaled by a unique
random factor.</p>

<p>However, there’s another algorithm I like much better, and it has both
the desirable properties. Space is broken up into a grid of square
tiles. To determine the star pattern in any given tile, hash the tile’s
position, and use the hash output to generate a few positions within the
tiles, which is where stars are drawn. To create a parallax effect,
perform it in different layers at different scales.</p>

<p>Here’s what it looks like in the game,</p>

<p><img src="/img/hypernova/starfield.gif" alt="" /></p>

<p>Hypernova is written in Java, with Clojure as a scripting language, so
the starfield drawing function looks like this.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">STAR_SEED</span> <span class="o">=</span> <span class="mh">0x9d2c5680</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">STAR_TILE_SIZE</span> <span class="o">=</span> <span class="mi">256</span><span class="o">;</span>

<span class="kd">public</span> <span class="kt">void</span> <span class="nf">drawStars</span><span class="o">(</span><span class="nc">Graphics2D</span> <span class="n">g</span><span class="o">,</span> <span class="kt">int</span> <span class="n">xoff</span><span class="o">,</span> <span class="kt">int</span> <span class="n">yoff</span><span class="o">,</span> <span class="kt">int</span> <span class="n">starscale</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">size</span> <span class="o">=</span> <span class="no">STAR_TILE_SIZE</span> <span class="o">/</span> <span class="n">starscale</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">w</span> <span class="o">=</span> <span class="n">getWidth</span><span class="o">();</span>
    <span class="kt">int</span> <span class="n">h</span> <span class="o">=</span> <span class="n">getHeight</span><span class="o">();</span>

    <span class="cm">/* Top-left tile's top-left position. */</span>
    <span class="kt">int</span> <span class="n">sx</span> <span class="o">=</span> <span class="o">((</span><span class="n">xoff</span> <span class="o">-</span> <span class="n">w</span><span class="o">/</span><span class="mi">2</span><span class="o">)</span> <span class="o">/</span> <span class="n">size</span><span class="o">)</span> <span class="o">*</span> <span class="n">size</span> <span class="o">-</span> <span class="n">size</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">sy</span> <span class="o">=</span> <span class="o">((</span><span class="n">yoff</span> <span class="o">-</span> <span class="n">h</span><span class="o">/</span><span class="mi">2</span><span class="o">)</span> <span class="o">/</span> <span class="n">size</span><span class="o">)</span> <span class="o">*</span> <span class="n">size</span> <span class="o">-</span> <span class="n">size</span><span class="o">;</span>

    <span class="cm">/* Draw each tile currently in view. */</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">sx</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">w</span> <span class="o">+</span> <span class="n">sx</span> <span class="o">+</span> <span class="n">size</span> <span class="o">*</span> <span class="mi">3</span><span class="o">;</span> <span class="n">i</span> <span class="o">+=</span> <span class="n">size</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="n">sy</span><span class="o">;</span> <span class="n">j</span> <span class="o">&lt;=</span> <span class="n">h</span> <span class="o">+</span> <span class="n">sy</span> <span class="o">+</span> <span class="n">size</span> <span class="o">*</span> <span class="mi">3</span><span class="o">;</span> <span class="n">j</span> <span class="o">+=</span> <span class="n">size</span><span class="o">)</span> <span class="o">{</span>
            <span class="kt">int</span> <span class="n">hash</span> <span class="o">=</span> <span class="n">mix</span><span class="o">(</span><span class="no">STAR_SEED</span><span class="o">,</span> <span class="n">i</span><span class="o">,</span> <span class="n">j</span><span class="o">);</span>
            <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">n</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mi">3</span><span class="o">;</span> <span class="n">n</span><span class="o">++)</span> <span class="o">{</span>
                <span class="kt">int</span> <span class="n">px</span> <span class="o">=</span> <span class="o">(</span><span class="n">hash</span> <span class="o">%</span> <span class="n">size</span><span class="o">)</span> <span class="o">+</span> <span class="o">(</span><span class="n">i</span> <span class="o">-</span> <span class="n">xoff</span><span class="o">);</span>
                <span class="n">hash</span> <span class="o">&gt;&gt;=</span> <span class="mi">3</span><span class="o">;</span>
                <span class="kt">int</span> <span class="n">py</span> <span class="o">=</span> <span class="o">(</span><span class="n">hash</span> <span class="o">%</span> <span class="n">size</span><span class="o">)</span> <span class="o">+</span> <span class="o">(</span><span class="n">j</span> <span class="o">-</span> <span class="n">yoff</span><span class="o">);</span>
                <span class="n">hash</span> <span class="o">&gt;&gt;=</span> <span class="mi">3</span><span class="o">;</span>
                <span class="n">g</span><span class="o">.</span><span class="na">drawLine</span><span class="o">(</span><span class="n">px</span><span class="o">,</span> <span class="n">py</span><span class="o">,</span> <span class="n">px</span><span class="o">,</span> <span class="n">py</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Assuming the origin is in the center of the display, it iterates over
each tile currently covered by the display. Positions are created by
looking at the first couple bits of the hash for X, shift a few off, and
looking at the first few bits again for Y. Repeat until we run out of
bits. It’s called with different <code class="language-plaintext highlighter-rouge">starscale</code>s, back to front (darker to
lighter), to create layers.</p>

<p>The <code class="language-plaintext highlighter-rouge">STAR_SEED</code> is just a Mersenne prime from the Mersenne Twister PRNG.
It probably doesn’t matter much what you choose for the seed, but
changing it by a single bit will drastically alter the starfield.</p>

<p>As far as I know, Java comes with no decent 32-bit (int) hash functions,
which is really one of the biggest roadblocks in implementing effective
<code class="language-plaintext highlighter-rouge">hashCodes()</code>s. Fortunately, I found an excellent hash function, <a href="http://www.concentric.net/~ttwang/tech/inthash.htm">Robert
Jenkins’ 96 bit Mix
Function</a>, to do the
trick.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/** Robert Jenkins' 96 bit Mix Function. */</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">mix</span><span class="o">(</span><span class="kt">int</span> <span class="n">a</span><span class="o">,</span> <span class="kt">int</span> <span class="n">b</span><span class="o">,</span> <span class="kt">int</span> <span class="n">c</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">-</span><span class="n">b</span><span class="o">;</span>  <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">-</span><span class="n">c</span><span class="o">;</span>  <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">^(</span><span class="n">c</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">13</span><span class="o">);</span>
    <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">-</span><span class="n">c</span><span class="o">;</span>  <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">-</span><span class="n">a</span><span class="o">;</span>  <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">^(</span><span class="n">a</span> <span class="o">&lt;&lt;</span> <span class="mi">8</span><span class="o">);</span>
    <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">-</span><span class="n">a</span><span class="o">;</span>  <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">-</span><span class="n">b</span><span class="o">;</span>  <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">^(</span><span class="n">b</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">13</span><span class="o">);</span>
    <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">-</span><span class="n">b</span><span class="o">;</span>  <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">-</span><span class="n">c</span><span class="o">;</span>  <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">^(</span><span class="n">c</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">12</span><span class="o">);</span>
    <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">-</span><span class="n">c</span><span class="o">;</span>  <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">-</span><span class="n">a</span><span class="o">;</span>  <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">^(</span><span class="n">a</span> <span class="o">&lt;&lt;</span> <span class="mi">16</span><span class="o">);</span>
    <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">-</span><span class="n">a</span><span class="o">;</span>  <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">-</span><span class="n">b</span><span class="o">;</span>  <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">^(</span><span class="n">b</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">5</span><span class="o">);</span>
    <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">-</span><span class="n">b</span><span class="o">;</span>  <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">-</span><span class="n">c</span><span class="o">;</span>  <span class="n">a</span><span class="o">=</span><span class="n">a</span><span class="o">^(</span><span class="n">c</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">3</span><span class="o">);</span>
    <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">-</span><span class="n">c</span><span class="o">;</span>  <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">-</span><span class="n">a</span><span class="o">;</span>  <span class="n">b</span><span class="o">=</span><span class="n">b</span><span class="o">^(</span><span class="n">a</span> <span class="o">&lt;&lt;</span> <span class="mi">10</span><span class="o">);</span>
    <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">-</span><span class="n">a</span><span class="o">;</span>  <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">-</span><span class="n">b</span><span class="o">;</span>  <span class="n">c</span><span class="o">=</span><span class="n">c</span><span class="o">^(</span><span class="n">b</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">15</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">c</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<video src="/vid/hypernova/hypernova.ogv" controls="" poster="/vid/hypernova/hypernova-poster-small.png" width="600" height="450">
</video>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Feedback Loop Applet</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/05/01/"/>
    <id>urn:uuid:953638ec-fa1e-36a4-397e-2aeb435aebbd</id>
    <updated>2011-05-01T00:00:00Z</updated>
    <category term="java"/><category term="interactive"/>
    <content type="html">
      <![CDATA[<p><em>Update June 2014</em>: This <a href="/blog/2014/06/21/">was ported to WebGL</a> and greatly
improved.</p>

<ul>
  <li><a href="https://github.com/skeeto/Feedback.git">https://github.com/skeeto/Feedback.git</a></li>
</ul>

<p>I was watching the BBC’s <em>The Secret Life of Chaos</em>, which is a very
interesting documentary about chaos, <a href="/blog/2007/10/01/">fractals</a>, and emergent
behavior. There is <a href="magnet:?xt=urn:btih:80e59413ca2b46e74f4a7572366a4a7de9b3e096">a part where emergent behavior is demonstrated using
a video camera feedback loop</a> (35 minutes in). A camera, pointed
at a projector screen, has it’s output projected onto that same screen.
A match is lit, moved around a bit, and removed from the camera’s
vision. At the center of the camera’s focus a pattern dances around for
awhile in an unpredictable pattern, as the pattern is fed back into
itself.</p>

<p>That’s the key to fractals and emergent behavior right there: a feedback
loop. Apply some simple rules to a feedback loop and you might have a
fractal on your hands. More examples,</p>

<ul>
  <li><a href="http://www.youtube.com/watch?v=Jj9pbs-jjis">How to make fractals without a computer</a></li>
  <li><a href="http://www.youtube.com/watch?v=xzJVbmqcj7k">video feedback experiment 4</a></li>
</ul>

<p>I was inspired to simulate this with software (and I <a href="http://devrand.org/view/emergentFeedback">passed that on to
Gavin too</a>). Take an image, rescale it, rotate it, compose it
with itself, repeat.</p>

<p>Here are some images I created with it.</p>

<p><img src="/img/feedback/dense-tunnel.png" alt="" />
<img src="/img/feedback/single-spiral.png" alt="" />
<img src="/img/feedback/sun2.png" alt="" />
<img src="/img/feedback/jagged-spiral.png" alt="" /></p>

<p>You can interact with the mouse — like the lit match. And that really is
a feedback loop. In this video, you can see the mouse hop travel down
through the iterations.</p>

<video src="/vid/feedback/hop.ogv" controls="controls" width="640" height="640">
</video>

<p>Unfortunately I didn’t seem to be able to achieve emergent behavior. The
image operators too aggressively blur out fine details way down in the
center. Bit that’s fine: it turned out more visually appealing than I
expected!</p>

<p>Here’s a gallery of image captures from the applet. To achieve some of
the effects try adjusting the rotation angle (press r or R) and scale
factor (press g or G) while running the app. A couple of these were made
using an experimental fractal-like image operator that can only be
turned on in the source code.</p>

<p class="grid"><a href="/img/feedback/fractal.png"><img src="/img/feedback/fractal-thumb.png" alt="" /></a>
<a href="/img/feedback/gimpy.png"><img src="/img/feedback/gimpy-thumb.png" alt="" /></a>
<a href="/img/feedback/green-spots.png"><img src="/img/feedback/green-spots-thumb.png" alt="" /></a>
<a href="/img/feedback/halo.png"><img src="/img/feedback/halo-thumb.png" alt="" /></a>
<a href="/img/feedback/orange-star.png"><img src="/img/feedback/orange-star-thumb.png" alt="" /></a>
<a href="/img/feedback/pink-spiral.png"><img src="/img/feedback/pink-spiral-thumb.png" alt="" /></a>
<a href="/img/feedback/spin-blur.png"><img src="/img/feedback/spin-blur-thumb.png" alt="" /></a>
<a href="/img/feedback/spin-spiral.png"><img src="/img/feedback/spin-spiral-thumb.png" alt="" /></a>
<a href="/img/feedback/spiral.png"><img src="/img/feedback/spiral-thumb.png" alt="" /></a>
<a href="/img/feedback/star.png"><img src="/img/feedback/star-thumb.png" alt="" /></a>
<a href="/img/feedback/sun.png"><img src="/img/feedback/sun-thumb.png" alt="" /></a>
<a href="/img/feedback/tunnel.png"><img src="/img/feedback/tunnel-thumb.png" alt="" /></a>
<a href="/img/feedback/gear.png"><img src="/img/feedback/gear-thumb.png" alt="" /></a></p>

]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>October's Chess Engine Gets Some Attention</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2011/04/09/"/>
    <id>urn:uuid:bf181782-accb-396e-2855-b7e49b23f2db</id>
    <updated>2011-04-09T00:00:00Z</updated>
    <category term="java"/><category term="game"/>
    <content type="html">
      <![CDATA[<p>Looking at my server logs the other I noticed that the unnamed <a href="/blog/2010/10/17/">Chess
engine I wrote this past October</a> recently got <a href="http://immortalchess.net/forum/showthread.php?t=8845">some attention on
the Immortal Chess forum</a>. As far as I know this is the first
time anyone who’s good at Chess has played it. They were analyzing its
behavior a bit too.</p>

<p>As I expected, in its default setting (the <em>only</em> setting without
editing text configuration files) it’s a pretty weak engine. I did this
to keep is fast, so its turns would take only seconds even on older
hardware. In this state it searches four plies (good engines get as high
as 12). They were able to defeat it easily.</p>

<p><img src="/img/chess/chess-defeat.png" alt="" /></p>

<p>I posted some information on how they can tweak the engine without
having to edit source code or download any new files. Specifically, it’s
easy to increase the search depth to six plies, or more. This
information may be useful in general for anyone wanting to tweak my
Chess engine.</p>

<blockquote>
  <p>You can increase the AI’s strength with some trickery, without having
to go to the source code. Open the .jar file with your favorite
archive manager (looks like 7-Zip is popular around here), and locate
the file <code class="language-plaintext highlighter-rouge">com/nullprogram/chess/ai/default.properties</code>. Open it up in
a text editor and you can see some configuration for the AI (and
remember to save your changes back into the .jar file).</p>

  <p>The most important setting is “depth”, which is a default of 4 plies
right now. You can set this to any <strong>even</strong> number. If you’re on
modern hardware, 6 plies is still reasonably fast. 8 if you’re
patient. It’s multithreaded, so more cores means faster AI. Each
increase in ply is probably a strength increase of about 200-250, so 4
to 6 is about a 450 point increase.</p>

  <p>You can also adjust piece values and situational weights (“safety” is
king safety), which could possibly yield a more powerful AI. Changing
these will not cause any more CPU use, but the payoff will probably be
little.</p>
</blockquote>

<p>The next step to making it stronger would be running a Java profiler,
finding the bottlenecks, and getting the engine sped up enough to search
more plies in the same amount of time. This would certainly involve
tightening up memory use, because the tree search currently creates lots
and lots of garbage. Another option is using opening books, but that’s
not something I’m interested in doing — I like that it currently doesn’t
really rely on any domain knowledge.</p>

<p>Even though it’s a below-average engine, it looks like it still made it
into some personal Chess engine collections. Perhaps I should have put
some credits in there so that, in the future, they could have found
their way back here. I should have also stuck the source code in the
.jar so they’d have it around too.</p>

]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Sudoku Applet</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/20/"/>
    <id>urn:uuid:8451de1d-f0c4-3001-2e5a-5720aaa17ed4</id>
    <updated>2010-10-20T00:00:00Z</updated>
    <category term="java"/><category term="interactive"/><category term="game"/>
    <content type="html">
      <![CDATA[<!-- 20 October 2010 -->
<p>
<img src="/img/sudoku/small.png" alt="" class="right"/>

Over the last two evenings I created this, a Sudoku Java applet.
</p>
<pre>
git clone <a href="https://github.com/skeeto/Sudoku">git://github.com/skeeto/Sudoku.git</a>
</pre>
<p>

The hardest part was creating and implementing the algorithm for
generating new Sudokus. The first step to writing any Sudoku generator
is to <a href="/blog/2008/07/20/">write a Sudoku solver</a>. Use it to
solve an empty board in a random order, then back off while
maintaining a single solution. For a proper Sudoku, this has to be
done symmetrically leaving no more than 32 givens.
</p>
<p>
I didn't work out a great way to determine the difficulty of a
particular puzzle. The proper way would probably be to solve it a few
different ways and measure the number of steps taken. Right now I'm
controlling difficulty by adjusting the number of givens: 24 (hard),
28 (medium), and 32 (easy). Harder puzzles take longer to generate
because the search-space is less dense, due to the strict constraints.
</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Java Applets Demo Page</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/18/"/>
    <id>urn:uuid:0caa6106-7605-3b67-59c2-215e415f062f</id>
    <updated>2010-10-18T00:00:00Z</updated>
    <category term="java"/><category term="interactive"/><category term="game"/>
    <content type="html">
      <![CDATA[<!-- 18 October 2010 -->
<p class="abstract">
  Update February 2013: Java Applets are a dead technology and using a
  Java web browser plugin is simply much too insecure. I strongly
  recommend against it. This applet page has since been moved to a
  more generally-named URL.
</p>

<p>
Because the two projects I announced over the weekend can be used as
Java applets, I went back and upgraded <a href="/blog/2007/10/08/">
two older</a> <a href="/blog/2009/12/13/">projects</a> so that they
could also behave as interactive applets. Now that I have several
applets to show off I've collected them together onto a "Java Applet
Demos" page.
</p>
<p class="center">
  <a href="/toys/">
    <b>Java Applet Demos</b><br/>
    <img src="/img/applets/applets.png" alt=""/>
  </a>
</p>
<p>
I intend on expanding this in the near future with improvements
(Michael is unhappy with my integration function on the water wheel,
for one) and new applets <a href="/blog/2010/10/15/">while I'm on a
roll</a>. Swing is my oyster.
</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>A Modest Chess Engine</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/17/"/>
    <id>urn:uuid:7e35b889-394e-3b57-3b32-f2bee090dddf</id>
    <updated>2010-10-17T00:00:00Z</updated>
    <category term="java"/>
    <content type="html">
      <![CDATA[<!-- 17 October 2010 -->
<pre>
git clone <a href="https://github.com/skeeto/october-chess-engine">git://github.com/skeeto/october-chess-engine.git</a>
</pre>
<p class="center">
  <img src="/img/chess/chess-screenshot.png" alt=""/>
</p>
<p>
Here's what I've been working on for about the last week: a little
chess application in Java. It has a built-in AI you can play against
and it's capable of playing both standard chess and Gothic chess right
now. It's actually a chess framework, so it would be fairly easy for
me to add new chess variants, and the AI would be able to play it
automatically. The hardest part is handling a particular chess
variant's castling rule, since that's the hardest rule to generalize.
</p>
<p>
The AI is a minimax search over four full plies with a fairly
simplistic heuristic (but more than just adding up material). It's
probably not that great of a player, but it's good enough that none of
my friends, nor I, are able to beat it. I concentrated more on making
it flexible than fast, so it can't search more than five plies without
taking unreasonably long. But it does use multiple threads to do the
search, so it should be pretty speedy on an SMP system.
</p>
<p class="center">
  <img src="/img/chess/gothic-screenshot.png" alt=""/>
</p>
<p>
I thought about adding multiplayer capability and perhaps giving it
the ability to interface with standalone chess engines (wow are those
protocols ugly!),
like <a href="http://en.wikipedia.org/wiki/GNU_Chess">GNU
Chess</a>. But there are other programs that already do this better
than I ever could. I've done about as much as I was interested in
doing with it.
</p>
<p>
Maybe you remember <a href="/blog/2007/10/24/">that chess AI essay I
wrote some years back</a>? I was talking about using a genetic
algorithm to tweak the AI parameters. Well, I actually tried to do
that here with this AI (see the <code>OptimizeGA</code> class in the
code). Turns out it's not very useful anyway! :-P It wasn't getting
anywhere useful in my experiments.
</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Lorenz Chaotic Water Wheel Applet</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/16/"/>
    <id>urn:uuid:dee2a554-b81f-3d55-85dd-e0bf9a220e51</id>
    <updated>2010-10-16T00:00:00Z</updated>
    <category term="java"/><category term="interactive"/>
    <content type="html">
      <![CDATA[<p><strong>Update Feburary 2018</strong>: This project <a href="https://github.com/skeeto/waterwheel">has gotten a huge facelift</a>.</p>

<p>Today’s project is a Java applet that simulates and displays a
<a href="http://en.wikipedia.org/wiki/Edward_Norton_Lorenz">Lorenz</a> water wheel. Freely-swinging buckets with small holes
in the bottom are arranged around the outside of a loose wheel. Water
flows into the bucket at the top of the wheel, filling it up. As it gets
heavier it pulls down on the wheel, spinning it.</p>

<p><img src="/img/wheel/waterwheel.png" alt="" /></p>

<p>Source: <a href="https://github.com/skeeto/ChaosWheel">https://github.com/skeeto/ChaosWheel</a></p>

<p>You can click with your mouse to adjust the simulation. If you run it
standalone (<code class="language-plaintext highlighter-rouge">java -jar</code>) it will allow you to give it the number of
buckets you want to use as a command-line argument. It’s based on some
Octave/Matlab code written by a friend of mine, Michael Abraham. Those
environments are so slow, though, that they couldn’t do it in real time
like this.</p>

<p>This simulation is <a href="http://en.wikipedia.org/wiki/Chaos_theor)">chaotic</a>: even though the behavior of the
system is deterministic it is <em>highly</em> sensitive to initial conditions.
The animation you see above is unique: no one saw this particular
variation before, nor will anyone again. If you refresh the page you’ll
be given a new wheel with unique initial conditions (well, one out of
the 2\^128 possible starting conditions, since this is running inside of
a digital computer).</p>

<p><img src="/img/wheel/butterfly.png" alt="" /></p>

<p>On the state space plot you should be able to see the state orbiting two
<a href="http://en.wikipedia.org/wiki/Lorenz_attractor">attractors</a>. It’s the classic butterfly image that gives the
phenomenon its name. The state space plot will look smoother with more
buckets, being perfectly smooth at an infinite amount of buckets. Your
mouse cannot possibly survive that much clicking, so don’t try it.</p>

]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Introducing Java Mode Plus</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/15/"/>
    <id>urn:uuid:5cf6344b-537b-36eb-53d8-6ca6b24fd492</id>
    <updated>2010-10-15T00:00:00Z</updated>
    <category term="java"/><category term="emacs"/>
    <content type="html">
      <![CDATA[<!-- 15 October 2010 -->
<p>
There's an extension to Emacs
called <a href="http://jdee.sourceforge.net/"> JDEE</a> which tries to
turn Emacs into a heavyweight IDE for Java. I've never had any success
with it, and I don't know anyone else who has either. It's difficult
to set up, the dependencies are even worse, poorly documented, and
then it doesn't seem to work very well anyway. I think it's too
divorced from Emacs'
core <a href="http://en.wikipedia.org/wiki/Composability">
composable</a> functionality to be of much use. I may as well be using
a big IDE.
</p>
<p>
So, instead, as <a href="/blog/2009/12/06/">I've
posted</a> <a href="/blog/2010/09/30/">about</a>
<a href="/blog/2010/10/14/">over time</a>, I've started with the basic
Emacs Java functionality and tweaked my way up from there. I've
extended it enough that I decided to package it up on it's own, and
hopefully others will find it useful too. I call
it <code>java-mode-plus</code>!
</p>
<pre>
git clone <a href="https://github.com/skeeto/emacs-java">git://github.com/skeeto/emacs-java.git</a>
</pre>
<p>
Specifically: <a href="https://github.com/skeeto/emacs-java/blob/master/java-mode-plus.el">java-mode-plus.el</a>
</p>
<p>
It provides a hook into <code>java-mode</code> that creates a bunch of
new bindings. It also creates some new globally-available functions
like <code>open-java-project</code>. It's all heavily Ant-based since
that's what I like to use. It wouldn't be very hard to modify it to
use Maven, if that's what your thing.
</p>
<p>
<b>My very thorough documentation is in a large header comment in the
source file itself.</b> I cover my whole workflow from top to
bottom. If you're interested in making Emacs more Java-friendly take a
look at it. It's not a lot of code, but each line has been
thoughtfully added after hours and hours of Java development.
</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Jump to Java Documentation from Emacs</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/14/"/>
    <id>urn:uuid:4fe4bf26-5447-3337-33bd-1cb0647708b0</id>
    <updated>2010-10-14T00:00:00Z</updated>
    <category term="java"/><category term="emacs"/>
    <content type="html">
      <![CDATA[<!-- 14 October 2010 -->
<p class="abstract">
Update January 2013: this package has been refined and formally
renamed
to <a href="https://github.com/skeeto/javadoc-lookup">javadoc-lookup</a>.
The user interface is essentially the same — under different function
names — but with some extra goodies. It's available for install from
MELPA.
</p>

<p>
I keep running to either a search engine or, when offline, manually
browsing to Java API documentation when I need to look something
up. When I'm using Emacs this is stupid, so I fixed it. I put together
a <code>java-docs</code> package that let's me quickly jump to
documentation from within Emacs.
</p>
<p>
Repository: <code>git clone <a href="https://github.com/skeeto/emacs-java">git://github.com/skeeto/javadoc-lookup.git</a></code>
</p>
<p>
Unfortunately it launches it in a web browser right now because there
doesn't seem to be a reasonable way to render the
documentation <i>inside</i> Emacs itself. So
you'll <a href="http://www.emacswiki.org/emacs/BrowseUrl"> need to
have <code>browse-url</code> set up properly</a> in your
configuration.
</p>
<p>
I strongly recommend you use this
with <a href="http://www.emacswiki.org/emacs/InteractivelyDoThings">
Ido</a>, which comes with Emacs. If you do, you'll want to load
it <i>after</i> you enable <code>ido-mode</code>, which will enable
the Ido minibuffer completion in <code>java-docs</code>.
</p>
<p>
So, after you <code>require</code> <code>java-docs</code>, you give it
a list of places to look for documentation.
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="nb">require</span> <span class="ss">'java-docs</span><span class="p">)</span>
<span class="p">(</span><span class="nv">java-docs</span> <span class="s">"/usr/share/doc/openjdk-6-jdk/api"</span> <span class="s">"~/src/project/doc"</span><span class="p">)</span></code></pre></figure>
<p>
It will scan these locations and build up an index of
classes. <a href="/blog/2010/06/07/">If you're using a recent enough
version of Emacs</a> it will cache that index for faster loading in
the future, since on <i>certain</i> systems it can needlessly take a
bit of time.
</p>
<p>
After that you can jump to documentation with <code>C-h j</code>
(<code>java-docs-lookup</code>). It will ask you what you want to look
up and offer completion with your preferred completion function.
</p>
<p class="center">
  <a href="/img/emacs/java-import.png">
    <img src="/img/emacs/java-import-thumb.png" alt=""/>
  </a>
</p>
<p>
If you don't want to open it up in an external browser, you can set
Emacs to run a text-based browser inside itself.
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="k">setq</span> <span class="nv">browse-url-browser-function</span> <span class="ss">'browse-url-text-emacs</span><span class="p">)</span></code></pre></figure>
]]>
    </content>
  </entry>
    
  
    
  
    
  <entry>
    <title>Sample Java Project</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/10/04/"/>
    <id>urn:uuid:e92e3985-6680-335c-2c69-dc95781f42bd</id>
    <updated>2010-10-04T00:00:00Z</updated>
    <category term="java"/><category term="tutorial"/>
    <content type="html">
      <![CDATA[<!-- 4 October 2010 -->
<p>
Here's a little on-going project I put together recently. It's mostly
for my own future reference, but perhaps someone else may find it
useful.
</p>
<pre>
git clone <a href="https://github.com/skeeto/sample-java-project">git://github.com/skeeto/sample-java-project.git</a>
</pre>
<p>
If you couldn't guess already, I'm strongly against tying a project's
development to a particular IDE. It happens too much: someone starts
the project by firing up their favorite IDE, clicking "Create new
project", and checks in whatever it spits out. It usually creates a
build system integrated tightly into that particular IDE. At work I've
seen it happen on two different large Java projects. There are some
ways around it, like maintaining two build systems side-by-side, but
it's not very pretty. Sometimes the Java IDE can spit out some Ant
build files for the sake of continuous integration, but it remains a
second-class citizen for development.
</p>
<p>
I prefer the other direction: start with a standalone build system,
then stick your own development environment on top of that. Each
developer picks and is responsible for whatever IDE or editor they
want, with the standalone build system providing the canonical build
(and, in my experience, if you <i>must</i> use an IDE, NetBeans has
the smoothest integration with Ant). So in the case of Java, this
means setting up an Ant-based build.
</p>
<p>
I've said before that <a href="/blog/2010/08/13/">I like the Java
platform</a>, I just find the primary language
disappointing. Similarly, I like Ant, I just find the build script
language disappointing (XML). It seems other people like it too, at
least for Java development,
because <a href="http://www.google.com/search?q=ant+sucks">I haven't
been able to find any serious criticisms</a> of it outside of hating
the XML (notice the first result in that search is written by someone
who is Doing It All Wrong). I love that it works on filesets and not
files. It's like getting atomic commits for my build system. If I add
a new source file to my project I don't need to adjust the Ant build
script in any way.
</p>
<p>
One downside of Ant is that, while it's commonly used in a very
standard way, it doesn't guide you in that direction or provide
special shortcuts to make the common cases easier. It's typical to
have a <code>src/</code> directory containing all your source and
a <code>build/</code> directory, created by Ant, that contains all the
built and generated files. With Ant you basically say, "Compile these
sources to here, then jar that directory up." Ant alone doesn't make
this very obvious. Give it to someone standed on a desert island and I
bet they won't derive the same best practice as the rest of the world.
</p>
<p>
Take <code>make</code>, for example. Because building object files
from source is so common, (depending on the implementation) it has
built-in rules for it. This is all you need to say,
and <code>make</code> knows how to do the rest.
</p>
<figure class="highlight"><pre><code class="language-make" data-lang="make"><span class="nl">file.o </span><span class="o">:</span> <span class="nf">file.c</span></code></pre></figure>
<p>
Same for linking, it's so common you don't have to type anything more
than necessary.
</p>
<figure class="highlight"><pre><code class="language-make" data-lang="make"><span class="nl">program </span><span class="o">:</span> <span class="nf">main.o common.o file.o</span></code></pre></figure>
<p>
It guides you in creating good Makefiles. If you want to learn the
best practice for Ant, you have to either buy a book on Ant or look at
what lots of other people are doing. And so I provide my
sample-java-project for this exact purpose.
</p>
<p>
You can use that as a skeleton when creating your own project, and
you'll barely have to customize the build file. It's a big mass of
boilerplate, the kind of stuff that Ant should have built-in by
default. I'll be expanding it over time as I learn more about how to
effectively use Ant.
</p>
<p>
So far, I included two things that you normally won't see: a target to
run a Java indenter
(<a href="http://astyle.sourceforge.net/">AStyle</a>) on your code,
and a target to run the
bureaucratic <a href="http://checkstyle.sourceforge.net/">
Checkstyle</a> on your code.
</p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Java is Death By A Thousand Paper Cuts</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2010/08/13/"/>
    <id>urn:uuid:beca38a0-bd9d-3304-02c9-1941ced67121</id>
    <updated>2010-08-13T00:00:00Z</updated>
    <category term="java"/><category term="rant"/>
    <content type="html">
      <![CDATA[<!-- 13 August 2010 -->
<p>
At least it is for me. This past week at work I've been furiously
rushing work on a project written in Java. It's completely my fault
that I'm using Java since I'm the one who picked the language. I
wanted to use Java the platform, but I don't know any other JVM
languages well enough to use them in place of Java the language for a
project at work.
</p>
<p>
It's all sorts of little things that make writing Java so exhausting
for me. At the end of the day it I just feel irritated. I hate the
absolute lack of functional programming and that I have to specify
everything at such a low level. The whole reason we program in
high-level languages is so we can express algorithms more concisely,
but Java fails at this.
</p>
<p>
Here's an example of what I'm talking about, something I basically did
a few times today. Let's say you have an array of
floats, <code>nums</code> and you want to sum them and return the
result (or maybe use it in another expression). In Lisp it's very
straightforward.
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="nb">reduce</span> <span class="ss">'+</span> <span class="nv">nums</span><span class="p">)</span></code></pre></figure>
<p>
"Reduce the sequence <code>nums</code> by addition." Notice that it's
more about saying <i>what</i> I want to do rather than <i>how</i> to
do it. I don't have to introduce any temporary storage or
iterators. To do the same thing in Java it will look something like
this.
</p>
<figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kt">int</span> <span class="n">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">double</span> <span class="n">num</span> <span class="o">:</span> <span class="n">nums</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">sum</span> <span class="o">+=</span> <span class="n">num</span><span class="o">;</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">sum</span><span class="o">;</span></code></pre></figure>
<p>
If you're using an older Java without the enhanced looping construct
it gets even uglier. I had to introduce a variable for accumulation
and a second variable for iteration. This sort of thing has to be
done <i>all over the place</i> in Java, and it greatly increases the
cognitive overload when reading Java code.
</p>
<p>
This instruction is more about telling the computer the <i>how</i>
rather than my overall intention. One problem with telling it
the <i>how</i> is that I've unnecessarily locked in a specific
algorithm and ordering. The literal instruction says that the
numbers <i>must</i> be added in order, sequentially. My Lisp
instruction doesn't do that.
</p>
<p>
It gets even worse when you complicate it slightly by adding a second
array and, say, multiplying it pairwise with the first.
</p>
<figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">nums1</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
    <span class="n">sum</span> <span class="o">+=</span> <span class="n">nums1</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">*</span> <span class="n">nums2</span><span class="o">[</span><span class="n">i</span><span class="o">];</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">sum</span><span class="o">;</span></code></pre></figure>
<p>
Now the loop gets more complex. I have to tell it <i>how</i> to
increment the iterator. I have to tell it to check the bounds of the
array. The iterator is a misdirection because the actual number stored
in it isn't what's important. Again, the Lisp method is much more
concise.
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="nb">reduce</span> <span class="ss">'+</span> <span class="p">(</span><span class="nb">map</span> <span class="ss">'list</span> <span class="ss">'*</span> <span class="nv">nums1</span> <span class="nv">nums2</span><span class="p">))</span></code></pre></figure>
<p>
"Map the two sequences by multiplication into a list, then reduce it
by addition." Unfortunately we start to leak a little bit into
the <i>how</i> here. I am telling it that the intermediate structure
should be a list, because <code>map</code> forces me to pick a
representation. Besides that, I am <i>only</i> describing my overall
intention and not the obvious details.
</p>
<p>
So with Java my days become filled with the tedious low-level
algorithm descriptions that I have to hammer out over and over and
over. Death by a thousand paper cuts.
</p>
<p>
Lisp isn't the only language that has a (generally) much better
approach; it's just my favorite. :-) Most languages with at least some
decent functional facilities will also do the above concisely.
</p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Game of Life in Java</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2009/12/13/"/>
    <id>urn:uuid:dfc591b0-65ed-39d6-80b2-57a8991c2a0d</id>
    <updated>2009-12-13T00:00:00Z</updated>
    <category term="java"/><category term="interactive"/>
    <content type="html">
      <![CDATA[<!-- 13 December 2009 -->
<p>
Sources:
</p>
<pre>
git clone <a href="https://github.com/skeeto/GameOfLife">git://github.com/skeeto/GameOfLife.git</a>
</pre>
<p>
<img src="/img/gol/game-of-life.png" width="250"
     alt="" title="Screenshot of this thing" class="right"/>
</p>

<p>
Since I recently got back into Java recently, I threw together this
little Game of Life implementation in Java. It looks a lot like my <a
href="/blog/2007/10/08/">maze generator/solver</a> on the inside,
reflecting the way I think about these things. Gavin wrote a <a
href="http://devrand.org/show_item.html?item=98&amp;page=Project">
competing version of the game</a> in <a
href="http://processing.org/">Processing</a> which we were partially
discussing the other night, so I made my own.
</p>
<p>
The individual cells are actually objects themselves, so you could
inherit the abstract Cell class and drop in your own rules. I bet you
could even write a Cell that does the <a href="/blog/2007/11/06/">
iterated prisoner's dilemma cellular automata</a>. The Cell objects
are wired together into a sort of mesh network. Instead of growing it
wraps around on the sides.
</p>
<p>
It takes up to four arguments right now, with three types of cells,
<code>basic</code>, implementing the basic Conway's Game of Life,
<code>growth</code>, which is a cell that matures over time, and
<code>random</code> which mixes both types together (seen in the
screenshot). The arguments work as follows,
</p>
<pre>
java -jar GoL.jar [&lt;cell type&gt; [&lt;width&gt; &lt;height&gt; [&lt;cell pixel width&gt;]]]
</pre>
<p>
I may look into extending this to do some things beyond simple
cellular automata.
</p>
]]>
    </content>
  </entry>
    
  
    
  <entry>
    <title>Tweaking Emacs for Ant and Java</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2009/12/06/"/>
    <id>urn:uuid:42b07d86-b8d5-3992-5b5e-ad5c41b9256d</id>
    <updated>2009-12-06T00:00:00Z</updated>
    <category term="emacs"/><category term="java"/><category term="lisp"/>
    <content type="html">
      <![CDATA[<!-- 6 December 2009 -->
<p class="abstract">
Update: This is now part of my
<a href="https://github.com/skeeto/emacs-java">
<code>java-mode-plus</code></a> Emacs extension.
</p>
<p>
Developing C in Emacs is a real joy, and it's mostly thanks to the
compile command. Once you have your Makefile — or SConstruct or
whatever build system you like — setup and you want to compile your
latest changes, just run <code>M-x compile</code>, which will run your
build system in a buffer. You can then step through the errors and
warnings with <code>C-x `</code>, and Emacs will take you to them.
It's a very nice way to write code.
</p>
<p>
I use the compile command so much that I bound it to <code>C-x
C-k</code> (<code>C-k</code> tends to be part of compile key
bindings),
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="nv">global-set-key</span> <span class="s">"\C-x\C-k"</span> <span class="ss">'compile</span><span class="p">)</span></code></pre></figure>
<p>
Until recently, I didn't have as nice of a setup for Java. Since they
generally force offensive IDEs onto me at work this wasn't something I
needed yet anyway, but <i>I</i> get to choose my environment on a new
project this time. If you're using Makefiles for some reason when
building your Java project, it still works out fairly well because
they're usually called recursively. It gets more complicated with <a
href="http://ant.apache.org/">Ant</a>, where there is only one
top-level build file. Emacs' compile command only runs the build
command in the buffer's current directory.
</p>
<p>
I know three solutions to this problem. One is to provide the build
file's absolute path when <code>compile</code> asks for the command
with the <code>-buildfile</code> (<code>-f</code>) option. You only
need to type it once per Emacs session, so that's not <i>too</i> bad.
</p>
<pre>
ant -emacs -buildfile /path/to/build.xml
</pre>
<p>
It's not well documented, but there is a <code>-find</code> option
that can be given to Ant that will cause it to search for the build
file itself. This is even nicer than the previous solution. Just
remember to place it last, unless you give it the build filename
too. For example, if you wanted to run the <code>clean</code> target,
</p>
<pre>
ant -emacs clean -find
</pre>
<p>
To keep the actual call as simple as possible, I wrote a wrapper for
<code>compile</code>, and put a hook in <code>java-mode</code> to
change the local binding. The wrapper, <code>ant-compile</code>,
searches for the build file the same way <code>-find</code> would do.
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="nb">defun</span> <span class="nv">ant-compile</span> <span class="p">()</span>
  <span class="s">"Traveling up the path, find build.xml file and run compile."</span>
  <span class="p">(</span><span class="nv">interactive</span><span class="p">)</span>
  <span class="p">(</span><span class="nv">with-temp-buffer</span>
    <span class="p">(</span><span class="nv">while</span> <span class="p">(</span><span class="nb">and</span> <span class="p">(</span><span class="nb">not</span> <span class="p">(</span><span class="nv">file-exists-p</span> <span class="s">"build.xml"</span><span class="p">))</span>
                <span class="p">(</span><span class="nb">not</span> <span class="p">(</span><span class="nb">equal</span> <span class="s">"/"</span> <span class="nv">default-directory</span><span class="p">)))</span>
      <span class="p">(</span><span class="nv">cd</span> <span class="s">".."</span><span class="p">))</span>
    <span class="p">(</span><span class="nv">call-interactively</span> <span class="ss">'compile</span><span class="p">)))</span></code></pre></figure>
<p>
So I can transparently keep using my muscle memory compile binding, I
set up the key binding in a hook,
</p>
<figure class="highlight"><pre><code class="language-cl" data-lang="cl"><span class="p">(</span><span class="nv">add-hook</span> <span class="ss">'java-mode-hook</span>
          <span class="p">(</span><span class="k">lambda</span> <span class="p">()</span> <span class="p">(</span><span class="nv">local-set-key</span> <span class="s">"\C-x\C-k"</span> <span class="ss">'ant-compile</span><span class="p">)))</span></code></pre></figure>
<p>
Voila! Java works looks a little bit more like C.
</p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  <entry>
    <title>Java Animated Maze Generator and Solver</title>
    <link rel="alternate" type="text/html" href="https://nullprogram.com/blog/2007/10/08/"/>
    <id>urn:uuid:a0616bd6-6e00-38c5-c84c-12335f388d88</id>
    <updated>2007-10-08T00:00:00Z</updated>
    <category term="java"/><category term="interactive"/>
    <content type="html">
      <![CDATA[<p><img src="/img/screenshot/maze-thumb.png" alt="" /></p>

<ul>
  <li><a href="https://github.com/skeeto/RunMaze">https://github.com/skeeto/RunMaze</a></li>
</ul>

<p>In preparation for showing off the maze-navigating robot I made last
week, I give you this program I wrote last year.</p>

<p>When I started to learn Java, I wrote this little program for
practice. It features a GUI and multi-threading. It generates a maze
and then slowly solves the maze so you can watch it go. I wrote this
with the GNU project’s Java implementation <span style="text-decoration: line-through;">(never used the official Sun
one). The Makefile is therefore set up for <code>gcj</code> and
<code>gij</code>. The Makefile can build the byte-compiled
<code>.jar</code> file as well as a natively compiled version.</span>
I have updated it to use Ant, and I also use Sun’s OpenJDK these days.</p>

<p>The maze generation algorithm is what I believe to be called the
“straw man” algorithm: the maze starts as a matrix of individual
cells. Break down the walls between two cells that aren’t already
connected and move into it. Choose another wall at random and
repeat. If there are no walls left to break down, go back a
step. Lather, rinse, repeat. If you are back in the starting cell with
no more walls to break down, you are done.</p>

<p>Solving the maze is done in a similar way to generation. Go forward,
right, or left if you can. If not, go back to the previous cell. This
is the same algorithm I employed in the maze-navigating robot I built,
which has kept me pretty busy. I will post pictures of it later.</p>

<p>You can specify the maze height, width, and cell pixel size on the
command line when you run it. This runs with the defaults,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>java -jar RunMaze.jar
</code></pre></div></div>

<p>Or if you grabbed the source,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ant run
</code></pre></div></div>

<p>And, for a tiny 100 by 100 maze,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>java -jar RunMaze.jar 100 100 5
</code></pre></div></div>

<p>where,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>java -jar RunMaze.jar &lt;width&gt; &lt;height&gt; &lt;cell-size&gt;
</code></pre></div></div>

<p>So, why learn Java? I still don’t like Java, but I had missed out on
an interesting research opportunity because I had zero Java
experience. I probably wouldn’t use it on my own for anything but
practice, as my own projects don’t really need to be super-portable.
Java is ugly, bulky, and slow, but I don’t want to miss any more
opportunities. Right after I was turned down because of my lack of
experience, I bought a Java textbook and read it cover to cover on
vacation. More importantly, I wrote simple little Java programs (like
the one presented here) as I learned core concepts.</p>

<p><em>Update 2009-07-07: I use Java all the time at work now. There is
really no escaping it. Except maybe with something like
<a href="http://clojure.org/">Clojure</a> …</em></p>
]]>
    </content>
  </entry>
    
  
    
  
    
  
    
  
    
  
    
  
    
  
    
  

</feed>
