Search Results: "hle"

27 June 2006

David Pashley: Intelligently Designed

Some one on a mailing list pointed out this cartoon and thought I'd share it with people: cartoon

23 June 2006

David Pashley: Where Do You Want To Go?

On the way home, someone asked me where I wanted to go when I died. My initial reaction was Tahiti. After thinking about it, I'd quite like to see New Zealand.

18 June 2006

David Pashley: Markable InputStreams

Java has a nice IO subsystem. In particular, it has been designed such that input streams can optionally support a feature where a programmer can mark a position in the stream and at a later stage return to that point to read the data again. Programmers can check for this support by calling InputStream.markSupported(). Unfortunately I've had the need for this support, but I haven't managed to find a stream which supports this. Not even ByteArrayInputStream sees to support it. Fortunately it's fairly trivial to wrap an InputStream in another class which will add this support. Here is my quick adaptor, which seems to work for most cases.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class MarkableInputStream extends InputStream  
    private InputStream inputstream;
    private int maxpos = 0;
    private int curpos = 0;
    private int mark = 0;
    private ArrayList<Integer> buffer = new ArrayList<Integer>();
    public MarkableInputStream(InputStream is)  
        inputstream = is;
     
    @Override
    public int read() throws IOException  
        int data;
        if(curpos == maxpos)  
            data = inputstream.read();
            buffer.add(data); maxpos++;curpos++;
          else  
            data = buffer.get(curpos++);
         
        return data;
     
    @Override
    public synchronized void mark(int readlimit)  
        mark = curpos;
     
    @Override
    public boolean markSupported()  
        return true;
     
    @Override
    public synchronized void reset() throws IOException  
        curpos = mark;
     
 
You can use it like:
if (!istream.markSupported())  
   istream = new MarkableInputStream(istream);
 
This could probably be improved on, most notably by not using an ArrayList. I'm not sure what performance penalty that adds. It should be possible to use a normal array as the readlimit parameter to mark() says how many bytes the stream should record before throwing old data away in favour of new input. The class above will record all data from the start of the stream, so could result in a significant amount of memory usage. Hope you find it useful.

David Pashley: New Delivery

For the last few weeks, we've had a couple of pigeons nesting in one corner of the small triangular piece of glass I delude myself into calling a garden. Yesterday the egg they've been incubating hatched and we now have a small yellow ball of fluff my girlfriend has named Armstrong. Armstrong
and Mother/Father

17 June 2006

David Pashley: Invalid Characters in Encoding with JAVA

Imagine you've got some text you've been told is ASCII and you've told java that it's ASCII using:
Reader reader = new InputStreamReader(inputstream, "ASCII");
Imagine your surprise when it happily reads in non-ascii values, say UTF-8 or ISO8859-1, and converts them to a random character.
import java.io.*;
public class Example1  
   public static void main(String[] args)  
      try 
         FileInputStream is = new FileInputStream(args[0]);
         BufferedReader reader 
            = new BufferedReader(new InputStreamReader(is, args[1]));
         String line;
         while ((line = reader.readLine()) != null)  
            System.out.println(line);
          
        catch (Exception e)  
         System.out.println(e);
       
    
 
beebo david% java Example1 utf8file.txt ascii
I t rn ti n liz ti n
beebo david% java Example1 utf8file.txt utf8
I t rn ti n liz ti n
So, I hear you ask, how do you get Java to be strict about the conversion. Well, answer is to lookup a Charset object, ask it for a CharsetDecoder object and then set the onMalformedInput option to CodingErrorAction.REPORT. The resulting code is:
import java.io.*;
import java.nio.charset.*;
public class Example2  
   public static void main(String[] args)  
      try 
         FileInputStream is = new FileInputStream(args[0]);
         Charset charset = Charset.forName(args[1]);
         CharsetDecoder csd = charset.newDecoder();
         csd.onMalformedInput(CodingErrorAction.REPORT);
         BufferedReader reader 
            = new BufferedReader(new InputStreamReader(is, csd));
         String line;
         while ((line = reader.readLine()) != null)  
            System.out.println(line);
          
        catch (Exception e)  
         System.out.println(e);
       
    
 
