Simple Ruby Text Parser

Mar 20
2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
filename = "sample records.txt"
file = File.open(filename)
data = []
record = {}
 
class MyParse
  Tokens = [
    ### change the regular expressions accordingly ###
    ### sale date, sale time, sale address,
    [/^Sale:\s*(\d+\/\d+\/\d+)\s+(\S+\s+\w\w)\s+(.+?)\s*$/,
        lambda { |m| m.to_a &&
            {"sale date"=>m[1], "sale time"=>m[2], "sale address"=>m[3] } }],
    ### seller name, seller time, seller address
    [/^Seller:\s*(\d+\/\d+\/\d+)\s+(\S+\s+\w\w)\s+(.+?)\s*$/,
        lambda { |m| m.to_a &&
            {"seller date"=>m[1], "seller time"=>m[2], "seller address"=>m[3] } }],
    ### Trustor: trustor
    [/^Trustor:\s+(.+?)\s*$/,
        lambda { |m| m.to_a && {"trustor"=>m[1] } }],
  ]
 
  def self.read(text)
    parse(text)
  end
 
  protected
  def self.parse(text)
    text.each do |line|
      Tokens.each do |token|
        if m = token.first.match(line)
          return token.last.call(m)
        end
      end
    end
    nil
  end
 
end
 
begin
  while line = file.readline
    if line.match(/^\s*$/)
      record = {}
      next
    end
    line.sub!("\r", "")
    if record = MyParse.read(line)
      data.push(record)
    end
  end
rescue EOFError => e
  puts "'#{filename}': #{e}"
ensure
  file.close
end
 
puts data.inspect
 
exit(0)

a quick remedy for ipod shuffle illnesses

Mar 18
2009

Symptoms: one green light flash, followed by two green ones.

Conclusion: the player is dead.

Remedy: download ipod reset utility, reset the player and

# change _path_to_the_device_ with the real path (see `dmesg|tail`)
 
mount /dev/_path_to_the_device_  /mnt && cd /mnt
 
# download rebuild_db.py from http://shuffle-db.sourceforge.net/
# copy 'rebuild_db.py' in /mnt and create the dirs' structure
 
python -c '
import os
os.makedirs("iPod_Control/iTunes")
os.makedirs("Music")
'
 
cd /mnt && cp ~/Music/*.mp3 Music
python rebuild_db.py
cd .. && umount

That’s it.

P.S. you can format an ipod device as many times as you like,
just follow the above procedure to reset it.

How to download an image from flickr

Mar 11
2009

I wasn’t able to download a photo from flickr. It happened to be 1px transparent image over the other. Here is a simple scaper in cases of such “protection”:

1
2
3
4
5
6
7
8
9
10
11
12
require 'rubygems'
require 'www/mechanize'
 
url = 'http://www.flickr.com/photos/46457493@N00/3162339409/in/set-72157612102050814/'
 
my_id = url.split("/")[-3]
agent  = WWW::Mechanize.new
page   = agent.get(url)
 
url   = page.search("//div[@id='photoImgDiv#{my_id}']/img").attr('src')
 
agent.get(url).save_as((File.basename(url)).split("?")[0])

Calendar

March 2009
M T W T F S S
« Feb   May »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Tags