Monthly Archives: December 2010

The Friday Fragment

It’s Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week’s Fragment

If you coded last week’s fragment under Linux, you could check your results by running cal month year.  The unix cal utility formats calendars based on the current date or a given date.  So let’s continue our new year’s programming along those lines:

Write code to print out a month’s calendar given a month and year.

To play along, post the code for the solution as a comment or send it via email.  You can built atop last week’s solution to determine the starting day of week.  There are likely many implementations already available (including C code for the unix utility), but this is a good opportunity to try new languages or techniques.

Last Week’s Fragment – Solution

With our round of game programming, our code solutions had grown a bit larger than mere fragments.  So last week’s puzzle returned to something short and sweet, as Friday Fragments marked Christmas Eve and New Year’s Eve:

Write code to calculate the day of week (Sunday through Saturday) for a given date.  Remember to account for leap years.

This is something of a classic math puzzle, and it’s not too tough to do the calculation mentally.  Many languages have a library function for this, but calling that would be cheating.  Perhaps the simplest approach is to implement Zeller’s Congruence in the language of your choice, overcoming numeric conversions.  I coded it in newly-explored Gosu:

   uses java.lang.Math
   var month=12;   var day=31;    var year=2011;  // Your date here
   var dayNames = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }

   // Shift the year to start in March, split the year components:
   if (month<3) { month += 10; year--; }
   else         { month -= 2; }
   var shortYear = year % 100
   var century = (year / 100)

   // Zeller's: W = (k + floor(2.6m - 0.2) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7
   var dayOfWeek = ((day +
                      Math.floor((2.6 * month) - 0.2) - (2 * century) +
                      shortYear + Math.floor(shortYear/4) + Math.floor(century/4)) % 7) as int
   print(dayNames[dayOfWeek])

 

Have a happy 1-1-11!

Gosu

It’s Wednesday, so there must be another new scripting language for the JVM.

Well, the latest entry in this crowded field is Gosu, a language that feels a bit like Groovy, but with Scala-like static typing.   It attempts to plug some of the perceived holes in current JVM scripting languages (static typing) and Java itself (type inference, closures, properties, delegates, etc.).  Gosu compiles to Java classes and enables good code completion and strong compile-time verification.

If you have Java 1.5 or higher installed (who doesn’t?), it’s very quick and easy to give Gosu a try.  Just download and unzip, and the gosu command line and editor environment are ready to go.   There’s an Eclipse plug-in, but since it doesn’t yet support the newer Helios (3.6) version I have installed, I skipped it for now.

If you’re like me, your eyes may roll when someone actually promotes static typing.  But Gosu’s type inferencing goes a long way to simplify code and make it feel a bit like dynamic typing.  Likewise, many other features (properties, short hand syntax, cleanups, etc.) are mainly directed toward simplifying code and reducing bloat, alleviating Java’s “endless forms in triplicate” feeling.

Just to get a feel, I coded a few small things in it, including a solution to this week’s Friday Fragment.  For just about everything I tried, it was quick, clean, and intuitive, although error messages were sometimes confusing.

Gosu’s inventors (Guidewire Software) and others have already made good use of the language in production systems, so it’s not some fly-by-night research project or half-baked alpha that’ll likely go away or get neglected.  But it’s not yet clear how much adoption it will see.  I really like the language, but I’ll probably take a “go-su? we’ll see” approach before using it further.

The Friday Fragment

It’s Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week’s Fragment

This year has Friday Fragments marking Christmas Eve and New Year’s Eve.  With that and another year change in mind, let’s do a simple calendar-related puzzle:

Write code to calculate the day of week (Sunday through Saturday) for a given date.  Remember to account for leap years.

To play along, post the code for the solution as a comment or send it via email.

Last Week’s Fragment – Solution

With last week’s puzzle, we conclude our round of game programming:

Upgrade your game (rock-paper-scissorstic-tac-toe, or Reversi, your choice) to use async (AJAX-style) calls and updates, rather than postbacks. Use any frameworks you’d like, or just plain old Javascript.

