Monday, October 27, 2008

Onward

Over the weekend I learned the benefit of coding semantic XHTML: beauty in simplicity. By separating content from presentation, the code for a page is mostly uncluttered content, free of presentation elements.

Consider this post to be an update of my earlier post on the selection of web standards for projects going forward. It's been a very long time since I've addressed my desire to learn the tricks of the trade and one day become an artisan web designer.

Now that many of my household projects are complete (refinishing bedroom, wood stove installation) are complete, I can invest some of my time in learning the ins and outs of web design.

My Plan to Learn
In many skilled trades, it is necessary to go through a period of apprenticeship before becoming qualified to independently serve customers. A blacksmith may work many years as an apprentice, learning tricks of the trade and the basics of metallurgy prior to putting his own forged tools up for sale. In a similar fashion, I plan to be an apprentice for web design. However, instead of working hand-in-hand with a single skilled master, I will continuously consult the internet. This wonderful series of information transport tubes and digital aqueducts serves as the conduit for creative designs made by millions of people world-wide. The frosting on cake (homemade, vanilla frosting, of course) is the fact that anyone can peel back the onion and see how these designs function internally. HTML source, style sheets, and images are all subject to examination by anybody willing to click the View -> Source menu item in their web browser.

Armed with a StumbleUpon button and a shortcut to Digg, I am now poised to unleash a fury of mind-melding with the web-masters of the world.

Saturday, August 2, 2008

World of World of Warcraft

The sequel to World of Warcraft is here!


'Warcraft' Sequel Lets Gamers Play A Character Playing 'Warcraft'

Saturday, July 12, 2008

Fixing EXIF Date/Time Stamp in Photos

[UPDATE] I've uploaded source code to the SVN repository on SourceForge.net that is capable of changing the date and time stamps in JPEG EXIF images. The software is barebones, but feel free to contribute should you so desire. Eventually, a GUI would be nice. This project depends on the Exiv2 library and on Expat. You will need to link to Exiv2 and have its header files in your include path, and will need to have the Expat DLLs either installed in a globally accessable path or in the program executable directory. This software comes with no warrantee, so please use it at your own discretion and MAKE BACKUPS OF YOUR PHOTOS prior to running the software!

=====================================

It's been bothering me for a few years now -- my girlfriend's camera has an incorrect date/time setting. As a result, any photos that I import from her camera get sorted incorrectly by date by programs like Picasa or Windows Explorer (view -> details shows "Date Picture Taken").


The date and time data are not stored concurrently with the file access/create/modify data, but are instead stored inside the JPEG file, in the metadata portion. This portion is known as EXIF data, and provides a space for your camera to record all sorts of good information about the photo, such as resolution, shutter speed, F-stop, flash settings, and more. However, this data proves to be a formidable data structure to tackle independently. Luckily for me, I found a lovely library known as Exiv2. Exiv2 provides a cross-platform library for reading and writing the EXIF and metadata inside JPEG files. Using the library, it is possible to add, modify, or remove this metadata.

Some very useful scenarios for this include
  • setting the date of a scanned photo
  • correcting the date of photos from a digital camera that was not configured properly
  • storing other, extra information about a photo inside the photo itself.
For my scenario, I will be using the library to systematically correct the 1,000+ photos taken by my girlfriend's Pentax Optio S40 camera, whose date is off by 7 days, 21 hours, and 56 minutes. I'll start off by opening a JPEG, checking to see if it was captured using that model of camera, then adjusting 3 different timestamp fields: "Exif.Image.DateTimeOriginal", "Exif.Photo.DateTime", and "Exif.Photo.DateTimeDigitized".

I'll be posting my source code to SourceForge as soon as the project is approved. Check back for more info.

[UPDATE]: After I spent time successfully writing software to perform this action, it appears as if my efforts are futile. Every time I turn on the Pentax Optio S40, the time changes by 1 hour and 20 minutes. By turning on and off the camera repeatedly, I find this to be fairly consistent.

I turned the camera on/off within seconds, and noticed the time change:
  • 7/3/2008 10:02pm
  • 7/3/2008 8:42pm
  • 7/3/2008 7:22pm
  • 7/3/2008 6:02pm
It looks to me like a systematic software bug. The camera has version 1.0 of the firmware (found by holding down the Menu button at power-on). I have found no path for upgrading firmware for the Optio S40 via the Pentax website either.

I still plan on posting the source code to my application on SourceForge, pending approval.

Wednesday, July 2, 2008

Snooze Button Addiction

I don't know too many people who can top my inexplicable ability to repeatedly torture myself in the wee hours of the morning. At the peak of my snooze button habit, I would tell myself the night before that I would "definitely wake up" at 6am. In reality, I would wake up at 9:30AM or sometimes even later, while reprogramming the alarm clock in 6-15 minute intervals.

