Feeds:
Posts
Comments

For a while now I’ve been struggling to remove games I’ve played on Google+. Typically I grant a Third Party game access to all of my private data, play it for a few days and then I’m done with it. This is true of all the games I’ve played on Google+ with the exception of Triple Town, which is simply awesome!

Anyway, once I’ve finished with a game, I want to block it from accessing my private data. Annoyingly Google doesn’t seem to provide an obvious way to do this in their settings. That was until I came across this link. This page allows you to revoke permissions from any Third Party application that is connected to your Google account. Google take heed – please provide a link somewhere on Plus to this page!

A Kindle for reading PDFs

I have been reading quite a lot of PDF eBooks of late at work, such as Implementing CIFS. As I don’t like reading on a bright computer monitor for long periods, purchasing a Kindle seemed like a good idea due to the high contrast, non-backlit E-Ink display. Having loads of free classics books available to download was an added bonus.

 

“…displayed like an image, and not text”

PDFs on Kindle almost work, but are a bit of a pain. Unlike regular Kindle formatted books, they are displayed like an image, and not text. The major difference is that you cannot resize the text of a PDF, instead you have to “zoom in”, as if the PDF was an image. This is a bit annoying, because you cannot make the text to a big enough size to read on one page without rotating it – so you end up using the Kindle in landscape, rather than portrait mode. This is not as comfortable as the page turning buttons are now on the top and bottom of the device. Still, the PDF formatting is perfect, e.g. images and tables look fine.*

 

On the plus side

  • The online store is better than I imagined for finding books, even free ones. They literally download in seconds, which is very satisfying, but a little disconcerting as you could easily flutter away all of your money very quickly.
  • Minesweeper can be played by pressing ALT+SHIFT+M from the Home screen. Press G to play GoMoKu (4 in a row).
  • I’m currently experimenting with Instapaper, which sends long articles from the internet to your Kindle, so they’re easier to read.

What’s Missing?

More games! Some text-adventures would be nice (lots of hacking in this area!).
I would love to hear from you if you have any similar Kindle experiences of reading PDFs.

* As an experiment, I e-mailed the CIFS book to my amazon kindle email which automatically converts it to Kindle formatting. The theory being that I can then resize the text and read it the normal way around. Unfortunately it loses the formatting of the columns and images, so it seems the “rotation method” is the best solution at the time of writing.

Hardcore Linux users will tell you that copy and paste is as simple as selecting a piece of text and middle clicking. And if you’re stuck with a two-button mouse or trackball, the usual trick is to click both left and right buttons simultaneously. This used to work out of the box on Ubuntu, but recent versions (since at least 11.04) do not have the middle button emulation.

What to do? – Install this cool little program:

sudo aptitude install gpointing-device-settings

Then run it and check the middle button emulation box. :-)

Having problems playing Counter Strike on 02 Broadband?

Symptoms include not being able to connect to a game, VAC security errors or getting disconnected shortly after joining. The problem isn’t related to your internet connection, but rather the free Thomson modem that comes with it:

Thomson Modem

Got one of these?

The Fix

  1. Click on the start button and run cmd.exe. If you are on Windows XP you may need to click on Start->Programs>Accessories->Command Prompt.
  2. This should bring up a black box. Type telnet 192.168.1.254 and hit return.
    1. If you are on Windows 7 and you get an error about telnet is not recognized as an internal or external command, then you need to enable telnet first.
    2. Go to Start -> Control Panel -> Program -> Turn Windows Features on or off, and check Telnet Client.
    3. Press OK.
    4. Repeat step 2.
  3. You have now logged into the router. Type :connection bindlist and hit enter. You should see something like this:
    Application  Proto Portrange   Flags
    LOOSE(UDP)   udp   69
    LOOSE(UDP)   udp   67
    GAME(UDP)    udp   27010-27011
    JABBER       tcp   15222
    JABBER       tcp   5222
    FTP          tcp   21
    IRC          tcp   6660-6669
    H323         tcp   1720
    ILS          tcp   1002
    ILS          tcp   389
    RTSP         tcp   554
    RAUDIO(PNA)  tcp   7070
    CU/SeeMe     udp   7648
    SIP          udp   5060        SIP_ALG:E RTP_predict_for_term_SIP_ALG:E
    IKE          udp   500
    ESP          esp   0
    IP6TO4       6to4  0
  4. Type :connection unbind application=GAME(UDP) port=27010-27011 and hit enter.
    1. If the Portrange shown above is different, then edit the unbind command to have the same value.
  5. Type :connection bindlist and hit enter again. The GAME(UDP) line should have gone, which means you have fixed the problem.
  6. Type exit and hit enter.
  7. Restart Steam.