My Reversi solution is at http://derekwilliams.us/bots/reversi/reversiajax.php.  I used jQuery for the AJAX (get) calls, and ported much of playreversi.php and reversimove.php to Javascript.  Here’s the gist of it:

  var url = "http://derekwilliams.us/bots/reversi";  // Your bot here
  var board = "...........................OX..." +
              "...XO...........................";

  function userMove(row, col) {
    var index = (row*8) + col;
    var play = board.substr(0, index) + "X" + board.substr(index + 1);
    board = updateBoard(board, play);
    if (board.indexOf(".") >= 0)
      callBot();
    else
      showBoard();
  }

  function callBot() {
    var fullUrl = url + "?board=" + board + "&piece=O";
    $.get(fullUrl, "", function(play) { botReturn(play) }, "text");
  }

  function botReturn(play) {
    board = updateBoard(board, play);
    showBoard();
  }

  function showBoard() {
    var boardTable = document.getElementById("boardTable");
    for (var row=0; row<8; row++)
      for (var col=0; col<8; col++) {
        var piece = board.charAt((row*8)+col);
        var cellContents = "<img src='" + imageForPiece(piece) + "'>";
        if (piece == "." && canPlay(board, "X", (row*8)+col))
          cellContents = "<a href='javascript:userMove(" + row + "," + col + ")'>"
                                                           + cellContents + "</a>";
          boardTable.rows[row].cells[col].innerHTML = cellContents;
        }
  }

To see the helper functions, view the Javascript source. I continue to call my reversi web service bot; you can substitute your own at the “Your bot here” line.

By moving most of the behavior to the client, I greatly simplified the server-side PHP code (see the reversiajax.php source code).  You can view all our games and bots at http://derekwilliams.us/bots.

No Charge for AWS-omeness

Until recently, I’ve only used Amazon Web Services (AWS) vicariously, such as S3 storage through Dropbox.  But since I’ve started pushing my “cloud” things beyond my hosting service’s limits, I couldn’t resist Amazon’s new one year free offer.

For my initial work, I needed only EC2 (Linux instances) and S3 (storage), so I navigated the obligatory sign-ups and confirmation emails and calls for these.  The services were activated after a short wait, and I could manage them through the AWS Management Console and Elasticfox.

For EC2, I started an Amazon AMI with SLES 11 (in spite of that Attachmate/Novell thing) and enabled ssh and http access in its security group.  I then ssh’ed in to install (zypper) and configure (chkconfig, etc.) apache2, mysql, php, mod-php, and a few other goodies.  Within just a few minutes, I had the entire stack running in the VM, ready to take on my stuff.

Compared with old-fashioned ways of building and publishing web servers, VMs, and VPSes, this is just too easy.  And it’s reassuring to know that this thing is hugely scalable.  But, best of all, it’s free.  At least for a year.

The Friday Fragment

It’s Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week’s Fragment

Let’s bring our games into the modern era.  You’ll notice in my solutions that every play causes a full redraw of the page.  That’s so very 1990s, so let’s fix it:

Upgrade your game (rock-paper-scissorstic-tac-toe, or Reversi, your choice) to use async (AJAX-style) calls and updates, rather than postbacks. Use any frameworks you’d like, or just plain old Javascript.

To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email.  If you’d like, you can build atop the games, bots, and/or source code at http://derekwilliams.us/bots.

Last Week’s Fragment – Solution

Last’s week’s puzzle returned to our Reversi game:

Write code to let man compete against machine (a game bot) in Reversi.  Present the game board on a web page, let the human player make the next move, and then call the game bot for its move.  Continue this until one side wins.

My solution is at http://derekwilliams.us/bots/reversi/playreversi.php.  I built it from last week’s code and called our Reversi bot unmodified.  Here it is:

<?php
  require('reversimove.php');
  $url = 'http://derekwilliams.us/bots/reversi/';  // Your bot here

  // Set up the session.  If this is a new game, show the initial board:
  session_start();
  if (!isset($_SESSION['board']) || !isset($_REQUEST['row'])) {
    $board = str_repeat('.',64);
    $board[27]='O'; $board[28]='X';
    $board[35]='X'; $board[36]='O';
    $_SESSION['board'] = $board;
    exit(show_board($board));
  }

  // Get the board, add Xs (the human's) move, and score it:
  $play = $board = $_SESSION['board'];
  $play[($_REQUEST['row'] * 8 ) + $_REQUEST['col']] = 'X';
  $board = update_board($board, $play);
  if (substr_count($board, '.') == 0) {
    unset($_SESSION['board']);
    exit(show_board($board));
  }

  // Call the web service bot to get its (O's) move and score it:
  $play = file_get_contents($url.'?board='.$board.'&piece=O');
  $board = update_board($board, $play);
  show_board($board);
  $_SESSION['board'] = $board;

  function show_board($board) {
    STATIC $images = array( 'X' => 'black.jpg', 'O' => 'white.jpg', '.' => 'green.jpg');
    $scores = array('.' => 0, 'X' => 0, 'O' => 0);
    echo '<table border="1">';
    for ($i=0; $i<8; $i++) {
      echo '<tr border="1">';
      for ($j=0; $j<8; $j++) {
        $piece = $board[($i*8)+$j];
        $scores[$piece]++;
        if ($piece == '.' && can_play($board, 'X', ($i*8)+$j))
          printf('<td border="1"><a href="playreversi.php?row=%d&col=%d"><img src="%s"></td></a>',
                   $i, $j, $images[$piece]);
        else
          printf('<td border="1"><img src="%s"></td>', $images[$piece]);
      }
      echo '</tr>';
    }
    printf('</table><p>X: %d, O: %d.&nbsp;<a href="playreversi.php">Start Over</a></p>',
               $scores['X'], $scores['O']);
  }
