List of Cartoon and Movie Characters

What times fly by? It is so long time since I wrote something here and it feels like it was yesterday (again?). It is even equally long time since I have worked on my Sudoku project. Unfortunately Sudoku has to wait better days until I am less busy with work. Anyway, I can put few sentences in the blog. It is about something I had to make for the work.

Currently, in context of a project for a customer, I had to generate about 2500 imaginary names and social numbers for a database project. I had to do it in order to be able to take a database off from customer’s network due to confidentiality of personal data stored in it in accordance to Swedish law.

I could have used same name and same number for all records, and for most testing purposes 2 records with data and 2 different names, Mickey Mouse and Donald Duck, would do fine. But in some cases it is nice to have the entire set of data.

Of course I have searched the internet for the list of names I could use. Unfortunately I didn’t found any downloadable list with lots of names in parsing-friendly format. There probably is some, but I don’t know hwere :-) ; if somebody can point me to some nice link I would be thankful.

Instead I have managed to find a nice list of cartoon characters, and another list of movie characters. It was posted on some web forums, so I have cut-pasted it in a text file. There is not much to say about; it is one name per line in plain ascii text for easy parsing. As a note, I use ‘#’ as a comment starter, and movie list uses ‘-‘ as a delimiter between movie character and name of the movie and actors playing it in the movie.

Lists are by no means exhaustive, especially cartoons, so if you have a character I miss I would be glad if you post it in a comment or send an email with updated list.

So if you need a big list of fiction names download and try a list of cartoon characters and/or movie characters.

Posted in Programming, tools, Uncategorized | Leave a comment

Sudoku File Formats

For testing the solver I obviously need few puzzles to work with. Since I am no fan of manually inserting the values I was looking around for some database to download. Whauh! It turned out there are tons of different file formats, solving techniques and so on. This page shows just few. I am amazed how many different techniques for solving sudokus there are; or helping techniques or what should they have being called, at least according to that rating table on the page.

I haven’t actually managed to find too many free databases with Sudoku games. I did found few on page for SimpleSudoku and quite a few overhere. The former seems to be devoted to a special problem (the smallest number of cues required for unique solution). Database consists of almost 50 000 puzzles in sdm format which is quite trivial and easy to parse so I have kind opted to use those puzzles to start with.

Here is fast and dirty parser for puzzles in sdm format:

import java.io.*;

public class SDMFileReader implements SudokuFileReader {
    
    public SDMFileReader(String filename){
	try {
	    br = new BufferedReader(new FileReader(filename));	    
	}catch(Exception e){
	    e.printStackTrace();
	    try{
		br.close();
	    }catch(Exception e2){
	    }
	}
    }
    
    public boolean hasMoreRows(){
	return rowoffset < kind*kind;
    }

    public boolean hasMoreGames(){
	boolean b = false;
	try{
	    b = br.ready();
	}catch(Exception e){
	}
	return b;
    }

    public void readGame(){
	try{
	    rowoffset = 0;
	    game = br.readLine();
	}catch(Exception e){
	}
    }

    public String nextRow(){
	String row = game.substring(rowoffset,rowoffset+kind);
	rowoffset += 9;
	return row;
    }

    public void close(){
	try{
	    br.close();
	}catch(Exception e2){
	}
    }
    
    private File file;
    private String game;
    private int kind = 9;
    private BufferedReader br;
    private int rowoffset = 0;
}

Obviously some more control on input correctness might be in place, but for a starter and time invested, this one is just fine :) .

Posted in Java, Programming | Leave a comment

Undo/Redo in Swing

As I recall, Swing does have some kind of undo/redo support so after some googling around I have managed to implement it in my SudokuField. Actually I did my own stack and undo redo operations first, but I wanted to learn how is done with built-in support because I suspected it to be a bit more elegant. Turned out to be a bit fuzzy instead , but still the code to use built in support turned to be somewhat shorter (not much actually ).

public class UndoTextField extends JTextField {

    public UndoTextField(){
	
	getDocument().addUndoableEditListener(urm);

	KeyStroke z = KeyStroke.getKeyStroke(KeyEvent.VK_Z,Event.CTRL_MASK);
	KeyStroke y = KeyStroke.getKeyStroke(KeyEvent.VK_Y,Event.CTRL_MASK);

	getKeymap().addActionForKeyStroke(z,new UndoAction());
	getKeymap().addActionForKeyStroke(y,new RedoAction());
    }
    
    class UndoAction extends AbstractAction {
	
	public void actionPerformed(ActionEvent e) {
	    try {
		urm.undo();
	    } catch (CannotUndoException ex) {
	    }
	}
    }
    
    class RedoAction extends AbstractAction {
	
