Archive

Archive for the ‘General Programming’ Category

(Sweet) Chili

July 24th, 2010 No comments

Who doesn’t like chili? Perhaps vegetarians, but that doesn’t matter. Cook this. It takes less than an hour to throw it all in a pot. The hardest part is not eating it when it starts smelling delicious.

Ingredients

1 package of ground beef
6 chipotle (or other spicy) sausage
1 bulb of garlic
1 medium sized white onion
2 tablespoons (at least) of chili powder for a mild sensation
1 can of red kidney beans
2 cans of beans in molasses
2 680mL cans of tomato sauce
4 heaping tablespoons of brown sugar (optional)

Instructions

  1. Eat some breakfast or lunch. Whichever is closer.
  2. Heat pot to medium heat. Cook a package of ground beef. I used extra lean.
  3. Cut up 6 spicy sausages. Add when beef is cooked.
  4. From one bulb of garlic, remove skins of all cloves. Leave whole. Add when all inedible bits are removed.
  5. Peel and slice one medium sized white onion. Add to the pot. And stir while you’ve been adding stuff.
  6. Add 2 tablespoons (the big one) of hot chili powder.
  7. Cover and reduce the heat to low (2 on a scale of 10). Let sit a few minutes.
  8. While the pot is sitting, strain and rinse 1 can of red kidney beans. Add.
  9. Add 2 cans of beans with molasses.
  10. Add 2 cans of tomato sauce.
  11. Let sit a few minutes and then taste it. Add more chili powder as required.
  12. If it fits, you can add more of your favorite ingredient now.
  13. Optional: Add 4 heaping tablespoons of brown sugar.
  14. Let it cook at low heat until you’re hungry again.

I’m hungry again writing down these instructions.

FizzBuzz and a false coin

April 16th, 2010 No comments

I just had my co-worker visit me at home. We all work remotely so we don’t see each other on a daily basis, but he was passing through town. He brought up an interesting topic; a programming “test” called “FizzBuzz”.

The rules: Print out all values between 1 and 100. When a number is divisible by 3 print “FIZZ” and when divisible by 5 print “BUZZ”. When the number is divisible by both, print “FIZZ BUZZ”.

My simple solution to it (a Perl script) is as follows:

for ($i = 1; $i <= 100; $i++) {
 print "$i:\t";
 if ($i%3==0) { print "FIZZ "; }
 if ($i%5==0) { print "BUZZ "; }
 print "\n";
}

This meets the criteria, though I don’t check if a number is specifically divisible by both within a condition.

This brought back a memory of an “Algorithm Analysis” exam from University. I call it “The False Coin” problem, though it probably has many names.

You have a pile of coins. All of the coins are equal, except one, which is lighter than the other coins. This is the false coin. You also have a scale which allows you to compare two weights against each other. Using the scale, what is the most efficient way to find the false coin?

The other students insisted you split the pile of coins into two equal piles, weigh the two against each other and find the lighter pile, then split the lighter pile into two piles, and so on.

Close. But wrong. There is a better way and it involves splitting the first pile into three equal piles. Compare two piles, identify which of the three is the lightest pile and split that into three more equal piles, and so on. With every weighing you get rid of 66% of the remaining coins, compared to only 50% when splitting the piles by half.

So keep that in mind before your next programming interview.

Java String Validation and Scrubbing

December 24th, 2009 No comments

I find myself more and more needing to validate user input, checking for illegal characters and empty Strings.

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ScrubTest {
 
	public String scrubText(String dirty) {
		dirty = scrub("\\s+", dirty, " ");
		return scrub("^\\s?|\\s?$", dirty, "");
	}
 
	public String scrub(String pattern, String text, String replace) {
		Pattern p = Pattern.compile(pattern);
		Matcher matcher = p.matcher(text);
		return matcher.replaceAll(replace);
	}
 
	public static void main(String[] args) {
 
		ScrubTest st = new ScrubTest();
		LinkedList<String> list = new LinkedList<String>();
 
		list.add(new String("test"));
		list.add(null);
		list.add(new String(""));
		list.add(new String(" "));
		list.add(new String("\n"));
 
		for (String s : list) {
			System.out.println ("\nTesting string: \"" + s + "\"\n---------------");
			try {
				s = st.scrubText(s);
				System.out.println ("null:  " + (s == null));
				System.out.println ("empty: " + s.isEmpty());
				System.out.println ("\\n:    " + s.equalsIgnoreCase("\n"));
			}
			catch (Exception e) {
				System.out.println ("ERROR:" + e);
			}
		}
 
		String scrubbed = "\n\n\n   This   is       just a  test            \n    ";
		scrubbed = st.scrubText(scrubbed);
 
		System.out.println (scrubbed + ".");
	}
}

