Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Tuesday, October 04, 2011

Funky Cygwin Path Issues

In getting familiar with Stuart Sierra's lovely Clojure test library Lazytest, I ran into a problem running it from the windows command console. The test output had special control codes not properly processed by the console:
E:\development\clojure\calibration>java -cp src;test;lib/*;lib/dev/* lazytest.watch src test

======================================================================
At  #<Date Tue Oct 04 07:45:47 CDT 2011>
Reloading calibration.test.core, calibration.core

←[33mNamespaces (no cases run)←[0m

←[33mRan 0 test cases.←[0m
←[32m0 failures.←[0m

Done.
I use mintty for cygwin, which will process those codes correctly, but I then had trouble with the Java classpath:

yawmark$ java -cp "src:test:lib/*:lib/dev/*" lazytest.watch src test
java.lang.NoClassDefFoundError: lazytest/watch
Caused by: java.lang.ClassNotFoundException: lazytest.watch
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: lazytest.watch.  Program will exit.
Exception in thread "main" [~]

After a little online research, I found that I needed to decorate the classpath a bit:
java -cp `cygpath --path --windows "src:test:lib/*:lib/dev/*"` lazytest.watch src test
After that, all is once again right with the world.

Thursday, August 27, 2009

Unexpected SimpleDateFormat Behavior

Failing test case:

import static org.junit.Assert.*;
import java.text.*;
import org.junit.Test;

public class DateFormatTests {

@Test
public void testRequiredTwoDigitDay() {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
try {
df.parse("2009081");
fail("Expected two-digit day");
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Argh.

SimpleDateFormat API Javadocs
:
For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
Tricksy API javadocs. We hatessss it forever.

Java - Resolving NullPointerException

In Java, the NullPointerException (NPE) is generally a simple exception to resolve. In very basic terms, it means that one is trying to access a property or call a method on an object that does not exist. Read the error message to find the line where the NPE occurred. Examine that line to determine which reference is a likely candidate to be null. Dig a little deeper to find out why that reference is null and fix the application to either ensure the reference is not null or to handle the reference gracefully if it is null.

Sunday, April 26, 2009

Netbeans 6.5 + Grails

I'm not pleased with the apparent behavior of NetBeans 6.5 when creating a new Grails domain class. I'm unable to create a domain class anywhere other than the default package; the dialog keeps asking for a "valid class name":



This name works fine for creating a Groovy class, just not a Grails domain class. So, why won't the Grails support allow it?
 

UPDATE (2009-05-08): This seems to be straightened out in NetBeans 6.7 (beta).

Tuesday, April 14, 2009

XPath Voodoo

I had a use case for Canoo Web Test to verify the value of a table cell. In an attempt to obtain the value using an XPath query, I used the following expression:
//form[@id='myFormName']/table/tr[2]/td[2]

My test failed, reporting that this expression didn't return any value at all. I verified this was the correct path by looking at the XHTML source. It was only through inspecting the XHTML using the Firebug plugin for Firefox did I see a mystery <tbody> tag. I'm not sure at which point that gets injected, or even why. The injection appears to be a misinterpretation of XTHML 1.0 strict (the specified DOCTYPE). When I added the <tbody> tag to the XPath expression -- which I remind you is not in the XHTML source -- the test passed. Here is the working expression:
//form[@id='myFormName']/table/tbody/tr[2]/td[2]

I haven't figured out what I'm missing, yet.
 

Monday, March 30, 2009

It's here!

I've started in on "The Definitive Guide to Grails, 2nd Edition," by Graeme Rocher and Jeff Brown, after having just received it via post today. The Groovy/Grails combo never ceases to amaze me. The first couple chapters (as far as I've read, yet) are a simple introduction to the Grails platform, which cover starting up a rudimentary CRUD web application, complete with dynamic scaffolding for a couple related domain classes.

I'm anxiously looking forward to digging into more detail as I'm familiar with the material so far. Slow and steady wins the race, however, and I don't want to risk missing any updated juicy tidbits by skipping ahead.
 

Thursday, March 26, 2009

Estimation error

"There's no point in being exact about something if you don't even know what you're talking about."
-- John von Neumann, as quoted in "Software Estimation" by Steve McConnell

 

Software Estimation: Demystifying the Black Art

At work, I just received "Software Estimation: Demystifying the Black Art," by Steve McConnell. I found his book "Code Complete" to be enlightening and practical, so I'm looking forward to reading what McConnell has to say about the art and science of software estimating. I'll be comparing the text to another favorite of mine; "Agile Estimating and Planning," by Mike Cohn.
 

Monday, March 23, 2009

The Definitive Guide to Grails, Second Edition

I'm anxiously awaiting The Definitive Guide to Grails, Second Edition to arrive by mail. I've been playing around with this framework and never cease to be amazed. I understand that other "RAD" web frameworks like Django and Rails probably offer similar features, but Grails' foundation of Groovy is especially attractive to me.

I'll try my best to be patient until TDGG2E shows up.
 

Sunday, March 08, 2009

Theory vs. Practice

"The difference between theory and practice is smaller in theory than in practice."
-- Unattributed
 

Saturday, June 21, 2008

Update: "Days Difference" with Joda

The more I play with the Joda Time API, the more I like it. Revisiting the "calculating difference in days" problem, here's the Joda/Groovy equivalent:
import org.joda.time.LocalDate
import static org.joda.time.Days.*

date1 = new LocalDate(2008, 3, 10)
date2 = new LocalDate(2008, 3, 12)
assert 2 == daysBetween(date1, date2).days

What's not to like? :o)

 

Friday, May 16, 2008

DGG Confusion #1 (among many to come, I'm sure)

I'm working my way through The Definitive Guide to Grails. Chapter 6 covers testing, and I'm a bit stuck on the GroovyMock example in listing 6-9. I'm using Grails 1.0.2, and as entered*, the test fails with "No call to 'getParams' expected at this point. Still 1 call(s) to 'redirect' expected." I tried demanding a call to getParams, but that leads down a path of yet more confusing errors.

So, I'll keep beating my head against it for a while, and hopefully post back with some results.

*
void testUpdateNotFound() {
def bc
def mock = new MockFor(BookmarkController)
mock.demand.redirect { Map params ->
assert params.action == bc.edit
}
mock.use {
bc = new BookmarkController()
bc.params.id = 5
bc.update.call()
}
}

[UPDATE] Nothing that a little Googling won't help, and I'm happy to know I'm not just insane (well, at least not with this particular problem). I'm using version 1.5.1, and according to a bug report, Groovy's MockFor is a bit squiffy in versions 1.5.1 and 1.5.4. Unfortunately, the bug's still open, so I'll have to pass over that part of the book for now. I can do that in good conscience. :o)

[UPDATE #2] This works with Groovy 1.5.6 (with "method pointers"):
import groovy.mock.interceptor.*

class BookmarkController {
def update = { redirect("value from original") }
def redirect = { println "Original class: $it" }
}

class BookmarkTests extends GroovyTestCase {
void testUpdate() {
def bc
def mock = new MockFor(BookmarkController)
mock.demand.redirect { println "Mock class: $it" }
mock.use {
bc = new BookmarkController()
bc.&update.call()
}
}
}

new BookmarkController().&update.call()
new BookmarkTests().testUpdate()

...but I'm not sure that does much for DGG Listing 6-9. Hmph.
 

Wednesday, December 26, 2007

Confusion

On two occasions I have been asked, – "Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?" In one case a member of the Upper, and in the other a member of the Lower, House put this question. I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.

-- Charles Babbage, English mathematician, philosopher, and mechanical engineer

 

Saturday, December 22, 2007

Calculate Difference in Days

Java has no built-in "give me the difference in days" API methods. One commonly-suggested solution is to get the difference in milliseconds between two dates and, using the number of milliseconds in a day, determine the number of days. Unfortunately, daylight savings time creates some problems with this method, as the following Groovy script demonstrates:
#! /usr/bin/groovy

df = new java.text.SimpleDateFormat('yyyy-MM-dd')

// These dates cross DST...
startDate = df.parse('2007-03-10')
endDate = df.parse('2007-03-12')

expectedDifferenceInDays = 2

// Here's the problem with millis:
millisInADay = 1000 * 60 * 60 * 24
differenceInMillis = endDate.time - startDate.time
actualDifferenceInDays = differenceInMillis / millisInADay

assert expectedDifferenceInDays != actualDifferenceInDays
assert actualDifferenceInDays < expectedDifferenceInDays


Here's a more straightforward solution using Java's Calendar API:
#! /usr/bin/groovy

df = new java.text.SimpleDateFormat('yyyy-MM-dd')

// These dates cross DST...
startDate = df.parse('2007-03-10')
endDate = df.parse('2007-03-12')

expectedDifferenceInDays = 2

calendar = Calendar.instance
calendar.time = startDate
actualDifferenceInDays = 0
while (calendar.time.before(endDate)) {
actualDifferenceInDays++
calendar.add(Calendar.DATE, 1)
}
assert expectedDifferenceInDays == actualDifferenceInDays


Note that what constitutes "a day" is subject to interpretation... :o)

Wednesday, October 03, 2007

Write simple code

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
-- attributed to Brian Kernighan

Friday, September 14, 2007

Integer Palindromes

File this one under "Silly, Simple Code Snippet Of The Day"™...

Several times on various programming forums, I've seen question about how to find out if an integer value is a palindrome or not (the number is the same "forwards" and "backwards"; e.g., 71317 would be a palindrome, while 71316 would not). Most of the suggested solutions revolve around converting the integer value to a string and reversing the characters. This makes sense, given that "71317" is just a character representation of a number, and many language APIs have ready-made facilities for reversing strings of characters (or at least arrays). That said, finding out if a number is a palindrome using basic math is dead simple, too. Here's a base-10 example in C#:
    using System.Diagnostics;

class ScratchUtils
{
public static int Reverse(int i)
{
int result = 0;
while (i != 0)
{
result = (result * 10) + (i % 10);
i /= 10;
}
return result;
}

public static bool IsPalindrome(int i)
{
return i == Reverse(i);
}

public static void Main()
{
Debug.Assert( 0 == Reverse(0));
Debug.Assert( 1 == Reverse(1));
Debug.Assert( 21 == Reverse(12));
Debug.Assert(-21 == Reverse(-12));

Debug.Assert(IsPalindrome(1));
Debug.Assert(IsPalindrome(11));
Debug.Assert(!IsPalindrome(12));
Debug.Assert(IsPalindrome(121));
}
}

Tuesday, September 11, 2007

Java - Cannot Resolve Symbol

You get a "cannot resolve symbol" message because the compiler doesn't recognize something you've typed. It's as if you instructed your friend to "fernt PL^%", to which s/he would likely reply, "Huh?". The compiler errors will tell exactly which symbols it does not recognize; correct these errors by properly defining variables, importing the correct classes, implementing the appropriate methods, etc.

Sunday, September 02, 2007

.NET - Connecting to SQL Server Express from VWDE

I was trying a tutorial for Visual Web Developer Express, and kept running into problems connecting to SQL Server Express. When I tried to configure the security settings by clicking on the security tab in the ASP.NET Web Site Administration Tool, I received the following error:
There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.

After researching a bit, I used the SQL Server Configuration Manager to use "Local System" as the built-in account (found under the [Log On] tab for the running SQL Server Express instance). Then, I had to add a Web.config to my project with the following connection strings:

<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString="Data Source=localhost;
Initial Catalog=aspnetdb;
Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>


After that, the connection succeeded, and I was able to continue with the tutorial.

Friday, July 06, 2007

Groovy and the Lambda Calculus

I've been playing around with the Groovy language, and have recently been involved in a discussion regarding the addition of closures to Java. Tangents lead to tangents, and all of a sudden, I find myself reading about Perl and the Lambda Calculus. Oy.

I had just started trying to get my head around the idea of the lambda calculus when the author brought up the subject of "currying", and discussed the "Lambda Calculus Way"™ of writing an addition function built on the concept that functions can only take a single argument. The author showed how to express such a thing in Perl:
    sub add {
my $x = shift;
my $f = sub {
my $y = shift;
return $x + $y;
}
return $f;
}

Groovy supports writing code like this too, so I thought I'd see what I could come up with in Groovy syntax. Here's the beast:
    def add (x) {
return {
y -> return x + y
}
}

And the test...
    assert 7 == add(3)(4) // whew.

If there's a Groovy expert out there reading this blog, let me know if there's a better way. All right, back to the essay...

Wednesday, July 04, 2007

Non-Static Members and Static Contexts

A question commonly asked on Java forums concerns an error message similar to the following:

non-static variable cannot be referenced from a static context

In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."

The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).