"Reprogramming?" That's right. I don't have a snooze button at all. I disabled it years ago because I recognized my problem. However, I quickly learned that pushing only a few more buttons not only allowed me to snooze once again, but would also allow me to customize how long I snoozed for.

I've tried moving the alarm clock to the other side of the room without luck. I've tried moving the alarm clock to a different room; still no luck. I've tried setting multiple alarms, setting the coffee maker to go off at a given time, but still, to no avail.

It's worth noting that I do not have a problem waking up when people are depending on me to be somewhere. I only exhibit this behavior when I have the option of sleeping late without consequence. I've behaved this way since college, at least, and have become frustrated with myself for not having any free time in the afternoon. Thus, I have found what I think is a path toward breaking my habit.

Throw away the alarm clock. Don't use it. Don't set it. I obviously can't handle the tremendous power of the alarm clock when I have nothing scheduled in the morning. I know other people have this problem as well, so hopefully I'll break through some barriers here.

I have not used my alarm clock all this week. While I woke up later than I would ideally like to wake up, I felt completely rested in the morning. Today, I felt myself drift in and out of sleep slightly before 6am, indicating that I was at an ideal point in my sleep cycle to wake up. I didn't wake up because I decided not to get out of bed, but at least this gives me a glimpse of what it's like to use a natural, biological clock instead of a blaring, disturbing, and obnoxious electronic device.

I will continue without an alarm clock until my sleeping habits improve, except for mornings in which meetings or appointments are scheduled. After all, if the source of my problem is a habit entwined with that cursed device, I must start by eliminating it from the equation.

Monday, June 30, 2008

Bird or Man? You Decide.

Yesterday I traversed the back roads of Northern NJ and upstate NY to give in to the beckoning call of flight, despite warnings of isolated thunderstorms and precipitation. My efforts were rewarded through the enjoyment provided by this flight, what I consider to be one of my best to date.



A powerful and confident launch, followed by proper adjustments toward my target, appropriate speed control, and a finely timed flare made this flight worth the 3 hour round trip drive to Ellenville.

In related news, our harnesses arrived. They look and feel awesome.



And yes, the white racing stripes will make me go faster.

Wednesday, April 30, 2008

Crappy Problems

Some people don't have a clue when it comes to being a respectful dog owner. Apparently, someone in my neighborhood is a repeat offender, continuously letting their dog take super-sized steamers right in front of my mailbox. In response to my frustrations, I am posting this sign next to my mailbox, in hopes that the responsible party will be deterred from continuing this blasphemous behavior. I'm not satisfied with those "Curb your dog" signs because they are too commonplace and do not make people think twice. Those signs imply that the underlying message is simply a recommendation, to be adhered to only on odd Saturdays of leap years when the moon is full and the temperature is 57 degrees at 2:30pm.

This sign, however, portrays consequence.

If this doesn't work, I'm upgrading to a bigger sign and a webcam.

I also had some fun over at diy.despair.com:

Thursday, April 24, 2008

Building a Sailboat on the Cheap

[Update: I've taken down direct links to images from pdracer.com, and instead I'm providing you with a link to the page containing the image. PDRacer does not like externally linked images, and I have not obtained/asked for permission to copy photos from the site.]

