[icon] Makes you like your eggs on the Jersey side
View:Recent Entries.
View:Archive.
View:Friends.
View:User Info.
View:Website (Clowns Will Eat You).
View:Poly Geek Relationship Disclosure Form.
You're looking at the latest 20 entries.
Missed some entries? Then simply jump back 20 entries

Tags:, ,
Subject:[CODE] Nifty Perl tricks: calling a superclass method dynamically
Time:11:42 am
I was going to have to write a bunch of copy/pasted methods for this work thing, and I didn't wanna. With this, I can do it somewhat minimally.

code behind the cut )

ETA: Even more minimally! I can define a bunch of methods from a qw//.
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[CODE] There's a clever answer to this
Time:05:45 pm
I want to break a set of 1000 or more array elements into smaller arrays of up to 1000 elements each. There's some clever way to do this in a for loop with a modulus operator, but I just can't manage to figure it out. So here's how I'm doing it, in Perl:


# @array is the array I am passed, assume it has more than 999 elements. 
my $count = scalar @array; # number of array elements I got
my $size = 1000; # maximum size of subarray
my @subarrays;
for (0..($count/$size - 1)) {
  my $start = $_ * $size;
  my $end = $start + $size - 1;
  push @subarrays, [@array[($start..$end)]];
}
my $start = $count/1000;
my $end = $count;
push @subarrays, [@array[($start..$end)]];



I'm sure one of you can post a more elegant solution. :)
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , ,
Subject:[CODE] bits o perl!
Time:03:54 pm
Trivial bits, but I get to play with bit shifting.

code behind the cut )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[GEEKY] Dusting off my Perl-fu
Time:10:11 am
The central issue of this little bit of code is that i'm building a hash with keys from the first line of a text file. That part wasn't bad, though I would of course appreciate any tips for doing it faster. The real kicker is in pulling the data from the file into that hash. When I knew the keys beforehand, I could just go:

# $_ here is one non-header line of the file.  
# $separator is the record separator
($hash->{foo}, $hash->{bar}, $hash->{baz}) = split /$separator/;


But since I don't know the keys beforehand, I have to do this:
# $_ here is one non-header line of the file.  
# @keys are the keys of the hash, pulled from the first line for the file. 
# $separator is the record separator
my @split = split /$separator/;
my $i = 0;
for (@split) {
  $hash->{$keys[$i]} = $split[$i];
}

And that seems a bit inelegant and overly verbose. Is there any way to do it more elegantly?

actual code behind the cut )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[CODE] Replacing things delimited by brackets
Time:09:09 am
I got really tired really quickly of writing out the hyperlink for the documentation on a given table when writing my reading the database posts on Scribblit. So I decided to throw some Perl at it, as I gave up on doing it in XSL. It took a couple tries, but here is the current version of the Perl code.

code behind the cut, WS )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , , ,
Subject:[CODE] Some old stuff I found poking around
Time:04:51 pm
Various bits of code behind the cut, WS )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , , , ,
Subject:[GEEKY] Java cryptography question
Time:06:29 pm
I'm trying to extract the key used to encrypt a DES-encrypted string by brute force methods. I know the cleartext, and when it's written to the Windows registry, it's a string of eight bytes. As a first attempt, i did some Googling and threw this code at it:

code behind the cut )

When I try to run the code, I get the error: "Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded"

What am I doing wrong?

And don't ask me why it's DES-encrypted. I didn't write the encryption routine.
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[GEEKY] thoughts
Time:09:22 pm
It might be neat to write a Java class that provides arbitrary-length fixed-width integers. Not BigIntegers - they grow, and I don't want them to grow. I want overflow.

I could base it on an array of bytes, but that constrains me to multiples of eight (or I have to start doing weird stuff to simulate the absence of those extra bits). Hmm.
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , , ,
Subject:[GEEKY] OOP Question
Time:07:43 am
Current Mood:[mood icon] curious
In Java, I can do this:

public interface foo {
  public void bar();

  public class Factory {
    public newInstance() {
      return new Foo() {
        public void bar() {
          System.out.println("bar");
        }
      }
    } 
  }
}


I.E. I can declare an interface and attach a static Factory class that spawns new anonymous classes that match that interface. Depending on conditions, I could spawn several different anonymous classes specially optimized for those conditions.

In Perl, I can't do that. There's no such thing as an interface (in Java terms) in Perl. If I wanted a single-class solutions, I would have to write the class to detect conditions on initialization and make the methods behave accordingly.

My question: is this a good thing, a bad thing, or indifferent? Discuss.
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[GEEKY] Non-recursive directory traversal in Java?
Time:04:07 pm
Alternatively, does anyone know a way to tune the JVM to speed up recursive directory traversals? I've got a directory structure of (estimated) 50 directories (each with between 0 and 20 subdirectories), each with 35,000 files in them. Grand total of 1.75 million files. On a test directory of only 35,000 files, the code below takes about 6 ms/file to traverse the whole structure, and I'd like to speed it up significantly if I can.

Any ideas? Using an array rather than an arrayList is a possibility, but there's going to be a lot of overhead in resizing the array unless I can think up some clever way around it.


public static ArrayList listRecursive(final File dir) {
		assert dir.isDirectory();
		assert dir.exists();

		ArrayList files;
		if (dir.list() == null) {
			files = new ArrayList(0);
		} else {
			files = new ArrayList(dir.list().length);
			for (File file : dir.listFiles()) {
				if (file.isDirectory()) {
					files.addAll(listRecursive(file));
					recursions++; // Note that this is defined statically outside of this method
				} else {
					try {
						files.add(file.getCanonicalPath());
					} catch (IOException e) {
						throw new RuntimeException("I/O Error: " + e.getMessage());
					}
				}
			}
		}
		return files;
	}


EDIT: Running this code on my test data gave me 132 recursions. This is why I think that the recursions are dominating the time the program uses.
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , ,
Subject:[GEEKY} I am *way* too easily amused
Time:11:35 am

JOptionPane.showMessageDialog(chooser, "You suck");
JOptionPane.showMessageDialog(chooser, "No, really.");
JOptionPane.showMessageDialog(chooser, "You really suck.");
JOptionPane.showMessageDialog(chooser, "BURMA SHAVE");

comments: Leave a comment Add to Memories Tell a Friend

Tags:, , ,
Subject:[CODE] Interesting Java bit
Time:11:08 am
Current Mood:geeky
So I'm writing some Swing (GUI) code by hand because I'm crazy. ;) Seriously, I want to get a feel for how this stuff works myself - I don't want some designer program thinking for me, at least not yet. :)

I'm displaying a JTable inside a JScrollPane like so:


JTable table = new JTable(data, columnLabels);
JScrollPane scroll = new JScrollPane(table);



And I was thinking I could get rid of table and access it via scroll.getComponents. But, interestingly enough, at least to me, when I do this:


for (Component c : scroll.getComponents) {
  System.out.println("scroll has component " + c);
}



Nowhere in there do I see a JTable.

Just a random bit of interestingness, at least to this Swing n00b.

EDIT: Here's a sketch that does the whole shebang.


import java.awt.Component;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

// Created Jul 31, 2007
/**
 * @author Kit Peters <popefelix@gmail.com>
 */

public class JScrollPaneSketch {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final JFrame frame = new JFrame("Scroll Pane Sketch");
		final String[] cols = { "foo", "bar", "baz" };
		final String[][] rows = { { "a", "b", "c" }, { "a", "b", "c" } };
		final JTable table = new JTable(rows, cols);
		final JScrollPane pane = new JScrollPane(table);

		for (Component c : pane.getComponents()) {
			System.out.println("pane has component" + c);
		}
		frame.setLayout(new GridLayout(1, 0));
		frame.add(pane);
		frame.pack();
		frame.setVisible(true);
	}

}

comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[GEEKY] Note to self
Time:02:05 pm
Dear self,

Java will silently convert an Integer into an int for you. But remember that a conversion is taking place, even if you don't see it happening. In reality, Java is inserting a call to Integer.intValue() for you. If said Integer is null, this is going to cause a NullPointerException.

Love,

me

It took me from about 11:00 until now (with lunch in the middle) to figure that one out. *sigh*
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[CODE] This acually works!
Time:10:15 am
Current Mood:[mood icon] surprised
<?php
   
  foreach(array('emp', 'mgr') as $prefix) {
      $data[($prefix == 'emp') ? 'employee' : 'manager'] = 1;
  }
  
  print_r($data);
?>


Output:

Array
(
    [employee] => 1
    [manager] => 1
)


I would have expected that from Perl, but not PHP.

EDIT: added output per [info]aisa0's request. :)
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , , , ,
Subject:[CODE] PHP is still pass-by-copy
Time:05:19 pm
Current Mood:[mood icon] disappointed
I had it in my head that with PHP5, objects were implicitly passed by reference. contrast this with PHP4, in which objects were implicitly passed by silent copy (I don't know how deep, though). This code demonstrates that objects are still implicitly passed by copy, and that annoys me.

*sigh* After having done a lot of OO Perl for the past month and a half, coming back to PHP OOP is a bit of a letdown.

PHP code behind the cut )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[code] A little something I tossed off
Time:04:09 pm
Current Mood:geeky
A bit of code for finding the dimension of an array or a hash. I define "dimension" here as the minimum number of coordinates required to get to a data value. In this case, all the data values are integers, because it makes things easy. :)

It's recursive, because that was easy too. :)

One more thing - it only considers the first value of the supplied reference. So if the array/hash contains a mix of references and data values at any given depth, it will return a value that's not strictly accurate.

So come one, come all, pick apart my code and show me where I can do it better. I don't mind. :) Extra points for making it consider (quickly) every element in the array/hash ref - you could even define a fractional dimension that reflects the number of "leaves" (if you think of it as some sort of tree structure) at at one depth versus the number at another depth. *ponder* That would be extra neato if that fractional dimension generalized to any number of different depths.

EDIT: Cleaned up code for easier display on LJ.

code behind the cut, WS )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[CODE] Quick-and-dirty bit of code for the wife
Time:01:32 pm
She's got an audiobook of Bridge To Terabithia that she wants to put on her MP3 player. It's on 4 CDs, and it ended up getting ripped into 1 directory for each disc. Each track was numbered with respect to the disc, rather than the whole thing. [info]hlynna can explain better. :)

Anyway, here's the code I used to rename things a bit:
Perl code behind the cut )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[code] FizzBuzz
Time:12:01 pm
In response to Why Can't Programmers.. Program?, just to show I can, in fact, do it. :)

FizzBuzz.pl )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, , ,
Subject:[CODE] A bit of Perl
Time:11:24 am
Current Mood:geeky
A bit of Perl I knocked up to increment the tabindex argument to HTML <input> tags.

code behind the cut )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:(GEEKY) A great big WTF?!?!?!?!?
Time:09:29 am
Current Mood:[mood icon] shocked
Apparently, automatically converting an object to an integer in PHP results in a 1....
code behind the cut )

This is just categorically wrong.

EDIT: This page sheds some light on this behaviour. It seems that in the case of a data type other than strings and floats, the item is first evaluated as a boolean, and then converted to integer. So since an object instance evaluates to boolean true, the subsequent integer conversion evaluates to 1.

Still not what I would have expected.
comments: Leave a comment Add to Memories Tell a Friend

[icon] Makes you like your eggs on the Jersey side
View:Recent Entries.
View:Archive.
View:Friends.
View:User Info.
View:Website (Clowns Will Eat You).
View:Poly Geek Relationship Disclosure Form.
You're looking at the latest 20 entries.
Missed some entries? Then simply jump back 20 entries