Skip to content

Instantly share code, notes, and snippets.

View vincentchu's full-sized avatar

Vincent Chu vincentchu

View GitHub Profile
@vincentchu
vincentchu / random_numbers_and_forking.rb
Created March 20, 2011 03:38
Using Ruby 1.8.7, let's take a look at how the random number generator behaves under forking
[false, true].each do |reseed_rand|
puts "*" * 100
puts "Force reseed of the random number generator? #{reseed_rand}"
2.times {
fork {
srand if reseed_rand
puts sprintf(" Process ID: %5d, child of %5d: 3 Randoms: %.5f, %.5f, %.5f", Process.pid, Process.ppid, rand, rand, rand)
}
}
require 'rubygems'
require 'redis'
require 'redis/distributed'
redis = Redis::Distributed.new(['redis://localhost:6379', 'redis://localhost:6380'])
(1..10_000).each do |i|
key = "rand_#{rand}"
val = rand(1000)
@vincentchu
vincentchu / histogram.rb
Created May 18, 2011 02:39
histogram.rb
#!/usr/bin/ruby
binwidth = ARGV[0].to_f
filename = ARGV[1]
rand_file_name = "rand_file-#{(rand*1000000).to_i}.data"
nums = File.open(filename, "r") {|f| f.readlines}.collect {|n| n.to_f }
binned_data = {}
nums.each do |n|
@vincentchu
vincentchu / pop_quiz_asshole.rb
Created May 18, 2011 22:24
pop_quiz_asshole.rb
begin
raise "THIS IS WEIRD?"
rescue ex
puts "EX = #{ex.message}"
end
# => undefined local variable or method `ex' for main:Object (NameError)
(`·. )\ )`·. )`·.
) `·. .·´( .·´ ( (`·. )`·._.·´( )`·. /( .·´ ( /( .·´ (
.·´( .·´:..::(,(::-- ' '\:·´ \::`·._)`·. )\.·´::... .::) .·´ ./ )\ ) `·._):::. ) )\ ) `·._):::. )
);; :-- ' ' _\ .·´( )::. ..:::).·´;· -- ´ ´\::.`·.(::...:(' )\ .·´ .:`·.(:;; -- ' '\:. :(.·´) )\ )\ .·´ .:`·.(:;; -- ' '\:. :(.·´) )\
.·´/\ ,..:´:::'/ ):..\(;;::-- ´ ´ '\:::::::...::) .·´ (,): -- ' ' \....:::`·.( ( .·´ (,): -- ' ' \....:::`·.( (
)/:::'\...:/I I::::::::/ '(::...:/\
@vincentchu
vincentchu / test_server.rb
Created May 28, 2011 05:02
Test sinatra + EventMachine
require 'rubygems'
require 'sinatra/base'
require 'eventmachine'
require 'logger'
$logger = Logger.new(File.join(File.dirname(__FILE__), "development.log"))
module TestEM
def self.start
if defined?(PhusionPassenger)
@vincentchu
vincentchu / smith-waterman.rb
Created June 23, 2011 05:50
Smith Waterman implementation in Ruby
class Matrix
IndexOverflow = Class.new(StandardError)
attr_reader :dims, :nrows, :ncols
def initialize(mm, nn)
@dims = [mm, nn]
@nrows = mm
@ncols = nn
# For multi-line blocks, use do. E.g.:
users.each do |user|
user.name = "foo"
user.save
end
# For single-line blocks, use {}
users.each {|user| user.destroy }
>>> num = 5.0/3
>>> print "num = %.2f" % (num)
num = 1.67
>>> print "num = %.3f" % (num)
num = 1.667
>>> print "num = %6.3e" % (num)
num = 1.667e+00
>> Loofah::Helpers.strip_tags("<script>var foo;</script>")
=> "<script>var foo;</script>"