August 24, 2011

Small Java Note

Filed under: code,java — Tags: , — Max @ 12:00 pm

When running a program with a long loop it can be incredibly useful to have some sort of index counter or process indicator. Even if just as an assurance that the program hasn’t got stuck in an unending loop. Using something like:
new Thread(new Runnable() {
  public void run() {
    int requiredWidth = Integer.toString([EndIndex]).length();
    while(runningDescriptors){
      String current = String.format("%0"+requiredWidth+"d", [Index]);
      System.out.print(current+"/"+[EndIndex]+"\r");
      try{Thread.sleep(1000);}catch(InterruptedException ex){}
    }
  }
}).start();

The \r in the print command moves the caret back to the start of the line so it overwrites the previous count. The format pads the current index with the required number of zeroes so the overwrite is always of the same number of total characters.

It’s a pretty simple piece of code but it can make life just that little bit easier.

June 12, 2011

Philadelphia state penitentiary

Filed under: photos — Tags: , , , — Max @ 3:56 pm

 

image

image

 

image

Is awesome…

April 1, 2011

Simple Java Argument Reader

Filed under: code,java — Tags: , , , — Max @ 3:50 pm

For a lot of simple java applications using the ability to pass arguments in at the program start just makes a lot more sense than having a complicated input setup.

However the argument still needs to be passed and if there are multiple options this can be a pain, code like an ArgsReader class help alleviate the stress.

It’s used in the fashion displayed below, where the statics are just a set of public strings used as keys to identify the argument type.

public static void main(String[] args){
    ArgsReader reader = new ArgsReader();
    reader.addFlag("-h",        Statics.HELP, "Prints argument descriptions");
    reader.addFlag("--help",    Statics.HELP);
    reader.addProperty("-i",    Statics.INPUT, "An input value");
    reader.addFlag("-l",        Statics.FLAG, "A flag to change some response");
    reader.loadArgs(args);
    if(reader.hasFlag(Statics.HELP)){
        System.out.println(reader.helpText());
        System.exit(0);
    }
    if(!reader.hasProperty(Statics.INPUT)){
        System.out.println("No input");
        System.exit(1);
    }
    String input = reader.getString(Statics.INPUT);
    if(reader.hasFlag(Statics.FLAG)){
        //do something with input
    }else{
        //do something different with input
    }
}

Running this with the line

java [java class with main] -i "Some input" -l

Will use the input value of "Some Input" with the flag set as true

The full code listing of the ArgsReader class is:

(more…)

March 14, 2011

Clean Query

Filed under: code,php,web — Tags: , , , — Max @ 4:19 pm

In PhP the process for performing a mysql query can be torturous, making sure things are the correct type (numbers are actually numbers) and everything’s escaped properly etc. I got very very bored of repeating this sort of work so made a simple class with a very handy query function that I will now share with you1.

<?php
class Database {
    protected $password, $username, $server, $db_name, $connection, $debug;
    public function __construct($server, $db_name, $username, $password) {
        $this->server = $server;
        $this->db_name = $db_name;
        $this->username = $username;
        $this->password= $password;
        $this->debug = false;
    }
    public function setDebug($debug) {
        $this->debug = $debug;
    }
    public function getServer() {
        return $this->server;
    }
    public function getUsername() {
        return $this->username;
    }
    public function getDBName() {
        return $this->db_name;
    }
    public function getConnection() {
        return $this->connection;
    }
    
    public function connect() {
        $this->connection= mysql_connect($this->server, $this->username,$this->password)
            or die('Could not connect: ' . mysql_error());
        mysql_select_db($this->db_name, $this->connection);
    }
    
    public function close() {
        if($this->connection) mysql_close($this->connection);
    }
    
    
    public function lastId() {
        return mysql_insert_id($this->connection);
    }
    
    public function __destruct() {
        $this->close();
    }
    public function free($result) {
        mysql_free_result($result);
    }
    
    /**
     * Used like sprintf to run mysql queries,
     * if the result is a single row it returns that,
     * otherwise it returns an array
     * %s for strings, %% for a percentage, %d for digits (integer)
     * %f for a float and %i to make no change to argument (ignore)
     * @param String sql query to run
     * @param [] arguments to pass to query
     */

