Archive for July, 2009

New (version of) close-up font comparer: versus

Friday, July 31st, 2009

versus font comparerToday, I coded up Versus, a close-up font comparer. The original version (somewhat inspired by the documentary Helvetica) was written in straight html and css (with a little php to generate new phrases). The were a lot of problems with that version… Most importantly it only seemed to run on my browsers on my machine (some of the renderings — especially on IE browsers — were quite comical). The new version is all java and runs beautifully in a browser applet on any machine and any browser with java enabled. It also lets you choose fonts to compare from a list of fonts you have access to on your machine. I also included a “full screen page”.

Tell me what you think and leave ideas for improvements.

Note: For anyone interested here’s the source code.

Read a single keyboard hit (even arrows and special keys) without echoing, in Ruby

Friday, July 31st, 2009

I’m writing a command line program in ruby which interacts using single keystrokes with out hitting enter/return. Using system calls to stty I’ve been able to disable echoing (so the key you press isn’t displayed on the screen) and enable raw buffering (so you don’t have to hit enter/^D after the key to make it register into STDIN). Using this with STDIN.getc works fine for all keys on the keyboard that have single character equivalents: letters, numbers, punctuation, symbols, and white space (oddly enough it does work for the ESCAPE key, but more on that one later). This method does not work for special keys like the arrows or control keys (as in ^X or CNTRL+X) because those keys all register as a string of characters, not just a single character.