Produces:

Testing string: "test"
---------------
null:  false
empty: false
\n:    false

Testing string: "null"
---------------
ERROR:java.lang.NullPointerException

Testing string: ""
---------------
null:  false
empty: true
\n:    false

Testing string: " "
---------------
null:  false
empty: true
\n:    false

Testing string: "
"
---------------
null:  false
empty: true
\n:    false
This is just a test.

Slick, Phys2D, LWJGL, and Eclipse

August 13th, 2009 1 comment

This guide will be as straight-to-the-point as can be. Please note, I make an example of the Linux version in this setup, but you can substitute the instructions for Windows or Mac if that is what you use.

Purpose

Create an Eclipse project that uses Slick, Phys2D and LWJGL.

Requirements

  1. Slick – website – Download the “full distribution” slick.zip (~ 9.8 MB)
  2. LWJGL – website – I prefer to use the “last stable build” from the project repository (currently 2.2.0, ~ 3.6 MB)
  3. Phys2D – website – Download the latest build (current build 2008-04-06, ~ 100 KB)

Procedure

This is a personal preference, but I rename the Phys2D download. It downloads as phys2d-060408.jar, so I rename it phys2d.jar.

Next, extract/unzip the slick.zip file, it doesn’t matter where. We will import the files into the Eclipse workspace later anyway.

Open up Eclipse and start a new project.

File >> New >> Java Project

Presumably, you know your way around Eclipse so I will not help with the specifics of creating a project.

Now that the project is created, create a new folder called lib in the project.

File >> New >> Folder
Click the project name
Folder name: lib

Next, we import Slick and Phys2D into the project.

Right click lib >> Left click Import >> General >> File System >> Next
Browse to the unzipped slick directory and find the slick/lib folder >> OK
Select the following jar files
  • jogg-0.0.7.jar
  • jorbis-0.0.15.jar
  • lwjgl.jar
  • slick.jar
Click Finish

You’ve imported Slick, now we import Phys2D.

Right click lib >> Import >> General >> File System >> Next
Browse to the location you put phys2d.jar >> OK
Select phys2d.jar >> Finish

Now your lib folder should have those five jar files in them. Just about done.

We need to add the jar files into the project build path.

Right click the Project >> Properties
On the left, make sure Java Build Path is selected.
Click the Libraries tab >> Add JARs
Expand the Project
Expand lib
Select all of the jar files in the lib directory >> OK >> OK

You should now see a new directory in the Package Explorer called Referenced Libraries. The project is incomplete without first attaching the native libraries to lwjgl.jar. To do that, we first import those native libraries into the project.

Right click lib >> Import >> General >> Archive File
Browse to the unzipped slick directory and
select slick/lib/natives-linux.jar >> OK >> Finish
Do the same for natives-win32.jar and natives-mac.jar
(if you wish to support those operating systems)

Next, we attach those native libraries to the lwjgl.jar file.

Expand Referenced Libraries
Right click lwjgl.jar >> Properties
Select Native Library at the left of that window
Location path: >> Workspace
Expand the Project
Select lib >> OK >> Apply >> OK

Now you are ready to build your awesome game.

But wait, what about using the latest version of lwjgl? We skipped that step.

Right. We did. As of right now, we’re using the the version of LWJGL that came packaged with Slick. However, some users might run into a problem with LWJGL, particularly if you’re using Ubuntu 9.04 (like I am). At this point, if I were to try to compile a Slick program, I would end up with this error:

Failed to initialise the LWJGL display

The solution to which is to use the latest LWJGL native Linux libraries.

Extract that last stable build of LWJGL that you downloaded (lwjgl-2.2.0.zip).
In Eclipse, Right click lib >> Import >> File System >> Next
Browse to the unzipped lwjgl-2.2.0 directory, to lwjgl-2.2.0/native/linux >> OK
Select all of the .so files (all of the files in the directory) >> Finish
Yes To All when asked to overwrite files

Not entirely done yet. Trying to compile now would result in the following error:

Version mismatch: jar version is '16', native libary version is '17'

So we replace the old lwjgl.jar with the new. Find it at lwjgl-2.2.0/jar/lwjgl.jar. Import it into the lib folder of the project. You know how to do that by now. Compile and run again and all should be well.

P.S. You are done with all the extra unzipped directories and zip files, etc. Everything needed to run your project has been imported into Eclipse. They can be deleted if you so choose.

Update: It seems that now there is an additional problem, as follows.

java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path

The solution was found at the jMonkeyEngine forums. You need to tell the lwjgl.jar where it can find the native libraries so it can run. Basically it calls for

Right click the project >> Properties >> Java Build Path >> Libraries
Expand lwjgl.jar
Select Native Library >> Edit
Click Workspace
Expand the project
Click lib >> OK >> OK

Backing up your Database (with GoDaddy and Cron)

March 18th, 2009 9 comments

In short, this is  a guide to setting up a cron job in GoDaddy so that your databases can be backed up (and later restored). It’s generally a good idea to regularly backup your databases, whether you think you need to or not.

This guide assumes that you are using the Linux hosting of GoDaddy.

First, get familiar with mysqldump. It’s the utility we’re going to use to do the backing up. Do you have access to your sites shell? It’s that thing you get when you log into yourdomain.com through SSH. I’ll assume you’ve got access to the command line to try this yourself and if you don’t then just follow along and trust me.

I’ll paste a facsimile of the mysqldump command that I use in my account, and then explain what it does. Keep in mind, the following command is continuous, all on one line, but I’ve broken it down to fit on this page.

mysqldump
-h DBHOSTADDRESS
-u DBNAME
-pDBPASSWORD
DBNAME |
gzip >
$HOME/html/somefolder/DBNAME_`date '+%m-%d-%Y_%H-%M'`.sql.gz

I’d like to point out the workings of that “date” thing first. Simply put, that gives the backup a name like “MyDB_03-18-2009_02-15.sql.gz” which tells us that the database, MyDB, was backed up March 18, 2009 at 2:15am.

DBNAME is whatever you named the database. As we all know by now, GoDaddy shares the database name and the database username, which is why it shows up so often.

DBPASSWORD is worth noting. There is no space between the -p and the password. That is not a typo. Just keep it as -pNoSpace or it will not work (of course, use the database password in place of “NoSpace”).

DBHOSTADDRESS can be found in the GoDaddy control panel. The control panel is found at

GoDaddy.com >> Hosting >> My Hosting Account >> Manage Account >> Databases >> MySQL

Then click the “Edit/View Details” Action for the database you want. The host address can be found in the Host Name row of the MySQL Database Information.

GZIP is what zips up the backup for us. It keeps the backup small (or at least smaller than the raw backup file).

$HOME is the full path to the backup directory. You do not need to worry about the path, just keep $HOME as it is.

And now for the easy part.

Create a file and write #!/bin/bash for the first line. Then on the second line, paste in the mysqldump command for your database. Remember to change the variables in the command to suit your account and database configuration.

Now change the permission of the script you just created to be executable by you. From the command line the command is

chmod 744 WhateverTheScriptIsCalled

You could probably change the permission from within an FTP program, like FileZilla, by right clicking and changing the permission.

Next, open Cron Manager. It is located in the Control Panel under the Content tab.

Give the cron job a name and set the frequency. Next, in the command box, browse to the location of the script you just created. Select it. Save. Done.