If you live near a lake, pond, or any other body of water with sufficient depth (~2') and access, you have the wonderful opportunity of sailing on said body of water.....

But you don't know how to sail, don't have a boat, don't want a trailer, can't fit a boat in your yard, and don't have the expendable cash to buy a sunfish or equivalent. Even if you did buy a sunfish, you still can't fit yourself, both of your kids and the dog in that boat. What about fishing gear? Lunch?

These are all excuses. All you need is a small amount of time, some basic hand tools, and a roof rack, and you can be sailing in one of these lovely boats known as a Puddle Duck Racer.



This boat can be constructed from materials that are mostly available at your local Home Depot, such as 5.2mm luaun plywood, polytarp or Tyvek (for the sail), and douglas fir. As somewhat of a stunt, the boat can be built in a day. However, to build it properly takes more time, as it needs to be sealed with epoxy, paint, and so forth.

If you have your doubts about how much weight a properly constructed Puddle Duck Racer (PDRacer) can hold, then take a look at this:

Payload Records @ pdracer.com


This is a photo of the world record for most weight supported by a PDR; 1700lbs of people in hull number 136, built by Rick Landreville. This configuration is a bit unconventional (two sails, hull wider than 4'), but illustrates the capability of this little boat quite well!

This little boat allows its creator to express endless creativity. Check out the photo gallery over at PDRacer.com to see all the wonderful variations, paint schemes, and themed boats that people have built and enjoyed.


If you aren't convinced yet about building your own, watch the following videos and see if you change your mind! When you are ready to begin building, make sure to join the Yahoo Group (pdracer) for endless community support during your build!

Check out the speed Detlef Teufel gets in his PDR:


Or, enjoy a smooth cruise with Detlef:


David "Shorty" Routh put together this sweet video that makes me want to finish my PDR today!


Wednesday, April 23, 2008

Validation Hell

I just told my friend check out my latest post on hang-gliding, and he responded with "WTF LEARN HTML NOOB! I can't view your video!" Not only are some of my posts non-compliant, but it appears as if the template I'm using is also non-compliant. This bothers me, so I'm going to fix it.

The first thing I did was change my embedded flash video to use the "Satay Method" from A List Apart. This involved throwing the embed tag out the window in favor of solely using the object tag.

I'll keep updating this post as I find more sources of errors.

It appears as if I am screwed. Since I have no access to the full HTML source of this blog, I can't control the escaping of ampersands or the fact that an iframe is used, while the XHTML 1.0 strict DTD is declared at the beginning of the page. What's the deal here?? Looks like I will eventually have to go with independent hosting and a blog that allowed me greater control.

Does anyone have suggestions for hosting this blog?

Monday, April 21, 2008

My First Hang Gliding Lesson!

Last weekend was incredible! I found myself running swiftly down a grassy slope and eventually drifting into the sky for a brief moment! This is incredibly fun. What a wonderful sensation. I highly recommend trying this out sometime. It's not very expensive to take lessons. Mountain Wings in Ellenville, NY has package deals that are quite appealing!





Here's the link to my photo set on Flickr!

Wednesday, April 16, 2008

How to Save 20% on Gasoline

Recently, I realized that the fuel mileage I was obtaining in my 2005 Corolla (manual transmission) was not what it should be. I was getting around 32MPG, and could go roughly 330 miles per refueling stop. I knew that the car was much more capable, as I'd seen mileage as high as 37MPG in the past.

I decided to run an experiment. With a few changes to my driving style, I found myself getting over 40MPG! To put this in perspective, that's like going to the gas pump, filling up your tank, and paying 20% less! (for eaxmple: $2.47 per gallon versus $3.09 per gallon prior to changing driving styles). My commute to and from work takes about 5 minutes longer than previous, yet it is more consistent (no stop-and-go traffic). So, how did I do this?

Brakes: Your Enemy
Efficiency is defined as the ratio of useful output energy divided by the input energy. Differences between input energy (gasoline consumed) and output energy (proportional to miles driven) are caused by losses of energy due to heat, wind resistance, and mechanical resistance. There's not much you can do about wind and mechanical resistance, other than removing your roofrack, etc. However, you can dramatically reduce losses due to heat caused by braking.

Using the Brakes
Every time you press the brakes, you are generating heat, thereby wasting the energy you provided (gasoline) to your car to achieve the speed you were traveling at. Another way to think about this is to compare your decrease in speed while braking with the required use of the accelerator to achieve an equivalent gain in speed. This technique is simple: Don't use the brakes unless you need to, OR, AVOID SITUATIONS WHERE BRAKING IS NECESSARY. This means you should avoid tailgating. You should also try to preemptively anticipate red lights, slowing traffic ahead, and stop signs. For your regular commute, this may prove to be very easy.

Look way ahead in the distance; not just at the car immediately in front of you. If the car in front of you is very large and your visibility is limited in the distance, you may consider taking signs from reflections of brake lights on the wet road or on other reflective objects. In some cases, you can see brake lights through the car ahead of you.

Brake sooner! When you see a light turn red in the distance, slow down immediately and coast to the light, such that you never have to stop the car. By coasting to the light with some non-zero velocity, you are maintaining energy instead of wasting it all (by stopping completely). This is also much safer than braking at the last second, where gravel, oil, and other factors can cause accidents. As a note, you should not cross the intersection at high velocity as soon as the light turns green. This is dangerous, as aggressive drivers tend to speed up at the sign of a yellow light.

Engine Braking
Don't do it unless you need to slow down at a greater rate than possible by coasting. If you drive a manual transmission vehicle and do not have your foot on the gas and you do not need to slow down at a fast pace, simply depress the clutch and coast. In some areas with hills, this is possible for miles!

Keep the RPMs Low!
Don't accelerate quickly! Keep your RPMs low. Some vehicles have variable valve timing that engages at relatively low RPM (i.e. you don't need to floor the vehicle for it to engage). This can result in more available power at the expense of much greater fuel usage. Accelerating slowly also gives you additional time to anticipate upcoming slow areas, such as red lights or police activity.

Take the Slow Roads!
I enjoy my commute much more now that I've discovered some slow back-roads to travel instead of I-80. On a day without traffic, a commute through the back-roads is about 5 minutes longer than taking the highway. On a day with traffic, the back-roads can be 20 minutes shorter (or more). In addition, I can drive slower on the back-roads, thereby reducing the force of wind on the car. Wind resistance does not increase linearly with speed. In other words, if you double your speed, the wind resistance quadruples! Thus, there is a bigger hit in fuel efficiency between 65 and 70MPH than between 40 and 45MPH.


Conclusions

Drive slower, brake sooner, and avoid situations where braking is necessary! Also, do not accelerate quickly. Not only will your commute be more efficient, but you will likely find it to be less stressful and much safer. By utilizing the mentioned techniques, I was able to increase my fuel efficiency from 32MPG to 40MPG, and equivalent savings of about $7 per refueling at today's gas prices.

Monday, March 31, 2008

Custom Cell Editors and Renderers in a JTable

I have not disappeared! Working 60+ hours per week will make it seem that way, however. This article switches gears to Java, be it an applet or local application. It took me a bit of research to figure out how to accomplish custom cell renderers and editors on a cell-by-cell basis inside a JTable, so I thought I would share my experiences with you.

Let's say you need to whip up a control GUI, and you need to do it fast. You need to control variables of different types, and there are a few dozen of them...maybe even more. The task at first seems daunting. You could lay out all of your components in a GUI builder, hook up all the events, and test each one. You could code by hand if you need practice typing. Or, if you do not feel like dealing with layout styles (GridBagLayout is my favorite), and you need your GUI to be quickly extensible, you can use a JTable to hold your controls. This requires a small amount of effort to enhance the typical behavior of a JTable, where there is only one type of renderer and editor per column. After all, we don't want simple text areas for all of our variables. Some of them are hexadecimal numbers, combo box options, check boxes, and more.

With this entry, I'll walk myself through the process of creating custom cell renderers and editors, and hopefully you'll be able to follow along in the process. I'll assume that you are familiar with the AbstractTableModel and JTable classes.

First step: create a class that extends JTable. We need this so we can modify the behavior of two key functions, namely:

public TableCellEditor getCellEditor(int row, int column)
public TableCellRenderer getCellRenderer(int row, int column)


Let's start with the getCellRenderer function. Here's what mine looks like:

public TableCellRenderer getCellRenderer(int row,
int column)
{
if(column != 2)
return super.getCellRenderer(row, column);

TableModel mdl = getModel();

if(init)
{
createDefaultRenderers();
/* System.out.println("BEGIN");
init = false;
Collection col =
defaultRenderersByColumnClass.values();

Iterator iter = col.iterator();
while(iter.hasNext())
{
System.out.println(
iter.next().getClass());
}
System.out.println("END");

for (Enumeration e =
defaultRenderersByColumnClass.keys() ;
e.hasMoreElements() ;)
{
System.out.println(e.nextElement());
}
System.out.println("END");
*/

}

if(mdl.getValueAt(row,column).getClass() == Boolean.class)
return rnd_bool;
else if(mdl instanceof MyCustomTableModel &&
((MyCustomTableModel)mdl).useComboBox(row))
return rnd_edit_quad;
else
return rnd_hex;
}

I used the commented-out section to see what default renderers were supported by JTable, so I could refer to them appropriately if need be. You will see this come into play later. For columns other than number 2, my particular table has static text displayed, so I chose to use the default cell renderer. To do this, I simply call getCellRenderer on the parent class, and I can expect the default behavior.

The table model, obtained by calling getModel(), is the data provider. For a given row and column index, the cell may be a boolean, hex number, choice, or more. It's convenient to use the data type from the table model as a source for driving which type of renderer to use.

You can see toward the end of the function that the return value (the renderer) can be based on any data your underlying model provides. You could create a function in your table model called "getRendererType," and have it return a number or enumeration value that represents the type of renderer to use. Six in one hand, half a dozen in the other.

Next, let's look at what the custom renderers look like (the variables rnd_hex, rnd_bool, rnd_edit_quad). As a note, I've declared these objects inside the custom JTable class, which is why there is no declaration in the function.

The HexRenderer class, used to represent Long values in hexadecimal form (and preceded by '0x'), is extremely simple:

class HexRenderer extends DefaultTableCellRenderer {

public HexRenderer() { super(); }

public void setValue(Object value) {
setText("0x"+Long.toHexString((Long)value));
}
}

The HexRenderer class simply changes the formatting of the text before placing it into the cell. The boolean renderer is a little different, as we'd like a check box as an indicator:


public class BoolRenderer extends JCheckBox
implements TableCellRenderer
{
public BoolRenderer()
{
super("Render");
}

public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column)
{
this.setSelected((Boolean)value);
return this;
}

public void validate() {}
public void revalidate() {}
protected void firePropertyChange(
String propertyName,
Object oldValue,
Object newValue) {}
public void firePropertyChange(
String propertyName,
boolean oldValue,
boolean newValue) {}
}