?>

To keep it simple, there’s not a lot of error handling.  If you haven’t already done so, try coding your own bot, plug it in at the “Your bot here” line, and compete against it.

Big and Slow

All too often, folks will take a broad-brush “bigger is better” approach when sizing, configuring, and tuning databases.  After all, if 5 is good, 10 must be better, right?  Problems from this brute-force approach can show up quickly with “not enough memory” error messages, excessive paging, and slow start-up. But sometimes bad results can be delayed or indirect.  DBA “coolwinds” points out how high CPU utilization can result from an oversized tempspace bufferpool:

If a temporary tablespace has a very large bufferpool, and temporary tables are often dropped, CPU usage might be high. (Even if your application does not explicitly drop temporary tables, DB2 might still create and drop temporary tables internally in normal query processing.)

He explains why (dirty list scanning) and how to correct it (create a smaller bufferpool dedicated to the temporary tablespaces).

Tools make it easy to view bufferpool sizes, but you can always query the system catalog to check:

select tbspace, datatype, t.pagesize, bpname, npages
from syscat.tablespaces t, syscat.bufferpools b
where t.bufferpoolid = b.bufferpoolid
order by datatype, tbspace

Right-sizing can be a challenge. Fortunately, for DB2 9.1 and higher, you can use automatic sizing for many things and let STMM do the work.  When overriding, it helps to ask autoconfigure for its opinion.

The Friday Fragment

It’s Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week’s Fragment

With this week’s solution, we now have code to match man against machine in tic-tac-toe.  Let’s do that for our Reversi game:

Write code to let man compete against machine (a game bot) in Reversi.  Present the game board on a web page, let the human player make the next move, and then call the game bot for its move.  Continue this until one side wins.

To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email.  If you’d like, you can build atop the games, bots, and/or source code at http://derekwilliams.us/bots.

Last Week’s Fragment – Solution

With last week’s puzzle, we returned to our game bots to let us humans play along:

Write code to let man compete against machine (a game bot) in rock-paper-scissors, tic-tac-toe, or Reversi (your choice).  Present the game board on a web page, let the human player make the next move, and then call the game bot for its move.  Continue this until one side wins.

I wrote a basic tic-tac-toe solution, available at http://derekwilliams.us/bots/tictactoe/playttt.php.  I deliberately built it from prior code (like scorettt) and called our tic-tac-toe bot unmodified.  Here’s the PHP code, with more commenting this time:

<?php
 $url = 'http://derekwilliams.us/bots/tictactoe';  // Your bot here

 // Set up the session.  If this is a new game, show the initial board:
 session_start();
 if (!isset($_SESSION['board'])) {
   $_SESSION['board'] = '         ';
   exit(show_board($_SESSION['board']));
 }

 // Get the board, add X's (the human's) move, and score it:
 $board = $_SESSION['board'];
 $board[($_REQUEST['row'] * 3) + $_REQUEST['col']] = 'X';
 if (!is_null($result = score_board($board, 'X')))
   game_over($board, $result);

 // Call the web service bot to get its (O's) move and score it:
 $board = file_get_contents($url.'?board=|'.rawurlencode($board).'|');
 $board = substr($board, 1, 9);
 if (!is_null($result = score_board($board, 'O')))
   game_over($board, $result);

 // No-one has won yet.  Show the board & keep playing:
 show_board($board);
 $_SESSION['board'] = $board;

 // Helper functions:

   function score_board($board, $turn) {

     STATIC $wins = array( array(0,1,2), array(3,4,5), array(6,7,8),
                           array(0,3,6), array(1,4,7), array(2,5,8),
                           array(0,4,8), array(2,4,6) );

     for ($i=0; $i<8; $i++) {
       for ($j=0, $piececount=0; $j<3; $j++) {
         if ($board[$wins[$i][$j]] == $turn)
           $piececount++;
       }
       if ($piececount == 3)
         return $turn.' wins!';
       elseif (substr_count($board, ' ') == 0)
         return 'Tie!';
     }
   }

   function show_board($board) {
     STATIC $images = array( 'X' => 'x.jpg', 'O' => 'o.jpg', ' ' => 'space.jpg');
     echo '<table border="1">';
     for ($i=0; $i<3; $i++) {
       echo '<tr border="1">';
       for ($j=0; $j<3; $j++) {
         $piece = $board[($i*3)+$j];
         if ($piece == ' ')
           printf('<td border="1"><a href="playttt.php?row=%d&col=%d"><img src="%s"></td></a>',
                    $i, $j, $images[$piece]);
         else
           printf('<td border="1"><img src="%s"></td>', $images[$piece]);
       }
       echo '</tr>';
    }
    echo '</table><p>&nbsp;</p>';
   }

   function game_over($board, $result) {
     show_board($board);
     unset($_SESSION['board']);
     exit(printf('<p><b>%s</b></p><a href="playttt.php">Start Over</a>', $result));
   }