	public void actionPerformed(ActionEvent e) {
	    try {
		urm.redo();
	    } catch (CannotRedoException ex) {
	    }
	}
    }
	
    static UndoManager urm = new UndoManager();
}

UndoManager is static here because it will be shared between all text field components on a Sudoku panel. Achieved behavior is not exactly what I was hoping for; but it is close enough that I am satisfied considered how short code is (I have own implementation since before, but it is a bit messy to adapt, so I will let it out).

Finally here are two applets to illustrate this:

A JTextField with undo/redo stack.

Several JtextFields with shared undo/redo stack.

Use CTRL-Z to undo and CTRL-Y to redo.

Posted in Java, Programming | Leave a comment

WordPress annoyances

Whau; so much trouble just to include an applet in a WordPress post! It took me at least one hour of googling around to find the problem: line breaks! All html code to embedd applet has to be in one line!

There is no need to download and install any plugins; just remove all line breaks from html that embedds applets. For example:

Even in this example, some text is removed: Sudoku.class from “code” param.

Even bigger annoyance: applet + syntax highlighter == no no.

For some reason, JRE is trying to load a class with name “class”, when pre name=”code” class=”java” tag is used! Of course I have not forgott to close pre tag with matching /pre So no syntax highlight for exampel prior to applet … :-)

So much time spent to find about such basic stuff. Welcome back to year ’98.

Final annoyance: “Preview Changes” stops working after some time when writing new post. It just stops functioning. Nothing happends. No big deal; I can always click on “view post” link, but for that to work I have to save post; and I don’t really want to publish a post I am not done with yet :-( .

Annoying.

Posted in Uncategorized | Leave a comment

Sudoku Framework

It is ugly, snowy and rainy day overhere in Sweden. What you do such a day? I have been lazy and done some more Java programming to kill my time.

SudokuField

First thing was to update my Textfield to become a SudokuField. Obviously to become a Sudoku input, a text field has to follow few rules: it has to allow only certain characters to be typed in and only certain number of them. It also has to obey rules of Sudoku game, which means no duplicates in rows, columns or mini grids.

Range and number of characters depends obviously on type of Sudoku game, like range for 9×9 Sudoku would be digits 1 to 9, and for 16×16 would be numbers 1 to 16. Sudoku rules are of course same for all types (no duplicates allowed). First two checks can be implemented locally in a text field. Text fields have DocumentFilter class of JText components which is supposed to be used for exactly this purpose: validating the input. Its two methods: insertString and replace are places to check for range and number of characters in input.

Checking if input is valid according to game rules is little bit more difficult. A single SudokuField is tiny isolated island that only knows of its own input. It needs somehow to become aware of its fellow siblings in same row, column and mini grid. Since all inputs are children of SudokuPanel instance, I think it is a good place to have a method there that can check for validity of move. I call it isValidMove(String s, int r, int c,int g).

SudokuPanel

For the concept, there is nothing more involved here than an array of sizexsize JTextField objects, where size is typically 9, but can be 16, 25 or some other size. JPanel can be used both in web applets or JFrame for desktop applications and is a container of my choice here.

References to fields are held in three arrays: rows, cols and grds. Having three sets of references will simplify some traversals later on.

There are some issues to deal with drawing of the board. Text fields are Swing components and as such have some default borders. They look quite OK with those borders; but I have found the panel looks a bit better without them, so I have removed them. Furthermore I use GridLayout to evenly space text fields on the panel. By leaving vertical and horizontal gaps between fields, divider lines are “drawn” for free. Finally divider lines for mini grids, that usually are drawn in some other colour, are drawn on a separate panel on top of SudokuPanel; think GlassPane. I used GlassPane because the divider lines were sometimes overwritten by text fields when text was updated. Painting on top of entire panel solves the problem.

It turned to get around 200 lines of code for those 3 classes, but it is OK foundation to write the rest of Sudoku application on. It is also quite general, but there are few places tied to a 9×9 type; mostly document filter class, which is hardcoded to accept only characters 1 – 9. Obviously I have to abstract the alphabet that is allowed in a game, but for the moment it will have to rest in favor for some other functionality.

One generality is that strings from text fields are never converted to numbers. I see no reason to do that. Sure it is faster to compare numbers than Java Strings, but imagine a Sudoku of 16×16 sizes where allowed characters are numbers in hexadecimal system. Sudoku is really about symbols not numbers. It happened that symbols for numbers 1 – 9 are mostly used, but it could be colors, letters or any other symbols that have to be placed on the board according to Sudoku rules.

Some really annoying stuff that took quite a scratching to figure out was due to different versions of Java plugin installed. It seems that JRE 1.7 works fine in IE9, but Firefox and Chromium use older, 1.6. I didn’t found a way to get either of those browsers to accept latest 1.7 JRE, so I had to fix panel class and add some padding to get it to display nicely in older versions. Seems like there was a bug in older version of GridLayout manager as I googled for some possible problems, but I am not sure. From the picture it is possible to see that in older version (Chromium, Firefox), text fields are rendered from point (0,0), while newer respects horisontal and vertical gap from all four borders.

Differences in rendering between Java versions.

Code to fix it:

String jv = System.getProperty("java.version");

try {	  
	  int version;
	  version = Integer.parseInt(jv.charAt(2)+"");
	  if(version < 7)
	      c.setBorder(BorderFactory.createEmptyBorder(3,3,0,0));
	  else
	      c.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
      }catch(Exception e){
	  // do something here if desirable ...
      }

Finally my little Sudoku framework as an applet:

Java applet that draws a Sudoku frame.

When using applet you can click on fields and input numbers 1 - 9. The applet will prevent incorrect input and beep. Obs, you can't play sudoku! It is just a gui with no brains yet :-)

Latest Firefox has some issues with rendering; the applet is not rendering properly if page is scrolled! It renders first time, but when page is scrolled it gets messed up and is not redrawn properly.

Posted in Java, Programming | Leave a comment

Resizable JTextField

It has once again being long time since last update of my blog, more than year or so … as usual :-)