The class BoolRenderer extends the component it will be displayed as, in this case a check box, and it implements the interface TableCellRenderer. If you read up in the Java documentation, you'll find that table cell renderers are re-used across cells. In other words, you do not need 40 check box objects to render 40 cells that should be rendered as check boxes. When the JTable calls getTableCellRendererComponent, it provides the value of the cell, the location, and a reference to itself. You now have all the information you need to set up this GUI component as it should look before it's actually rendered. In our case, we set the state of the check box based on the value of the cell. Any time the cell needs to be re-painted, this component will be used.

The empty functions in the BoolRenderer class are there on purpose to improve performance in larger data sets. Because BoolRenderer does not need all the functionality of a real JCheckBox, we can snip out these features and gain additional performance. We're just using this component for painting our cell, remember?

Custom Cell Editors


Next on our list is how to create custom editors. We have the means of displaying values, but how do we edit them using similar components? Let's take a look at the getCellEditor function of our class that extends JTable.


public TableCellEditor getCellEditor(int row,
int column)
{
if(column != 2)
return super.getCellEditor(row, column);

TableModel mdl = getModel();

if(mdl.getValueAt(row,column).getClass() ==
Boolean.class)
return edit_bool;
else if(mdl instanceof MyCustomTableModel
&& ((MyCustomTableModel)mdl).useComboBox(row))
return rnd_edit_quad;
else if(mdl.getValueAt(row,column)
instanceof Long)
return edit_hex;
else
return (TableCellEditor)defaultEditorsByColumnClass.get(Number.class);

}


