February 2008

A Trip into Random

In the deep darkness of my computer I have a folder called random. Here I put all kind of code, far away from the public. This day I will share some of it. Beware…


Ruby has built-in support for AES-encryption through OpenSSL. How to use it? The only thing I could find was Encrypting data with ruby and OpenSSL at DZone Snippets. So how to turn that into a simple helper?

# m(ethod) => :encrypt or :decrypt
# k(ey) => String
# t(ext) => String 
def aes(m,k,t)
  (aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k)
  aes.update(t) << aes.final

def encrypt(key, text)
  aes(:encrypt, key, text)

def decrypt(key, text)
  aes(:decrypt, key, text)

encrypted = encrypt("a secret key", "secret text")
decrypt("a secret key", encrypted) #=> "secret text"

Reverse Polish Notation

Recently I discovered a RubyQuiz called Postfix to Infix. I didn’t submit my solution (it was already closed), but I think it’s quite small and hackish:

e = []
(ARGV[0]||"").split.each do |n|
  e << case n 
  when "+", "-", "*", "/", "^"
    next unless e.length >= 2
    y = e.delete_at(-1)
    x = e.delete_at(-1)
    [x, n, y]
  when /^\d+(\.\d+)?$/
exit if e.empty?
puts e[0].inspect.gsub("[","(").gsub("]",")").gsub(/[","]/,'')[1..-2]
# $ ruby dc.rb '1 56 35 + 16 9 - / +'
# 1 + ((56 + 35) / (16 - 9)) 

Friends for Sale

I’m using Facebook and Friends for Sale, and I’m taking it very serious. Just in order to get all the cash, I’m using this script to log in to FFS every hour (through cron):

require 'rubygems'
require 'mechanize'

URL = "http://apps.facebook.com/friendsforsale"
EMAIL = "judofyr@gmail.com"
PASS = "my password"

agent = WWW::Mechanize.new
page = agent.get(URL)

login = page.forms.name("loginform").first
login.email = EMAIL
login.pass = PASS

page = agent.submit(login)                                       


The last one is a little snippet to build a Pascal-triangle. Check it out at Balloon!

@c = {}
# Factoring n
def f(n)@c[n]||=(1..n).inject(1){|m,e|m*=e}end

# Find the number in a Pascal-triangle (row, column)
def p(r,c)f(r)/(f(c)*f(r-c))end

# Builds a Pascal-triangle (number of lines, extra width)
def t(n,w=1)(r=(0...n).map{|r|(0..r).inject(""){|m,c|m<<p(r,c).to_s.center(p(n,n/2).to_s.length+w)}}).map{|x|x.center(r.last.length)}end