Happy gaming :-)

Studying Java at University should give you enough grounding to get by in your day job, but can you really call yourself a Java programmer unless you know the language inside and out? In this series we will outline the lesser known features of how the language works, taken from the SCJP objectives. Mastering these will increase your understanding of the language, and possibly (no guarantees) elevate you to demi-god status in the workplace. If you are studying for the SCJP examination you may also find these examples to be useful revision.

Variable Names

Identifiers in Java can begin with a letter, underscore or $. The characters after the first one can include digits too. These are all valid variable declarations:

int myVar;
int $var;
int _var;
int _var2;
int $$$;

Normally you would stick to using the alphabet, with following words capitalised:

int myLongVariableName;

Beginning local variables with an underscore (_) is a common convention as well.

int _aLocalVariable;

Interface Constants

Given the following interface:

public interface ConstantInterface {
    int x = 2;
}

and an implementation of it

ConstantInterface impl = new ConstantInterface() {
   void test() {
      x = 2;
   }
};

This will not compile! The variable x is implicitly public static and final because it is declared in an interface. The code could be made more readable by capitalising the variable name, to show the intent that it is a constant. Alternatively, move the constant out of the interface as constant interfaces are rarely a good idea [1]

What do protected methods really mean?

Everyone knows that public methods can be called anywhere and that private methods can only be called within it’s own class. So what about protected methods? First, lets explain what no access modifier means:

package com.example.epiccode;
public class Ping {
   void myMethod() {
      System.out.println("fuzzy wuzzy was a bear");
   }
}

myMethod can be called from any class within the same package. i.e. any class that belongs to the package com.example.epiccode. This is because it has no (default) access modifier. If a class belonged to the package com.example.epiccode.winner it cannot call this method because it is in a different package (no exception made to sub-packages).

Protected methods follow exactly the same rules as default methods, except they also allow access to subclasses by inheritance only. This is a very subtle point as shown below.

package com.example.epiccode;
public class Ping {
   protected void myMethod() {
      System.out.println("I'm default yeh");
   }
}

We have changed myMethod to be protected. Now let’s subclass Ping.

package com.example.anotherpackage;
import com.example.epiccode.Ping;
public class Submarine extends Ping {
   void dive() {
     myMethod();
  }
}

This code is perfectly fine – dive can call myMethod because Submarine extends Ping (even though they are in different packages).

The following code will not compile:

package com.example.anotherpackage
import com.example.epiccode.Ping
public class Submarine2 extends Ping {
   void dive() {
     Ping p = new Ping();
     p.myMethod();
  }
}

We are not accessing myMethod through inheritance, instead we are creating a new instance of Ping and trying to call myMethod on it. This will not compile since Submarine is not in the same package as Ping. Funnily enough this subtlety is too much for Eclipse to handle:

eclipse error

The method is already protected, so the quick fix will not work.

References

[1] Effective Java 2nd Edition by Joshua Bloch – Item 19: Use interfaces only to define types.

Here’s a little script I wrote to look up words whilst reading a book or browsing the web. It uses the Aonaware web-service to get the definitions and prints them out to the console. And if you misspell a word it will offer some suggestions.

You will need to install the LWP::Simple and XML::XPath modules from CPAN to get it to work, but other than that it should be clean sailing.

If you have comments, bugs to moan about or feature requests then let me know :-)

Enums are Brittle

We all know Integer constants are brittle

Consider this example from StackOverflow today:-

Calendar date = Calendar.getInstance();
date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
        System.out.println("OK");

The questioner mistakenly thought that the java.util.Calendar set(int year, int month, int date) method followed a sensible human format for representing dates, but in fact the API makes use of zero based int constants to represent the month. The questioner was encouraged to avoid this pitfall by changing his code to date.set(2010, Calendar.MARCH, 7). This of course is better, but the root of the problem lies with the poorly designed Calendar API.

If java.util.Calendar class has been written post Java 5 then the set method could have been defined as set(int year, Month month, int date) where Month is an enum type:-

public eum Month {
JANUARY,
FEBRUARY,
MARCH,
...
}