This seems pretty self-explanatory. Simply use whatever logic you desire to determine what kind of editor to use. If you are looking to use the default editor for a given class, you can use (TableCellEditor)defaultEditorsByColumnClass.get(Number.class);. I wasn't sure what classes were available to use, so I used the commented code inside getCellRenderer to enumerate all the available default renderers.

Let's take a look at the BoolEditor class:



class BoolEditor extends JCheckBox implements
TableCellEditor, ItemListener
{
Vector editorListeners;

public BoolEditor()
{
super("Edit");
addItemListener(this);
editorListeners = new Vector();
}

public void itemStateChanged(ItemEvent e)
{
System.out.println("Firing!");
for(int i=0; i<editorListeners.size(); ++i)
{
((CellEditorListener)editorListeners.
elementAt(i)).editingStopped(
new ChangeEvent(this));
}
}


public Component getTableCellEditorComponent(
JTable table,
Object value, ]
boolean isSelected,
int row,
int column)
{
this.setSelected((Boolean)value);
return this;
}

public Object getCellEditorValue()
{
return this.isSelected();
}

public boolean isCellEditable(EventObject anEvent)
{
return true;
}

public boolean shouldSelectCell(EventObject anEvent)
{
return true;
}

public boolean stopCellEditing()
{
return true;
}

public void cancelCellEditing()
{
}

public void addCellEditorListener(CellEditorListener l)
{
editorListeners.add(l);
}

public void removeCellEditorListener(CellEditorListener l)
{
editorListeners.remove(l);
}


}


It seems like a lot, but it really isn't. Let's follow the code step-by-step. First, note that this component extends JCheckBox. This is necessary, as we'd like to borrow the functionality of the check box and use it for editing some of our cells. Next, note that the class implements TableCellEditor and ItemListener. The TableCellEditor interface requires that we implement the following functions:

getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) - Note this is just like the case for getTableCellRenderer
addCellEditorListener
cancelCellEditing
getCellEditorValue
isCellEditable
removeCellEditorListener
shouldSelectCell
stopCellEditing


Basically, the table will add a listener to a cell and wait for the user to finish editing the cell. Our cell editor notifies the JTable that the user has finished editing the cell by using the CellEditorListener object added to the component and calling its editingStopped event. For example, as soon as the user releases the mouse button inside the checkbox, the value of the check box changes, the event is captured by the itemStateChanged event (part of the ItemListener interface), and any CellEditorListener objects are notified. When the table is done listening for events, it can remove the listener from the object's list by calling removeCellEditorListener.

That was a nice example -- now let's check out the class used for editing hexadecimal numbers, HexEditor:


class HexEditor extends JTextField implements
TableCellEditor, ActionListener
{
Vector editorListeners;
long thevalue;
long oldvalue;

public HexEditor()
{
super("Edit");
addActionListener(this);
editorListeners = new Vector();
}

public void actionPerformed(ActionEvent e)
{
System.out.println("HexEditor actionPerformed() Firing!");
try
{
if(getText().indexOf("x") >= 0)
thevalue = Long.parseLong(
getText().substring(getText().indexOf("x")+1),16);
else
thevalue = Long.parseLong(
getText(),16);
}
catch(Exception ex)
{
thevalue = oldvalue;
}

for(int i=0; i<editorListeners.size(); ++i)
{
((CellEditorListener)editorListeners.
elementAt(i)).editingStopped(new ChangeEvent(this));
}
}


public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column)
{
this.setText("0x"+Long.toHexString((Long)value));
thevalue = (Long)value;
oldvalue = (Long)value;
return this;
}

public Object getCellEditorValue()
{
return thevalue;
}

public boolean isCellEditable(EventObject anEvent)
{
return true;
}