    public static $queryargs;
    public function query($sql) {
        $sql = trim($sql);
        
        Database::$queryargs = func_get_args();
        //Remove the first argument
        array_shift(Database::$queryargs);
        $query = preg_replace_callback("/%./", create_function('$matches', '
            $type = $matches[0];
            switch($type){
            case "%s":
            return mysql_real_escape_string(array_shift(Database::$queryargs));
            break;
            case "%i":
            return array_shift(Database::$queryargs);
            break;
            case "%d":
            return intval(array_shift(Database::$queryargs),10);
            break;
            case "%f":
            return floatval(array_shift(Database::$queryargs));
            break;
            case "%%":
            return "%";
            break;
            default:
            return "";
            }'
), $sql);
        Database::$queryargs = null;
        $result = mysql_query($query, $this->connection)
            or die(($this->debug?$query:"Query Failed")."<hr/>".mysql_error());
        
        preg_match("/^\W*(\w*)\W/", $sql, $matches);
        $type = $matches[1];
        
        switch($type) {
            case "SELECT":
            case "SHOW":
            case "DESCRIBE":
            case "EXPLAIN":
                $objects = array();
                while($obj = mysql_fetch_object($result)) {
                    $objects[] = $obj;
                }
                return $objects;
                break;
            default:
                return ($result);
        }
        $this->free($result);
    }

}
?>

[1] You lucky lucky people.

March 7, 2011

Abusing .htaccess

Filed under: code,web — Tags: , , — Max @ 4:48 pm

My name is Max, and I abuse .htaccess.

The site to which this blog is attached uses .htaccess as part of its process and it serves 2 major purposes:

  1. I use it to mask the fact that it runs on PhP 1
  2. Passes all requests to a single script which, based on the url, feeds the correct page

Why bother you ask? Well so I can use my own templating system and frankly because I’m a computer scientist and am really bad at not re-inventing the wheel.

So that I have a backup and some explanation of what I’ve done next time I look at it and swear at my incomprehensible code the following is a transcript of the major sections:

ErrorDocument 401 /err/401.html
ErrorDocument 403 /err/403.html
ErrorDocument 404 /err/404.html
ErrorDocument 500 /err/500.html

Basically where to route the user on a given error, not actually used as it should be entirely handled by the site-engine.

Options +FollowSymlinks
RewriteEngine on

Turns on the ability to forward the user to another location

RewriteCond %{http_host} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]

Makes www. unaccessible, this is just for some basic consistency across the site. The R=301 makes it an actual http redirect, the NC tells it to ignore case and the L tells it that this is the last command and the rest of the file should be ignored.

<FilesMatch "\.htaccess$">
Order deny,allow
Deny from all
Satisfy all
</FilesMatch>

This stops the .htaccess file itself from being accessible.

RewriteCond %{http_host} !^3void.com$ [NC]
RewriteRule ^(.*)$ $1 [NC,L]

This is to allow subdomains to be used normally without passing through the site-engine.

RewriteCond %{request_uri} ^\/js\/.*$ [NC]
RewriteRule ^(.*)$ $1 [NC,L]

This speeds up the javascript access by not sending it to the script, actually required for tiny mce and possibly other external libraries to work properly.

RewriteCond %{HTTP:RedirectedToGenPage} !^true$ [NC]
RewriteRule ^[PAGE-GENERATOR-SCRIPT].php(.*)$ / [F,NC,L]

Checks to see if we’ve already been sent to the [PAGE-GENERATOR-SCRIPT] and if we have we can stop processing and let it run as normal.

RequestHeader set RedirectedToGenPage "true"

Sets a header on the request saying we’ve now been sent to the [PAGE-GENERATOR-SCRIPT]. This is important because I don’t want the script to be accessible directly so people have to use the site as a normal site and can’t directly got to [PAGE-GENERATOR-SCRIPT].php?uri=[WHEREVER].

RewriteCond %{request_uri} !^.*[PAGE-GENERATOR-SCRIPT]\.php.*$ [NC,OR]
RewriteCond %{request_uri} ^\$ [NC]
RewriteCond %{QUERY_STRING} ^(.*)$ [NC]
RewriteRule ^(.*)$ /[PAGE-GENERATOR-SCRIPT].php?uri=$1&%1 [NC,L]

Performs the actual redirect, this time it’s not a proper http redirect, we just send the current request to [PAGE-GENERATOR-SCRIPT].php.

[1] Not sure why I do this.

March 5, 2011

Mountains

Filed under: photos — Tags: — Max @ 1:51 pm

Some pictures taken on my phone, posted without comment:

image

image

image

image

Posted from WordPress for Android

February 24, 2011

Trains

Filed under: Uncategorized — Tags: , — Max @ 7:52 pm

Strangely some of my best thinking is done on trains. Today, for example, I re-wrote sections of a thesis chapter; worked out a new classification nomenclature; solved some maths puzzles; completed a game of solitaire; and I also realised just how dull a journey can be. Seriously I’m relatively sure my brain made a break for the sweet release of the reaper, that or I have an inordinate amount of wax attempting to leave my ear. It’s okay though, I used my little finger to ram it back into my hearing hole, disaster averted… This time.