To read these “long” key strokes I make two extra calls to STDIN.getc if I see a special key coming (based on the first call to STDIN.getc. Now I have all the arrows and others reading fine, but unfortunately the ESCAPE key is only a single character key hit and that character is exactly the special first character I match to know that a long character has been pressed. My primitive solution is to place the extra STDIN.getcs in a thread and kill that thread almost immediately after it is run. This way if the ESCAPE key is pressed, the program won’t wait on the extra STDIN.getcs. If a special key like an arrow is pressed the extra STDIN.getcs occur immediately and before the thread is killed. My read_char method:


# read a character without pressing enter and without printing to the screen
def read_char
  begin
    # save previous state of stty
    old_state = `stty -g`
    # disable echoing and enable raw (not having to press enter)
    system "stty raw -echo"
    c = STDIN.getc.chr
    # gather next two characters of special keys
    if(c=="\e")
      extra_thread = Thread.new{
        c = c + STDIN.getc.chr
        c = c + STDIN.getc.chr
      }
      # wait just long enough for special keys to get swallowed
      extra_thread.join(0.00001)
      # kill thread so not-so-long special keys don't wait on getc
      extra_thread.kill
    end
  rescue => ex
    puts "#{ex.class}: #{ex.message}"
    puts ex.backtrace
  ensure
    # restore previous state of stty
    system "stty #{old_state}"
  end
  return c
end

You may have to adjust the sleep time according to your machine.
Here’s a quickly case block to show what can be gathered:


# takes a single character command
def show_single_key
    c = read_char
	case c
	when " "
	  puts "SPACE"
	when "\t"
	  puts "TAB"
	when "\r"
	  puts "RETURN"
	when "\n"
	  puts "LINE FEED"
	when "\e"
	  puts "ESCAPE"
	when "\e[A"
	  puts "UP ARROW"
	when "\e[B"
	  puts "DOWN ARROW"
	when "\e[C"
	  puts "RIGHT ARROW"
	when "\e[D"
	  puts "LEFT ARROW"
	when "\177"
	  puts "BACKSPACE"
	when "\004"
	  puts "DELETE"
	when /^.$/
	  puts "SINGLE CHAR HIT: #{c.inspect}"
	else
	  puts "SOMETHING ELSE: #{c.inspect}"
	end
end

And here’s nifty rubyism to run this indefinitely, say in irb:


show_single_key while(true)  

Note: It seems the HOME, END, PAGE UP and PAGE DOWN keys are stolen by the command line terminal and won’t register to STDIN.getc. I don’t know of a “fix” for this.

Note: I have no access to a Windows machine right now and would gladly appreciate a comment as to how much of this will work on Windows.
Note: I have changed sleep(0.000000000000000000001) to the more ruby-friendly extra_thread.join(0.00001). I also decreased the limit. Neither of these really change anything in fact on my machine the code runs fine without this line.

Foiling google.com’s pay-per-click advertising program

Thursday, July 30th, 2009

For educational purposes only:
Here is a sketch for a script that works with Safari and shell to “click” on all the ads you see while surfing the web. These visits to the advertisers pages (after first being rerouted by the pay-per-click counter, in this case google.com) happen behind the scene. So to the advertiser and the host of the ads it seems as though you clicked on the ad you saw, but to you your surfing went undisturbed.

Save the following in a file called clickads.sh:


#!/bin/bash
SOURCE=`cat -`
ADS=`echo $SOURCE | grep -o "/aclk?[^\"]*" | \
sed s/amp\;//g | sed s/^/http:\\\/\\\/google.com/g`
for x in $ADS
do
  `/sw/bin/wget -q -erobots=off -t2 -O - -U "Mozilla/5.0 \
(Macintosh; U; PPC Mac OS X 10_4_11; en) AppleWebKit/530.17 \
(KHTML, like Gecko) Version/4.0 Safari/530.17" "$x" 2>&1 | \
cat > log.clickads`
done

Note: change your absolute path to wget accordingly (find what it is by issuing which wget in a terminal).

clickads.sh will accept the html source of a google search, strip out all of the side bar ads and “click” each one. Remove the log and change your -U User agent accordingly (remember this is not for use and for educational purposes only).

Now, so that the background clicker only “clicks” on ads you actually see, save and run this as an Applescript:


repeat
	try
		tell application "Safari"
			set old_current_source to ""
			set current_source to ""
			repeat until old_current_source is equal to current_source and current_source is not equal to ""
				set old_current_source to source of front document as string
				delay 1.0
				set current_source to source of front document as string
			end repeat
			set current_url to URL of front document as string
		end tell
		if current_url starts with "http://www.google.com" then
			set newFileName to ".behindthescenesadclick.temp"
			set newFile to open for access newFileName with write permission
			set eof of newFile to 0
			write current_source to newFile
			close access newFile
			do shell script "cat /.behindthescenesadclick.temp | bash ~/Bash/clickads.sh"
		else
			delay 1
		end if
	end try
end repeat

The path to the dump temp file ".behindthescenesadclick.temp" has to be in Applescript format not UNIX. And remember to change the path to ~/Bash/clickads.sh to point to your file.

The above code could be easily modified to target pay-per-click hosts other than google.com and there was no reason other than availability that I chose that site here.

Looping over the entire alphabet with old bash

Wednesday, July 29th, 2009

Working on a mac with an older version of bash (2.05b.0), I found myself deprived of the fancy sequences of bash versions greater than 3.0. Namely {1..100}, {a..z}, etc. Unfortunately, I did not have seq either. Luckily my mac did have jot, so I could implement a loop over the alphabet (lowercase and uppercase) like this:


#!/bin/bash
for x in `jot -c - a z 1` `jot -c - A Z 1`
do
echo $x
done

Directory name and base name in Applescript

Wednesday, July 29th, 2009

I wanted to extract the base directory of a URL which gave rise to the question in my last post of how to find the last offset in a string. Armed with this ability, I can now do in Applescript that which File.dirname and File.basename do so effortlessly in Ruby. I modeled my dirname and basename after their ruby counterparts just mentioned:


on dirname(the_path)
  set last_occurrence to last_offset(the_path, "/")
  if last_occurrence is equal to 0 then
    return "."
  end if
  if last_occurrence is equal to 1 then
    return "/"
  end if
  if last_occurrence is equal to (count of the_path) then
    set the_path to items 1 thru (last_occurrence - 1) of the_path as string
    return dirname(the_path)
  end if
  return items 1 thru (last_occurrence-1) of the_path as string
end dirname

on basename(the_path)
  set last_occurrence to last_offset(the_path, "/")
  if last_occurrence is equal to 0 then
    return the_path
  end if
  if last_occurrence is equal to 1 then
    return "/"
  end if
  if last_occurrence is equal to (count of the_path) then
    set the_path to items 1 thru (last_occurrence - 1) of the_path as string
    return basename(the_path)
  end if
  return items (last_occurrence + 1) thru -1 of the_path as string
end basename

I also wrote a third method similar to dirname but behaves better for striping out the base directory of a url:


on basedir(the_path)
  set last_occurrence to last_offset(the_path, "/")
  if last_occurrence is equal to 0 then
    return "."
  end if
  if last_occurrence is equal to 1 then
    return "/"
  end if
  return items 1 thru (last_occurrence) of the_path as string
end basedir

So what’s the difference? Here are some examples:


display dialog basename("/")        -- "/"
display dialog basename("foo")      -- "foo"
display dialog basename("foo/")     -- "foo"
display dialog basename("foo/bar")  -- "bar"
display dialog basename("foo/bar/") -- "bar"
display dialog dirname("/")         -- "/"
display dialog dirname("foo")       -- "."
display dialog dirname("foo/")      -- "."
display dialog dirname("foo/bar")   -- "foo"
display dialog dirname("foo/bar/")  -- "foo"
display dialog basedir("/")         -- "/"
display dialog basedir("foo")       -- "."
display dialog basedir("foo/")      -- "foo/"
display dialog basedir("foo/bar")   -- "foo/"
display dialog basedir("foo/bar/")  -- "foo/bar/"

For these examples and all that I could think of, my dirname and basename return the same strings as ruby’s File.dirname and File.basename. Notice that my basedir is not the same as either dirname, but it is convenient for operations on URLs like this:


tell application "Safari"
	set current_url to URL of front document as string
end tell
display dialog basedir(current_url)

But if you’re messing with URLs in Applescript you probably want the other half to, so maybe just use last_offset on your own.

Update: See my new post about extracting directory path, file name with extension and root with pure applescript.

Find the last offset in a string using Applescript

Wednesday, July 29th, 2009

Applescript has famously awkward, clumsy and insufficient string operations. I set about trying to extract the base address of a url (or file path) with applescript (by the way ruby provides this with the method File.dirname). Applescript provides offset of as in the offset of "e" in "hello" is 2 (remember Applescript is 1-indexed). There is no easy equivalent to find the last occurrence in a string, the last offset. Here are my two solutions.

Solution One:


on last_offset(the_text, char)
	try
		set i to 1
		set last_occurrence to 0
		repeat count of the_text times
			if item i of the_text as string = char then
				set last_occurrence to i
			end if
			set i to i + 1
		end repeat
	on error
		return 0
	end try
	return last_occurrence
end last_offset

This is really Intro to Computer Programming 101 feeling. I return 0 if something goes wrong or there are no matches like the way offset of returns 0 for no match.

Solution Two:


on last_offset(the_text, char)
  try
    set len to count of the_text
    set reversed to reverse of characters of the_text as string
    set last_occurrence to len - (offset of char in reversed) + 1
    if last_occurrence > len then
      return 0
    end if
  on error
    return 0
  end try
  return last_occurrence
end last_offset

It doesn’t seem like there’s any reason why one of these is faster than the other.

Remove icon from file/folder on Mac OS X

Monday, July 27th, 2009

I was messing with the icon of my external drive and managed to lose the ability to change or reset the icon using “Get info” in the GUI. I found a way to forcibly remove the icon, and in doing this found a nice way to change icons outside the GUI.

To remove a file’s icon or in this case my volume’s icon:
in a Terminal cd into that Volume, usually /Volume/[drive name]/, then remove the icon file called .VolumeIcon.icns with the command:


rm .VolumeIcon.icns

This prompted me to examine what icon files for regular files look like, for a tiff image called green.tiff the icon file was in the same folder called ._green.tiff. I wanted my volume to have the same icon as this tiff image, only the transparency wasn’t showing up correctly. It showed up correctly in the tiff file’s icon, but not when I copied the icon using “Get info” to the volume. On the command line I was able to give my volume a transparent icon from a tiff file by simply coping the icon file of the image onto the icon file of the drive:

 cp ._green.tiff .VolumeIcon.icns 

Update:
Might as well post the transparent icon images I changed my volume icons to. The idea was to have the color of the drive match the USB cord attached to the computer:

Red Drive IconGreen Drive IconBlue Drive IconPink Drive IconYellow Drive IconTeal Drive IconPurple Drive IconBlack Drive Icon


Download a folder containing all of the above read to use

Magic Eye Oriental Rugs

Friday, July 24th, 2009

I am planning to mass produce oriental living room rugs that are delicately woven to contain Magic Eye type optical illusions. Photos and blueprints to come (please contact me if you are a rug manufacturer interested in this idea).

Update:
Here’s a prototype I made using an image I implemented with google and http://www.easystereogrambuilder.com/ :
Oriental Magic Eye Rug

Tessellating cookie (cutters)

Friday, July 24th, 2009

I’m planning to create tessellating cookie cutters so that Escher can live on through culinary arts.
Photos and blueprints to come.

How to kill ruby on rails WEBrick server daemon

Friday, July 24th, 2009

I have been running a rails app on a machine, which I can’t restart (no root access) or physically pull the plug on, just using the prepackaged rails server, WEBrick. But I quickly found out that it was not that easy to kill my app. I’d run something like script/server -d -p 25000 > /dev/null .
Notice that -d puts the server in daemon mode and > /dev/null sends all the standard out to /dev/null .
I tried to kill the app using top and then killing with the process ID, then tried pgrep and kill on the command line, to no avail.

Finally I found the (simple) solution that I’ll repost here. On the command line of the machine running the server:

pgrep ruby

This will give you the process id of the rails app (assuming you don’t have another ruby app running). Note: if pgrep is not available on your machine try using the command:

top

and look for the id of a process called ‘ruby’.

Now kill that process using the command:

kill -9 [id]

Where [id] is the process id given by pgrep.

Update:
It seems kill -9 may be jumping the gun and perhaps you ought to be safe and follow the advice I found elsewhere.
I’ll reiterate his point here. After finding the process id using prgep issue the following commands waiting five seconds before trying the next one until the kill succeeds:


kill pid 
kill pid
kill -INT [id]
kill -INT [id]
kill -KILL [id]
kill -KILL [id]

Notice that -KILL is the same as -9 .