This time when we run it,we get:
beebo david% java Example2 utf8file.txt ascii
java.nio.charset.MalformedInputException: Input length = 1
beebo david% java Example2 utf8file.txt utf8
I t rn ti n liz ti n
On a slightly related note, if anyone knows how to get Java to decode UTF32, VISCII, TCVN-5712, KOI8-U or KOI8-T, I would love to know.

11 June 2006

Florian Ragwitz: Class::DBI is dead

David, you wrote about Class::DBI performance. Even without benchmarking you could have found out, that Class::DBI is quite slow. Fortunately there are some alternative object-relational mappers available in the perl universe. The best ones I found so far are Rose::DB::Object and DBIx::Class. I took a closer look at both and would like to share my experience. As this shows, RDBO is faster than DBIC in most of the case. The generated SQL doesn't differ too much and therefor it must be the perl side of things that makes the difference. Matt S Trout <dbix-class@trout.me.uk> says:
  However, RDBO achieves its perl speed by aggressive inlining of stuff
  etc. - for example the main object retrieval function in RDBO's manager
  class is >3000 lines in a single sub. DBIC values extensibility over a
  few extra sub calls, so methods are much more broken out and there are
  many more ways to hook into the DBIC execution process to extend.
Also its idea of resultsets is something I really love. Here's a small example to illustrate that:
  my $user_rs = $schema->resultset('User')->search(  registered => 1  );
  $user_rs    = $user_rs->search(
		    comment.title => 'Foo'  ,
		   
		  	join     =>   'article' => 'comment'  ,
			order_by => 'user.name',
		   ,
  );
  # no sql executed yet.
  # now you can use your resultset as an iterator or query a list of User
  # objects from it or ..
  while (my $user = $user_rs->next)  
	  ...
   
  # or
  my $count = $user_rs->count;