public boolean shouldSelectCell(EventObject anEvent)
{
return true;
}

public boolean stopCellEditing()
{
return true;
}

public void cancelCellEditing()
{
}

public void addCellEditorListener(CellEditorListener l)
{
editorListeners.add(l);
}

public void removeCellEditorListener(CellEditorListener l)
{
editorListeners.remove(l);
}


}


The HexEditor class contains the same boilerplate functions that handle the CellEditorListeners, but this time it extends JTextArea to provide text input. As a note, validation is not performed as the user types. If the user were to type some other than a hexadecimal number preceeded by '0x', the cell will revert to the previous value it contained. This class was designed to support unsigned integers. Since there are no unsigned types in Java (aarrrgg!), I opted to use a number with twice the amount of bits (a Long) and ignore the top 32 bits.

Finally, let's take a look at a cell editor (and renderer) that utilizes a combo box to provide the user with a set of 4 choices:


class QuadRenderer extends JComboBox implements TableCellRenderer, TableCellEditor, ItemListener
{
Vector editorListeners;

public QuadRenderer()
{
super();
editorListeners = new Vector();
addItem("Choice A");
addItem("Choice B");
addItem("Choice C");
addItem("Choice D");
addItemListener(this);

}

public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange()==ItemEvent.DESELECTED)
{
System.out.print("Firing!!");
for(int i=0; i<editorListeners.size(); ++i)
{
System.out.print(".");
((CellEditorListener)editorListeners.
elementAt(i)).editingStopped(
new ChangeEvent(this));
}
System.out.print("\n");
}
}

public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
{
System.out.println("Setting index to: "+value);
this.setSelectedIndex(((Long)value).intValue());
return this;
}


public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column)
{
System.out.println("Setting (editing) index to: "+value);
this.setSelectedIndex(((Long)value).intValue());
return this;
}

public Object getCellEditorValue()
{
return this.getSelectedIndex();
}

public boolean isCellEditable(EventObject anEvent)
{
return true;
}

public boolean shouldSelectCell(EventObject anEvent)
{
return true;
}

public boolean stopCellEditing()
{
return true;
}

public void cancelCellEditing()
{
}

public void addCellEditorListener(CellEditorListener l)
{
editorListeners.add(l);
}

public void removeCellEditorListener(CellEditorListener l)
{
editorListeners.remove(l);
}

}


This class implements everything in one place; both the rendering interface and the editing interface. By now you should be able to easily recognize what's going on in this class, and you should be able to implement something comparable should you need it.

Friday, February 29, 2008

(X)HTML Part 2: XML/HTML/XHTML/WTFML

Let me preface this post with a disclaimer: I am not a subject matter expert on (X)HTML. I am merely someone who knows HTML basics and is looking to see what the latest standards are. Please feel free to correct me if I make false or ambiguous statements. I'd like to find out what standards I should aim to comply with when I do start coding something real. So, without further a due, here is the path of exploration I've taken today...

After a bit of reading and probing, I've discovered that there are several distinct differences between HTML, XHTML, and the means by which the documents are served. Instead of immediately diving into the HTML 4.01 Strict DTD (as mentioned in my previous post), I'll begin by looking at the differences between these technologies, and address things like:
  • syntactical differences
  • architectural differences
  • reasons for choosing one over another
What is XHTML?
There's XHTML 1.0, XHTML 1.1, and XHTML 2.0, which is currently in the works. It turns out, XHTML 1.0 is simply HTML information that adheres to the more strict constraints of a properly formed XML document. This means slightly more work on behalf of the coder, but faster, more automated processing of the document by the user agent (web browser or HTTP client). Some important things to know about well-formed XML documents:
  • each open tag must be explicitly closed in proper nesting order
  • all attribute values are enclosed in single or double quotes
  • all element and attribute names are CASE-SENSITIVE
  • every attribute MUST have a value
This doesn't seem too hard to accomplish, as it only requires small modifications to HTML code. XHTML DTDs exist for strict, loose (transitional), and frames, just as in HTML 4.01. In order to maintain backwards compatbility with HTML 4.01, XHTML documents should be served as the mime type text/html and adhere to the compatibility guidelines specified by W3C. So far, I see no reason not to use XHTML 1.0.

XHTML 1.1 (Modular)
This actually sounds like a nice idea -- modularize XHTML such that small building blocks can be combined into a customized, extensible DTD. The full working draft of XHTML Modularization is available at the W3C site. If you browse through section 5, you'll find details on the type of modules that may be included to form a more complex document. Inline-frames, Objects, Targets, and more are now modules. I think this will become slightly clearer when I actually start coding with it. In the meantime, have a look at this W3C tutorial on modular XHTML. I'd like to use XHTML 1.1 as the primary technology for my web development activities, but I'm not so sure about the compatibility of it at this point. Still, it's worth learning about because it will likely see an increasing rate of adoption at some point.

The Fork in the Road