?>

To keep it simple, there’s not a lot of error handling.  Also, you’ll notice that our prior tic-tac-toe bot (the O player) isn’t very good at it.  If you haven’t already done so, try coding your own bot, plug it in at the “Your bot here” line, and compete against it.  Perhaps you could upgrade the wins map. Then maybe your record will be as good as the NFC-leading Falcons.  10-2 – Rise Up!

Gingerbread

Android 2.3 (a.k.a., Gingerbread) and the 9.1 APIs were released this week with an array of new features for gaming, multimedia, communication and new platforms.  Many of the enhancements are quantitative and behind-the-scenes improvements that I won’t really notice until I have it running on my phone or do some further development.  But there were enough usability improvements to interest me in giving it a spin.  So I downloaded the SDK and previewed it in my Eclipse AVD.

Not surprisingly, upgrading my Eclipse development environment also required an ADT plug-in upgrade.  But this is a familiar and easy process where the waiting is the hardest part.  A few downloads and restarts later, I had 2.3 running in my virtual device.

I instantly noticed the subtle color and contrast differences which, apart from graininess in some areas, make things more consistent and readable.  It’s become standard MO that each Android release changes the look and feel enough that you can typically identify the version at a glance.  I really like the text selection improvements, as I had otherwise nearly given up on accurate copy/paste.  The on-screen keyboard looks and behaves differently (apart from having to turn off the default Japanese IME settings), but it’s hard to get a true feel for the changes in an emulator.

For us Task Manager / pstat junkies, access to Manage Applications – Running is now quicker than a Windows Ctrl+Alt+Delete.  The release notes boast of improvements to the battery use monitor (formerly Settings – About Phone – Battery use), but I was unable to judge this on the emulator.

I didn’t / couldn’t try some of the platform enhancements like native support for AAC (new life for my abandoned iTunes downloads?), NFC tags, and SIP calls.  Those will wait until it’s on my phone.

But thus far it looks like Gingerbread is a nice addition to the Android dessert menu, and I’ll look forward to the Droid port and Verizon pushing it out (or, if I get impatient, rooting and loading it myself).  I’d be interested in your impressions of it, or even your predictions for the J release name: jello or jalebi, anyone?

The Friday Fragment

It’s Friday, and time again for the Friday Fragment: our weekly programming-related puzzle.

This Week’s Fragment

After last week’s commemorative fragment, we’ll resume our game bots.  Let’s make our bots more interesting by letting us play instead of just watching:

Write code to let man compete against machine (a game bot) in rock-paper-scissors, tic-tac-toe, or Reversi (your choice).  Present the game board on a web page, let the human player make the next move, and then call the game bot for its move.  Continue this until one side wins.

To play along, provide either the URL or the code for the solution. You can post it as a comment or send it via email.  If you’d like, you can build atop the bots and/or source code at http://derekwilliams.us/bots.

Last Week’s Fragment – Solution

Last week’s puzzle was another cryptogram:

OBKR
UOXOGHULBSOLIFBBWFLRVQQPRNGKSSO
TWTQSJQSSEKZZWATJKLUDIAWINFBNYP
VTTMZFPKWGDKZXTJCDIGKUHUAUEKCAR

I offered a hint (“try some googling”) and a short-cut (“just offer suggestions on how to go about solving it”).  And for good reason: this is a somewhat famous unsolved cryptogram.  It’s Part 4 of Kryptos, Jim Sanborn’s sculpture at the CIA headquarters. I posted it last week in celebration of its 20th anniversary, and the recent release of a new clue.

Many experts and other sorts have worked on solving Part 4, in search of fame or just a good challenge.  I think it utilizes a one-time pad or a long key, perhaps along with the Vigenere Table found on the sculpture.  The key or pad may be located on-site; for example in the underground utility tunnel.  Time will tell.

If you think you can crack it, don’t just tell me: send your solution to Sanborn for verification.

If you’re just interested in Sanborn’s work, check out photos online.  The CIA Kryptos sculpture is now closed to visitors, but you can visit Sanborn’s other sculptures, such as The Cyrillic Projector and Adam Smith’s Spinning Top at UNC Charlotte.  Just don’t show up at his home.