Using these resultset makes it extremely easy to built up queries piece by piece and to work together well with, for example, a templating system. You don't need to fetch all row-objects and give them to your template. You can just pass the iterator to the template library. There's a lot more to say about this two object-relational mappers (for example RDBO supports prefetching of multiple one-to-many at once, which DBIC doesn't), but maybe you just should take a look yourself. I personally prefer DBIx::Class for its vast extensibility.

David Pashley: Class::DBI performance

Class::DBI is a very nice database abstraction layer for perl. It allows you to define your tables and columns and it magically provides you with classes with accessors/mutators for those columns. With something like Class::DBI::Pg, you don't even need to tell it your columns; it asls the database on startup. It's all very cool mojo and massively decreases the development time on anything database related in perl. Unfortunately, as far as I can tell, it has a massive performance problem in its design. One of the features of Class::DBI is lazy population of data. It won't fetch data from the database until you try to use one of the accessors. This isn't normally a problem, except with retrieve_all(). Basically this function returns a list of objects for every row in your table. Unfortunately, due to the lazy loading of data, retrieve_all() calls SELECT id FROM table; and then every time you use an object it calls SELECT * FROM table WHERE id = n;. For a small table, this isn't too bad, but for a large table, it's a killer. I did a little benchmark today to see just how much slower it is over plain DBI. I wrote two functions which iterate over a table, assigning one value to a function (forcing Class::DBI to fetch the data). The table in question contains 635 rows. The code I used was:
use strict;
use warnings;
use Benchmark qw(:all) ;
use Foo;
use DBI;
sub class_dbi  
   for my $foo (Foo->retrieve_all())  
      my $bar = $foo->bar;
    
 
sub dbi  
   my $dbh = DBI->connect("dbi:Pg:dbname=$db;host=$host",$user, $passwd);
   my $sth = $dbh->prepare("SELECT * FROM foos;");
   $sth->execute();
   while(my $row = $sth->fetchrow_hashref())  
      my $bar = $row-> bar ;
    
 
cmpthese(100,  
      'Class::DBI' => 'class_dbi();',
      'DBI' => 'dbi();',
    );
The results:
brick david% perl benchmark.pl
           s/iter Class::DBI        DBI
Class::DBI   10.3         --       -97%
DBI         0.351      2845%         --
Class::DBI is more than 28 times slower than using DBI directly. I'm hoping that someone will now tell me "Oh you just do blah", otherwise I'm going to have to rewrite some of my code. One thing to learn from this is that reduction in development time can often cost you more in other areas, and it's often runtime performance. Update: It appears that the bug is that Class::DBI::Pg does't set the Essential list of columns, so Class::DBI uses the primary column. you can fix this by adding the following to your database modules:
__PACKAGE__->columns(Essential => __PACKAGE__->columns);
Remember you'll need to do that for each of your modules; you won't be able to do it in your superclass, as you won't have discovered your columns yet. This has increased performance, but not massively. New timings (with the addition of using Class::DBI through an iterator):
              s/iter Class::DBI it    Class::DBI           DBI
Class::DBI it   6.35            --           -2%          -94%
Class::DBI      6.23            2%            --          -94%
DBI            0.350         1714%         1680%            --
Update 2: It appears that further speedgains can be made by not using Class::DBI::Plugin::DateTime::Pg to convert the three timestamp columns in my table into DateTime objects.:
              s/iter Class::DBI it    Class::DBI           DBI
Class::DBI it   1.26            --          -11%          -72%
Class::DBI      1.12           12%            --          -69%
DBI            0.350          260%          220%            --

7 June 2006

David Pashley: Converting Epoch Time values To Timestamps

Just a quick one. If you've ever created a table using the number of seconds since 1970 and realised, after populating it with data, that you really need it in a TIMESTAMP type? If so, you can quickly convert it using this SQL:
ALTER TABLE entries 
   ALTER COLUMN created TYPE TIMESTAMP WITH TIME ZONE
      USING TIMESTAMP WITH TIME ZONE 'epoch' + created *interval '1 second';
With thanks to the PostgreSQL manual for saving me hours working out how to do this.

David Pashley: Oracle 10.2.0.1 Instant Client hanging?

Does your Oracle client hang when connecting? Are you using Oracle 10.2.0.1? Do you get the following if you strace the process?
gettimeofday( 1129717666, 622797 , NULL) = 0
access("/etc/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
access("./network/admin/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
access("/etc/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
access("./network/admin/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
fcntl64(155815832, F_SETFD, FD_CLOEXEC) = -1 EBADF (Bad file descriptor)
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
.
.
.
Has your client been up for more that 180 days? Well done; you've just come across the same bug that has bitten two of our customers in the last week. Back in the days of Oracle 8, there was a fairly imfamous bug in the Oracle client where new connections would fail if the client had been up for 248 days or more. This got fixed, and wasn't a problem with Oracle 9i at all. Now Oracle have managed to introduce a similar bug in 10.2.0.1, although in my experience the number of days appears to be shorter (180+). Thankfully, this has been fixed in the 10.2.0.2 Instant Client. More information can be found on forums.oracle.com and www.redhat.com.

2 June 2006

Adam Rosi-Kessel: Family News

I’ve been blogging a bit about my family lately — this entry about my brother Jonah’s band and this entry about my wife’s blog, so I didn’t want to leave out my youngest brother, Andrew. He has gained some renown as a tennis star at Macalester College. Men’s tennis gets help from a ‘Trainwreck’ perhaps captures it best:
Picture this: nervous first-year, short shorts, longer t-shirt, brown dress shoes, newly broken glasses taped together with white sports tape. He begins his first varsity tennis practice, he is excited. So excited in fact that he tips over the ball hopper while doing warm-ups, spilling tennis balls all over the court. That’s when they started calling me ‘Trainwreck,’ coach wanted to call me ‘Shoes,’ but the team agreed on Trainwreck,. Andrew ‘Trainwreck’ Kessel ‘07 said.
See also Athlete of the Week (scroll down to “Week 29”) and Cobbers Beat Scots 7-2 in Moorhead . I never even played intramural sports in college, so I can only appreciate Andrew’s success vicariously. Also, I’m now hosting a website for Jonah’s nascent photography business, Kessel Imaging. (Kids these days, they want to do everything with Flash! In my day, we hand-coded HTML and CSS.)

Meike Reichle: Cool sysad trick #3625

When moving your MX to another server, remember to also change your MUA's settings to query the new server instead of the old one.

Should you have sent mail to my alphascorpii.net account last month and not received an answer, this is why. I finally noticed now and am currently in the process of answering these mails. And there I was, wondering why there is so little mail to the shiny new address ... Hngh!

1 June 2006

David Pashley: Tidying Up

A few hours ago I got stressed about the lack of leg room under my desk and ended up spending the next few tidying and moving all of my computers to under the next desk. I also made the mistake of starting to remove keys from my keyboard to clean something sticky and found myself surrounded by keys and a keyless keyboard. It's now nice and shiny, which is more than can be said for the rest of the flat, which is now overrun with all the crap that was around my desk. Another thing that could do with a tidy up is Eddie, my Java liberal feed parsing library. After the initial coding sprint, I've had time to sit back and look at the design of the library and clean up any thing that sticks out. As mentioned in a previous entry, one of the things that has bothered me is that when ever you need to call an object method, you need to be certain that the object is not null. The means you end up with code like:
if (string != null && strong.equals("string"))  
This quickly becomes tiresome and the test for null distracts from the meaning of the code. Fortunately I was reminded of an improvement for string objects. Ideally, we should all be writing comparison conditionals like rvalue == lvalue. (an rvalue mostly is an expresion you can't assign to). The most common rvalue is a literal value like a string constant. The advantage of getting into the habit of writing code like this is that you'll discover at compile time when you accidentally write = rather than ==. Because you can't assign to an rvalue, the compiler will complain. What makes this interesting from a java string point of view is that you can call methods on string literals. Comparing a variable to a string literal, rather than calling .equals() on a variable is that the string literal is not going to be null, so you can remove the test for null and simplify the code:
if("string".equals(string))  
I know it's not everyone's cup of tea, but I prefer it to testing for null every time I look at a string. The other thing is that I've been reading Hardcore Java by Robert Simmons at work. Considering I've only got a few pages in so far. I've received a surprisingly large number of ideas to improve my code. The one that sticks in my head is using assert for doing post and pre conditions on your functions. Using asserts have number of advantages over throwing exceptions, including the fact they get optimised away when you do a production release. In Eddie, during a <feed> element I determine the version of Atom that we are parsing. This had a number of nested if/else if/else blocks. At the end of the function, I wanted to make sure I had set the version string to something, so had the following code:
if (!this.feed.has("format"))  
   throw new SAXParseException("Failed to detect Atom format", this.locator);
 
However, using assertions I can write this as
assert(this.feed.has("format")) : "Failed to detect Atom format";
I highly recommend the Hardcore java book if you want to improve your java programming. It includes sections on the new features of Java 1.5 and using collections. I've made a couple of other cleanups including going through member variable access specifiers to make sure they are right and making several public methods and variables and making them priavte. I also have a couple of ideas about refactoring some of the code to clean it up. Redesigning and refactoring code is almost more fun than writing it in the first place. You get to be in competition with yourself, challenging yourself to write better code and end up with cleaner code in the process. A couple of things I want to do in the near future is use a profiler and code coverage tools. If anyone has recommendations for either of these tools that integrates nicely with eclipse, I'd love to know.

David Pashley: Join Map Ord Split

Just when you thought Perl couldn't get more unreadable, someone[0] comes up with something like this:
print join ", ", map ord, split //, $foo;
This mess of perl might be easier to understand if I put the brackets in:
print join (", ", map( ord, split( //, $foo)));
What this does is split $foo into a list of characters. It then uses map to run ord() on each item in the list to return a new list containing the numeric character values. We then join these again with ", " to make the output easier to read.
david% perl -e 'print join ", ", map ord, split //, "word";'
119, 111, 114, 100
The map function is familiar to functional programmers and is very powerful, but beware it can reduce the clarity of your code. [0] Me

31 May 2006

David Pashley: Init(1) Causing zombies

Had an interesting problem today with one of our servers at work. First thing I noticed was yesterday that an upgrade of Apache2 didn't complete properly because /etc/init.d/apache2 stop didn't return. Killing it and starting apache allowed the upgrade to finish. I noticed there was a zombie process but didn't think too much off it. Then this morning got an email from the MD saying that various internal services websites were down (webmail, wiki etc). My manager noticed that it was due to logrotate hanging, again because restarting apache had hung. Looking at the server I noticed a few more zombie processes. One thing I'd noticed was that all these processes had reparented themselves under init and a quick web search later confirmed that init(1) should be reaping these processes. I thought maybe restarting init would clear the zombies. I tried running telinit q to reread the config file, but that returned an error message about timing out on /dev/initctl named pipe. I checked that file existed and everything looked fine. The next thing I checked was the other end of the named pipe by running lsof -p 1. This showed that init had /dev/console rather than /dev/initctl as fd 0. I tried running kill -SIGHUP 1, but that didn't do anything. Then I tried kill -SIGUSR1 1, but that didn't do anything either. I checked the console, but there wasn't enough scrollback to see the system booting and decided to schedule a reboot for this evening. Rebooting the server presented me with an interesting challenge. Normally the shutdown command signals to init to change to runlevel 0 or 6 to shutdown or reboot using /dev/initctl. Of course init wasn't listening on this file, so that was out. Sending it an SIGINT signal (the same signal init gets on ctrl-alt-delete) had no response. Obviously telinit 0 wasn't going to work either. I decided to start shutting services down manually with the help of Brett Parker. The idea was to stop all non-essential services, unexporting nfs exports, remounting disks read-only and then either using sysrq or a hardware reset. Unfortunately someone accidentally ran /etc/init.d/halt stop, hanging the server, but he is suffering from a bad cold today so I forgive him. The server restarted without a hitch (thank god for ext3) and running lsof -p 1 showed init having /dev/initctl open. I don't know what happened to init the last reboot on Monday, but a reboot seemed to fix it. Odd bug, but thankfully it was a nice simple fix. I could have spent the evening debugged init. :)

David Pashley: Laptop Harddisk Failure

I'm currently mourning the loss of my laptop's hard disk. I don't think there was massive amounts of data on there that I needed, but it's still upsetting. Looks like I'll have to buy a new 2.5" drive. At least it gives me a reason to reinstall Debian. Update: The bad news is that it is actually a 1.8" drive, which means I need to spend 93GBP including tax and postage for a new drive. Should get it by Friday. The good news is that having left the laptop off during the day, I managed to get the laptop booting and am not rsyncing the data off as fast as I can. Shame about the money, but at least I haven't lost much in the way of data.

David Pashley: Eddie RSS and Atom Feed Parser

I'd like to announce the initial release of Eddie, a feed parser library written in Java. It's taken me over 100 hours, but it now correctly parses 90% of the FeedParser unit tests, including all the rss and atom tests. It's GPLed, with an exception allowing you to use it in any open sourced program. Get it at my website. Need to add documentation and character set and encoding support. Also need to separate the testing infrastructure from the rest of the code. This is the first time I've done any java programming in anger, and I have to say I'm surprised to discover I quite like it. In many ways it seems a very quick language to program in. It seems almost like programming in a scripting language, but stronger typed. This is probably due to not having to worry about memory management. Certainly I don't think I could have written this quite so quickly in C++. Having said that, there are a couple things that I don't like about Java. Everything is a pointer. This is useful at times, but it means that every time you want to call a method on an object you have to test whether it is null or you run the risk of getting the dreaded NullPointerException. Java also doesn't have keywords for and, or and not. I know not everyone likes these, but I keep finding myself trying to use them. I'm sure there are other things I hated, but I can't remember them now. I think I'll end up doing more java programming in the future.

28 May 2006

Meike Reichle: Lost my mobile phone

I case you wrote me a text message or called me on my mobile phone lately and never got a response, here's why: It's gone.
I lost it some when between arriving at FRA airport on Monday evening and looking for it before going to uni on Wednesday morning. I already checked with the German Rail's lost and found service which - unsurprisingly - was little helpful. Basically they now have all my personal info, a detailed description of my mobile phone (Siemens C55, blue, battery empty, sim card pin-protected, transparent sticky tape on back that holds the battery cover) and told me to call back later since they haven't found anything yet. I have not yet given up completely, but for the moment please don't try to call or text me on my mobile phone. Use my home number or (much better) Email. The phone was nothing special, but I am still pretty unhappy about its loss, since I don't have the money to get a new one (this one was a gift, yet another reason why losing it sucks bigtime!) and it holds a few numbers that I don't have anywhere else. Oh well, just not my week. At all.

Meike Reichle: Still jet lagged

Although I've back from DebConf6 for almost a week now, I somehow still suffer from the jet lag. I am rather surprised by this since I usually don't have too many problems with changing my sleeping times and also the jet lag when going from Germany to Mexico was practically neglectable. However, this one is a real sucker! By now my sleep times are pretty much erratic, I have an almost constant headache and my stomach gives me trouble after each meal. Surprisingly I didn't have any problems with such stuff when I was in Mexico! I was neither sick nor heat struck or dehydrated. In fact I didn't even have so much as a sunburn. But ever since I got back, life has been pretty yargh. Why am I posting this?

26 May 2006

David Pashley: Makes you look big *and* clever

To the anonymous Texan that thought it would be a good idea to point out a Perl module in response to my date parsing class in Java: I'm well aware of date parsing modules in other languages. In fact I've used them for similar tasks. But the post wasn't asking "How do I parse dates in Perl?" It was giving some code that some people might find useful. Commenting with "man Date::Parse" doesn't make you look clever; it just makes you look like a twat and the kind of person people are relucant to invite to parties. You may be a geek and you may know stuff, but that doesn't mean you have to try to look clever, because you will invariably fail. </rant> Oh and Erich, I've got some more date formats I want to add support for, so I'll add german dates and post the updated code. :)

25 May 2006

David Pashley: Pathological Date Parser in Java

I've recently had cause to parse some date values in Java. As a result I've produced a class which can manage to parse an awful lot of date formats. I thought I'd better document it in case someone found it useful. Certainly there doesn't appear to be anything elsewhere which shows you how to parse lots of formats. I have found the order of date_formats to be very brittle, so I don't recommend you change it without an awful lot of test cases. Anyway, without further to do, I present to you, the Pathological Date Parser for Java
// Copyright 2006 David Pashley <david@davidpashley.com>
// Licensed under the GPL version 2
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class Date  
    private Calendar date;
    static String[] date_formats =  
            "yyyy-MM-dd'T'kk:mm:ss'Z'",        // ISO
            "yyyy-MM-dd'T'kk:mm:ssz",          // ISO
            "yyyy-MM-dd'T'kk:mm:ss",           // ISO
            "EEE, d MMM yy kk:mm:ss z",        // RFC822
            "EEE, d MMM yyyy kk:mm:ss z",      // RFC2882
            "EEE MMM  d kk:mm:ss zzz yyyy",    // ASC
            "EEE, dd MMMM yyyy kk:mm:ss",   //Disney Mon, 26 January 2004 16:31:00 ET
            "-yy-MM",
            "-yyMM",
            "yy-MM-dd",
            "yyyy-MM-dd",
            "yyyy-MM",
            "yyyy-D",
            "-yyMM",
            "yyyyMMdd",
            "yyMMdd",
            "yyyy", 
            "yyD"
    
     ;
    public Date(String d)  
        SimpleDateFormat formatter = new SimpleDateFormat();
        d = d.replaceAll("([-+]\\d\\d:\\d\\d)", "GMT$1"); // Correct W3C times
        d = d.replaceAll(" ([ACEMP])T$", " $1ST"); // Correct Disney timezones
        for (int i = 0; i < date_formats.length; i++)  
           try  
              formatter.applyPattern(date_formats[i]);
              formatter.parse(d);
              date = formatter.getCalendar();
              break;
             catch(Exception e)  
              // Oh well. We tried
            
         
        
     
 
The only date formats I can't get it to parse are <4-digit year>-<day of year> and <2digit year><day of year> (e.g. 2003-335 and 03335 for 2003-12-01). If you can add support for those and other date formats I'll gladly take patches.

Next.

Previous.