Recently I have found a little project of mine which I started long time ago. Actually it was one of my student projects: a Sudoku solver of course. I started this like more than 7 years (or more) ago, but never had time to finish it. In mean time, I have stopped using Java, not because I don’t like it – I do; but because I had other projects (mostly in C/C++ and VB) taking my time. However back to roots; let see how much Java one remembers after many moons of inactivity (I think since version 1.5 or something).

I don’t know what you think about JTextField, but In my eyes, rendering of text in a JTextField is plain brain dead.

I say this because, if you rescale your text field, the text will stay at very same size. It means you can have gigantic sized text field, yet the text in it will stay at same tiny size. Being a guy in almost forties, I can tell you that I feel the default size of text in JTextField is too small to be viewable :) . For those reasons I wish to be able to resize my JFrame by dragging borders of my application and text to resize as well.
To start with, here is my small application to display a textfield:

import javax.swing.*;
class TextFieldTest {    
    public static void main(String[] args){
	JFrame frame = new JFrame("Text Field Test");
	frame.setSize(100,100); 
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	JTextField tf = new JTextField();
	tf.setHorizontalAlignment(JTextField.CENTER);
	frame.add(tf);
	frame.setVisible(true);
    }
}

Screenshot of default JTextField with some text added.
Default JTextField with some text added:

I added horizontal alignment to text field just for aesthetics. If you compile and run this app you will get a window like in picture above. I have also typed some text in as example. That text field is quite big, but the text remains same size as if textbox had default size. Resize the window, and text stays same size, no matter how big or small the text field (which by default is resized to window size automatically).

Screenshot of default JTextField with some text added.
JTextField with some text added and scaled

To fix this thing we have to scale text as function of height and width of the text field. How to calculate scale? Change in textbox size (ration between start size and current size), will give us scale factor with which to multiply font size.

Also, in order to make text change with resizing events, we have to register our text field for ComponentListener events. ComponentListener is called when a component is resized, shown, hidden or moved. Since we are interested in only resizing events we will have to implement componentResized method of ComponentListener interface. With all this said, here is the code for a text field that I gave name ResizableTextField:

import javax.swing.*;

class ResizableTextField extends JTextField implements ComponentListener {
	float iw, ih, sw, sh, weight;
	boolean first;	
	public TextField(){
		first = true;
		weight = 8.0f;
		addComponentListener(this);
	}	
	public void componentResized(ComponentEvent e) {
		if (first) {
			iw = getWidth();
                        ih = getHeight();	
			first = false;
		}
		
		sw = (getWidth()/iw) * weight;
		if(sw == 0f)
		      sw = 1f;
		sh = (getHeight()/ih) * weight;
		if(sh == 0f)
		      sh = 1f;
		AffineTransform trans = AffineTransform.getScaleInstance(sw,sh);		
		setFont(getFont().deriveFont(trans));
	}	
	public void componentShown(ComponentEvent e) {}
	public void componentHidden(ComponentEvent e) {}
	public void componentMoved(ComponentEvent e) {}
}

Obviously it is quite simple, so not much to explain but one simple detail: iw and ih are initial width and height of textbox. We need those in order to calculate scale factor. Unfortunately initial width and height of the JTextField can not be taken in constructor, since width and height of components are not known before they are laid out by layout managers, which occur when components are first displayed on the screen. Instead I use a boolean variable called first, to track if our componentResized method is called for the first time, and if it is true we will then take it’s width and height since at that time those values are known. Variable called weight is there to add some further control of size.