This would prevent any ambiguity over whether the month parameter is zero or one based.

To change and to change for the better are two different things.

Enums may be preferable to int constants, but they are not as flexible as regular Java classes. You may well find that when you come to modify an enum which was written months ago, you need to refactor the whole thing into a regular class. This of course is time-consuming and you would have been better off designing a class from the start.

Below is an example enum representing a 2D direction on a grid. Direction takes two parameters, deltaX and deltaY which represent the offset of moving in that direction. Given that co-ordinate (0, 0) on the grid is located in the top left hand corner, moving NORTH will result in a negative change in deltaY, EAST will result in a positive change in deltaX and so forth.

enum Direction {
	NORTH(0, -1), NORTH_EAST(1, -1), EAST(1, 0),
        SOUTH_EAST(1, 1), SOUTH(0, 1), SOUTH_WEST(-1, 1),
        WEST(-1, 0), NORTH_WEST(-1, -1);
	private int deltaX;
	private int deltaY;
	Direction(int deltaX, int deltaY) {
		this.deltaX = deltaX;
		this.deltaY = deltaY;
	}
	public int deltaX() {
		return deltaX;
	}
	public int deltaY() {
		return deltaY;
	}
}

Direction feels like it should be an enum, as we only have eight possible directions to move in, allowing for diagonal moves. Furthermore this example demonstrates another advantage enums have over int constants – enums support methods. In fact, this enum almost appears to be a regular class, besides the enum declarations at the top.

We encounter a problem with enums when we want to add a method that returns the opposite direction. i.e. the opposite of NORTH is SOUTH, NORTH_WEST is SOUTH_EAST and so on. Here is the first technique.

enum Direction {
	NORTH(0, -1), NORTH_EAST(1, -1), EAST(1, 0),
        SOUTH_EAST(1, 1), SOUTH(0, 1), SOUTH_WEST(-1, 1),
	WEST(-1, 0), NORTH_WEST(-1, -1);
	private int deltaX;
	private int deltaY;
	Direction(int deltaX, int deltaY) {
		this.deltaX = deltaX;
		this.deltaY = deltaY;
	}
	public int deltaX() {
		return deltaX;
	}
	public int deltaY() {
		return deltaY;
	}
	public Direction getOpposite() {
		return new Direction(-deltaX, -deltaY);
	}
}

By simply negating the deltaX and deltaY values we get the opposite direction right? It doesn’t compile because we can’t invoke enum constructors directly, even from within the enum itself! Let’s try it another way: -

enum Direction {
	NORTH(0, -1, SOUTH), NORTH_EAST(1, -1, SOUTH_WEST),
        EAST(1, 0, WEST), SOUTH_EAST(1, 1, NORTH_WEST),
	SOUTH(0, 1, NORTH), SOUTH_WEST(-1, 1, NORTH_EAST),
        WEST(-1, 0, EAST), NORTH_WEST(-1, -1, SOUTH_EAST);
	private int deltaX;
	private int deltaY;
	private Direction opposite;
	Direction(int deltaX, int deltaY, Direction opposite) {
		this.deltaX = deltaX;
		this.deltaY = deltaY;
		this.opposite = opposite;
	}
	public int deltaX() {
		return deltaX;
	}
	public int deltaY() {
		return deltaY;
	}
	public Direction getOpposite() {
		return opposite;
	}
}

In the second technique we have hard-coded the opposite directions, passing them into the constructor. This doesn’t compiler either because you cannot refer to types before they are defined. e.g. SOUTH cannot be referenced in NORTH‘s constructor.

Finally we give up trying to find a work around with an enum and change the whole thing to be a regular class.

public class Direction {
	public static final Direction NORTH =
        new Direction(0, -1);
	public static final Direction NORTH_EAST =
        new Direction(1, -1);
	public static final Direction EAST =
        new Direction(1, 0);
	public static final Direction SOUTH_EAST =
        new Direction(1, 11);
	public static final Direction SOUTH =
        new Direction(0, 1);
	public static final Direction SOUTH_WEST =
        new Direction(-1, 1);
	public static final Direction WEST =
        new Direction(-1, 0);
	public static final Direction NORTH_NORTH =
        new Direction(-1, -1);
	private int deltaX;
	private int deltaY;
	private Direction(int deltaX, int deltaY) {
		this.deltaX = deltaX;
		this.deltaY = deltaY;
	}
	public int deltaX() {
		return deltaX;
	}
	public int deltaY() {
		return deltaY;
	}
	public Direction getOpposite() {
		return new Direction(-deltaX, -deltaY);
	}
}