So...we now understand that there are several flavors of HTML that we can use to start making something meaningful: HTML 4.01, XHTML 1.0, and XHTML 1.1. If we use HTML 4.01, we can probably get away without using stylesheets, although I see no reason we'd want to do that, because the idea of separating the content from the presentation seems very appealing. I like this idea, and I think I'm drawing a connection between XHTML and Model-View-Controller architecture. I realize MVC can be implemented in traditional HTML applications, but XHTML seems like it lends itself better to this more scalable, flexible architecture.

The leap from HTML with minimal CSS to independent XHTML and CSS compartments seems like the leap from populating a list box with every data item, to creating a view for the list box that only displays relevant data. If you've ever populated a list box with 10,000 items, you probably realize how slow and unmanageable it is (Oh, what, you'd like to add 1 more item? Let me re-organize all 10,000 items). However, if you create, say, an AbstractTableModel (Java) for accessing and updating your data, the user controls become much more responsive, reliable, and efficient.

GMail uses HTML 4.01 Transitional. Wikipedia uses XHTML 1.0 Transitional. What should I use? On one hand, we know that GMail and Wikipedia are very compatible sites, as they are viewed by millions of users from a plethora of user agents (Firefox, Netscape, IE, Opera, etc). I'd rather go with XHTML than HTML because I don't mind making my document a well-formed XML document, but what about XHTML 1.1?

After some Googling around, I find out there is tremendous debate about which technology to use. In Lachy's Log, the author is doubtful that XHTML documents served as text/html will be able to survive a transition to being served as XML documents. There's also some insightful discussion at the end of that post, and there is a list of nuances to consider when coding in XHTML.

I like a challenge, and I'd like to adopt new technology, but I'm not so sure about adoption of 1.1 (see here). And so, I will start coding using the XHTML 1.0 Strict DTD, and I will adhere to the compatibility guidelines provided by W3C.


Lessons Learned:
There are driving forces in the web technology sector that are pushing for new standards (i.e. W3C), and there are forces that are pushing back until existing standards are implemented properly (i.e. Internet Explorer non-conformance issues). The best thing a new web developer can do to stay on the cutting edge while developing applications for today's user agent implementations is to:
  • Write documents that have high compatibility from the get-go
  • Recognize points of failure when writing documents that implement work-arounds to maintain compatibility
  • Learn and practice using new standards with new, compliant user agents
User agents are very different. The Acid2 conformance test is clear evidence of that. It's also clear from the start that if we wish to maintain compatibility across many different browsers, we will need to piggy-back off of the hard-working individuals that were forced to eat hot pockets and drink coffee until 4:30am to find solutions and work-arounds.

Next Steps:
The next steps to take (not necessarily in this order) will involve:
  1. Reviewing the rules of properly structured XML
  2. Reviewing the compatibility guidelines from W3C for serving XHTML as text/html (HTML compatible, see the first paragraph of HTML Media Types)
  3. Learning XHTML tags and their attributes
  4. Learning CSS

Wednesday, February 27, 2008

HTML Part 1: Standards

There are a ton of tutorials. quick-starts, and reference sites out there for HTML. In this post, I attempt to guide myself through the plethora of digital documents in search of a better understanding of what HTML is and how to use it. What are all the tags? What do they do? How can we apply them in a useful manner?