Personally I think that original font size is too small compared with textfield’s size. There is too much white around. I simply multiply original size with some constant to make it bigger compared to original. You can even use this scale factor to give user extra control over font size, additional to ordinary font dialog. For example it can be connected to a slider, so that user can slide a slider in order to scale text.

Of course obligatory screenshot:

Screenshot of ResizableTextField with some text added.

Posted in Java, Programming | 1 Comment

WordPress upgrade

Whauh; everytime I log into my blogg, the wordpress is at new version. Either it is really well and fast developed or I am to lazy with my blogg …. well I guess both :-)

Posted in Uncategorized | Leave a comment

Visual Studio Express: Open Solution Directory

Just as it is handy to open command window in working directory from within VisualStudio, so is to open solution (or project) directory also from the IDE. If you have your projects nested somewhere deep on you harddrive or in default place for VS projects (My Documents\Visual Studio 2010\Projects), it might take some clicking with mouse in explorer. Instead you can simply add a command to open explorer in directory of your choice.

Click on Tools > External tools …. In dialog that opens click on Add. Enter some name for the tool; that name vill be shown to you on Tools menu. As command enter explorer.exe. As arguments add: /e, $(SolutionDir):

You might omit /e if you don’t want tree-view to be expanded.

This time you can’t use Initial directory since VS does not seems to understand how to pass directory name correctly to explorer. However, it will pass all arguments from command line as they are listed, with bonus that $(SolutionDir) will get expanded to name of solution directory. Again you might use any of VS predefined macros if you prefer some other directory or you can simply type in path to any folder you would like to have opened.

Posted in Programming, tools | Leave a comment

Visual Studio Express: Command Prompt in Solution Directory

Sometimes it is good to be able to open command prompt in your solution or project directory. This little tool also comes in Pro version of VS, but not in Express. Fortunately it is quite trivial to add this little time saver to your Tools menu. Open Tools menu and choose External Tools … :

In dialog that opens select “Visual Studio … “ and add $(SolutionDir) in field for Initial directory:

Click OK and you are done. You will have new option in Your tools menu to open command prompt in solution directory. You can change it to $(ProjectDir), $(ConfigurationDir) or any other directory you might find more useful. You can create several prompts if you wish, just click “Add” button , give it some name and initial directory and copy command and arguments fields.

Posted in Programming, tools | Leave a comment

Windows 7 & VS Express “Cmd here”

For some reason free users are not entitled to get this little shortcut feature installed with Visual Studio. Being able to open command window fast in some directory is invaluable. Yet it is somehow a “pro” feature :-) . Fortunately it is really simple to add this manually. There are many blogs & tutorials explaining how to do it through windows registry. You also download registry scripts that will fix this for you. Only thing is I haven’t seen one that will do this right. Typically they just call vcvarsall.bat, and leave it to explorer to sort out in what directory to start the command prompt. Unfortunately on Windows 7 this does not work satisfactory. Here is one nice blog with such script.

It will add following line to relevant registry keys:

C:\Windows\System32\cmd.exe /k "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86

Problem is that it does not pass a name of directory to cmd.exe, so it won’t start in right place. It might worked correctly on previous Windows versions, but it does not in 7.
In Windows 7 if you click in tree-view part of explorers window, it will open command window in directory where cmd.exe itself lives:



If you right click on a folder in folder view, it will open directory one level up. In example, I have clicked on build folder, but it opened command window in src folder:

This is a bit annoying, since you have to CD yourself to right folder after command window is opened.
To fix this pass a name of selected folder to cmd.exe, by adding either pushd %1 or cd %1 as first command on that line:

C:\Windows\System32\cmd.exe /k "pushd “%1” && C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86

and everything should work correctly.
I have written a small batch script to add correct “Command here” to shell that should work on all versions of windows, with both VS2008 and VS2010. It is probably not difficult to add option for VS .2005 and 2003 I guess. It should also work with other versions of VS but Express (if you need it for some reason). Since it uses environment variable to detect where VS lives on your harddrive instead of hardcoded path, it can’t use .reg files Reg scripts (.reg) can’t expand variables, so it has to be written as batch script. I don’t have 64-bit tools installed the script is written to work only with 32-bit tools, but it should be straightforward to add 64-bit entries as well. You can get it here:

http://nextpoint.se/vchere.bat

Is there really any valid reason why “Open command window here” is excluded form Express install? It is so trivial to add, that I really see no benefit for Microsoft to exclude it from Express versions.

Posted in Programming, tools | Leave a comment