The private constructor ensures that we cannot create any instances outside of the class. The eight public instances and the getOpposite() method provide the only means of access. Note that in this class we can write the getOpposite() method using the first technique.

In conclusion, enums may be an improvement over int constants, but are definitely less flexible than a regular class. If you do decide to create an enum, consider that it may outgrow itself, like Direction did. Creating a regular class from the start may be the better option. In some cases a class may be more verbose than an enum, but then Java is pretty verbose language anyway!

Since I started my new job as a Java Software Engineer, I’ve been doing some training in the form of reading Effective Java by Joshua Bloch. Today I came across the rather baffling method signature below: -

Public static <T extends Comparable<? Super T>> T max(List<? Extends T> list)

“OMG… What is that all about?” I thought at first glance. The description informs me that the method max takes a list of any comparable type and returns the object with the maximum value as defined by the implementation of the Comparable interface’s compareTo method.

So what’s with all the bloat? The answer is that generics are invariant rather than covariant in Java. For example List<String> is not a subclass of List<Object>. In order to make your generic methods as flexible as possible it is necessary to support the inheritance of parameter types, which can cause quite a headache. I think I’ve just about got my head round this example so I will do my best to explain it.

max is a method with modifiers public and static. Its return type is the generic type T.

Generic methods declare a type parameter list which goes in between the modifiers (public static) and the return type (T). The type parameter for max is  T extends Comparable<? Super T>>. This means that T is type that is comparable with itself or its super class.

To break this down, let’s consider the simpler parameter type T extends Comparable<T>>. In this example, T is the type that is comparable with itself only. Adding the bounded wildcard type <? Super T> allows T to be comparable with its super types as well. This is necessary if we apply T as a class that subclasses a class E that implements Comparable<E>. One example of this that the book gives is the java.util.concurrent.ScheduledFuture interface which is a sub-interface of java.util.concurrentDelayed. Delayed extends Comparable<Delayed> whereas ScheduledFuture does not extend the Comparable interface directly.

The final brain teaser is the sole parameter list of type List<? Extends T>. This means that list can be a List of any type that is a subclass of T (remember everything is a subclass of itself).

Phew, I hope this made some sense. Please appreciate I’m hardly an expert in this field, so if you spot an error in my description then let me know!

Aptitude Woes

I’ve just spent the last hour battling with Ubuntu to get it to upgrade. My problem stems from installing the World of Goo demo and then removing it (it never had a hope in hell of working on my ATI graphics card). Now every time I try to install a new package through aptitude, or try to perform an upgrade I receive

files list file for package `worldofgoodemo' contains empty filename

I had to remove

/var/lib/dpkg/worldofgoodemo.list

to fix it. Not the most elegant solution, but at least I can install things again.

Last year I attended a talk by Richard Stallman in Manchester, UK where he explained the motivations behind Free Software as well as its history and what we could do to support the cause. Whilst I enjoyed the talk and agreed with most of his views, I found myself hooked on obvious marketing anomalies.

First of all, there is the name – FREE SOFTWARE. Most people in the audience assumed (even after Stallman reiterated the point on several occasions) that it’s all about not paying a penny, when of course the name refers to the FREEDOMS to run, modify, redistribute and improve the program. Surly, calling the movement something like FREEDOM SOFTWARE or LIBRE SOFTWARE (See Gratis versus Libre) would cause less confusion?

A further negative consequence of the confusion caused by the name FREE SOFTWARE comes about as a result of the psychological weakness of human beings to perceive quality in terms of price. When I’ve tried to explain Free Software to the casual computer users/business people (not programmers), their immediate impressions of the name is that the software is free (gratis) AND THEREFORE there must be something wrong with it. Like the GNU OS is some cheap knock-off of MS Windows! My point is that the name FREE SOFTWARE creates unnecessary hurdles to climb when we are trying to pitch the benefits of Free Software to a wider audience.

Now I’m done ranting, I will balance the karma by advertising a Manchester Free Software event this evening – Dan Lynch, Audio Production with Free Software – 21st July. I hope to see you there!

Older Posts »

Follow

Get every new post delivered to your Inbox.