Standards
The standard for HTML documents is maintained by the "World Wide Web Consortium," or "w3c." The current HTML standard is up to version 4.01, and version 5 is in the works. We will focus on version 4.01. Here is a link to the HTML 4.01 Specification (kudos if you read through it all -- it's large). I am taking this approach in learning HTML because examples provided by some sites will display differently in Firefox and IE, etc. Learning HTML from the W3C is like hearing the news from the horse's mouth. We'll learn the nuances of browsers at some other point, but for now we will learn to be standards compliant.

Everything you need to know about syntax...(maybe)
After clicking around a bit on the W3C site, I found the motherload of information on HTML.... the DTD, or "Document-Type Definition." Basically, the DTD describes valid keywords and syntax for HTML. If you can read the DTD, you can refer to it when coding your site. The DTD is a plain-text file, and is an XML Schema. In other words, it is a document that describes the format and structure of a given type of document, namely an HTML document. I won't lie. You'll need to brush up on your XML/SGML to be able to read the document, but I'll give you the basics here as I read. Without further a due, let us parse through this esoteric text...

We see at first glance that comments in this document start with "<!--" and end with "-->". Luckily for us, the DTD is well-documented and contains hyper links to relevant sections of the HTML 4.01 standard. As a note, I had to use the escape sequences for less than and greater than signs while typing this post. Click View->Source to check it out.

The first line that I'm curious about is the one that contains the following ubiquitous text:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Why do we need this at the beginning of each page? According to this site, we need it so our HTML and CSS will validate properly. In other words, it essentially allows us to tell the web browser that we are standard-compliant with said DTD. It turns out this is extremely important if you'd like your web page to render correctly and predictably in IE, Firefox, etc. According to A List Apart,
Using an incomplete or outdated DOCTYPE—or no DOCTYPE at all—throws these same browsers into “Quirks” mode, where the browser assumes you’ve written old-fashioned, invalid markup and code per the depressing industry norms of the late 1990s.

In this setting, the browser will attempt to parse your page in backward–compatible fashion, rendering your CSS as it might have looked in IE4, and reverting to a proprietary, browser–specific DOM. (IE reverts to the IE DOM; Mozilla and Netscape 6 revert to who knows what.)

Here is a useful link to W3C that contains a table of all of the current DTDs.

There are two main DTDs: "loose" and "strict." The "loose," or transitional DTD provides better backwards compatibility, as it includes some components that were dropped in strict HTML 4.01. Some of these components are popular, familiar tags such as "APPLET," "FONT," and "CENTER." I can code web pages, but this is all new to me. Such is the glory of participating in the tech industry, where innovation drives change, creating a culture of continuous education.

Lesson Learned:
Use the DOCTYPE tag correctly in every HTML document, and use the W3C compliance testing tool (the validator) at http://validator.w3.org/ to make sure your document contains no errors. If you plan on using these deprecated tags (see this list and look for 'L' in the last column), use the loose DTD. If you plan on using frames, use the frameset DTD. Otherwise, use the strict DTD to ensure a more uniform structure for your site. See this article at HTMLHelp for a more thorough explanation of when to use what DTD.

For the Next Post: I'll start diving into the strict DTD to see what we're allowed to put inside our standard-compliant HTML document. I'm also curious about XHTML, the successor of HTML, so we'll touch on that and see what branches of investigation warrant attention.

Helpful Definitions:
  • XML Schema - "a description of a type of XML document, typically expressed in terms of constraints on the structure and content of documents of that type, above and beyond the basic syntax constraints imposed by XML itself. An XML schema provides a view of the document type at a relatively high level of abstraction" (source: Wikipedia)

The Lofty Goals of this Blog

First off, let me express that the intended audience for this Blog is people who are familiar with and interested in programming languages and software development technologies. Now, on to the meat of the post...

College is great. Every day, students have the ability to meet new and intelligent people, learn new and cutting-edge technology, and exchange ideas with well-published professors. All this interaction, studying, and learning stimulates the mind and keeps students full of motivation and creativity.

So what happens to you when you graduate and launch your career into the real world? Will you use the skills and techniques you learned in school? No. It's likely that you will not use a large part, if not a majority, of the vast breadth of your academic knowledge. Instead, you will most likely use your newfound analytical skills to learn several specialized tasks at your workplace. Eventually, you will find your mind becoming bored with the repeated activities you perform on a daily basis.

Thus, the purpose of this blog is:
  • to exercise my own analytical and learning ability
  • to expose myself to technologies I do not regularly use
  • to hone my expertise on nuances and 'gotchas' of said technologies
  • to share my findings, lessons learned, and inspirations with you
The initial technologies I plan on addressing in this blog are as follows:
  • HTML - Yes, I already know HTML. Am I an expert? No. It's time for a review.
  • CSS - Let's learn how to do this the right way.
  • Ajax - What exactly does it mean, and how can it make my blog better?
  • JavaScript - Let's dig into the features, syntax, and capabilities
After I have finished addressing these technologies, I will use the knowledge I acquired to enhance and add features to this blog. Nifty, eh? Next, I will switch to programming languages I currently do not know or do not actively use, namely:
  • Python - I've heard wonderful things about this language. I'd like to explore how powerful it really is, then write a few example applications in it.
  • Ruby - Does it annoy you when you see buzz-terms flying in your face and you have no idea what they are? Yeah, me too.
  • Perl - It's been around for a while, looks ugly as hell, but is extremely powerful, especially at searching text.
  • many more...i.e. awk, bash, MATLAB, LabView, PHP, ASP, Flash, C#, Cold Fusion, Fortran, Adobe AIR, and even MS-DOS Batch files. If there is a particular technology you would like me to address first, please let me know!
In general, when exploring a given technology or programming language, I will try to provide information with regards to:
  • Development environments (Windows and Linux)
  • Basic syntax
  • Gotchas (i.e. garbage collection in Java, pointers and references in C++, function name mangling in DLL's)
  • How to achieve functionality (i.e. network communication, multi-threading with thread-safe shared data, user input, GUI design, file I/O, external function calls)
  • Unique and exciting features of each language (i.e. the 'Reflection' class in C#)
I personally cannot wait to start diving into programming languages, but will restrain myself until I learn how to properly represent content in a web browser without using a template or someone else's HTML/CSS.

In closing, I'd like to welcome you to the start of a new journey that will help you and I 'kick our brains' to help foster creativity, excitement, and inspiration, and avoid the plague of complacency and doldrums.