Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Ruby word count

module StringExtensions
  def words
    s = self.dup
    s.gsub!(/\w+/, 'X')
    s.gsub!(/\W+/, '')
    s.length
  end
end

Fast stop word detection in Ruby

Requires BloominSimple (a pure Ruby Bloom filter class).

List of stop words obtained from http://www.dcs.gla.ac.uk/idom/ir_resources/linguistic_utils/stop_words

# Detect stop words QUICKLY
# Uses a bloom filter instead of searching literally through a list of stopwords
# for > 3x speed increase
# 
#    using bloom filter: 2.580000   0.030000   2.610000 (  2.698829)
#  using literal search: 7.850000   0.120000   7.970000 (  8.181684)


require 'bloominsimple'
require 'digest/sha1'
require 'pp'

# Create a simple bloom filter that uses a SHA1 hash (more effective than BloominSimple's default hashing)
b = BloominSimple.new(50000) do |word|
  Digest::SHA1.digest(word.downcase.strip).unpack("VVV")
end

# Add stopwords to the bloom filter!
stopwords = []
File.open('stopwords').each { |a| b.add(a); stopwords << a.downcase.strip }

# Read in a whole dictionary of regular words
words = File.open('/usr/share/dict/words').read.split.collect{|a| a.downcase.strip }

# Define two ways to detect stopwords for comparison..
using_filter = lambda { |word| b.includes?(word) }
using_array = lambda { |word| stopwords.include?(word.downcase.strip) }
techniques = [using_filter, using_array]

# Run stopword comparisons with both techniques
t = techniques.collect { |l| words.collect { |a| l[a] } }

# See how effective the bloom filter has been compared to the literal search
if t[0] == t[1]
  puts "GOOD"
else
  words.zip(t[0],t[1]).each do |x|
    puts x.first if x[1] != x[2]
  end
end

# Now do speed benchmarks..
techniques.each { |l| puts Benchmark.measure { words.each { |a| l[a] } } }

genetic algorithm in J

-------------  Beginning of class  pga.ijs   -------------------
coclass'pga'
create=:3 : 0
genes=: ? 4 $ 100  NB. 4 random integers 0-99
)
getgenes =: 3 : 'genes'
setgenes =: 3 : 'genes=:y.'
matewith=: 3 : 0
other=. y.
mine=. ((#genes) % 2) ? (#genes) NB. crossover
childgene=. getgenes__other '' NB. copy others intially
child=. conew 'pga'
setgenes__child ((mine { genes) (mine }) childgene)
child
)
perform =: 3 : 0 NB. dummy problem
+/ genes
)
destroy=:codestroy
-------------  End of of class  pga.ijs   ----------------------
-------------  beginning of script ga.ijs ----------------------
NB. genetic algorithm 
NB. needs pga class
NB. define a dummy target to measure fitness against
targetvalue =:  500  
fitness=: 3 : 0
object=. y.
1000 * %(targetvalue - perform__object '')
)

load jpath '~user\classes\pga.ijs'


top =: 4 : '(i.y.) { \: (fitness each x.)'  NB. pop top 10 returns the 10 fittest

pair=: 3 : 0  NB. pick two random ga objects, mate them, and return the child
pop=. y.
mom=. > (?#pop) { pop NB. must unbox!
dad=. > (?#pop) { pop NB.  # is length of boxed list
matewith__mom dad
)

NB.  pop evolve generations returns the fittest ga after 
NB. sifting the top 25 ga's
evolve=: 4 : 0
pop=. x.
n=. y.
for_k. i.n do.
kpop=.  3 : 'pop' NB. not sure if necessary to do here
newgen=.  (pair@kpop) each i.100  NB. create 100 children
best=.  (newgen top 25) { newgen NB. find the indices of the best, then select the corresponding objects
pop=. best,best,best,best  NB. not really necessary?
end.
>0{best  NB. return best
)
NB. usage  
load jpath '~user\ga.ijs'
average =: +/%#
pop=: conew&'pga' each i.100   NB. create 100 boxed ga objects
fitness each pop  NB. should show a boxed list of fitness values
average ; fitness each pop  NB. shows average fitness

fred=: pop evolve 100
fitness fred
uberfred=: pop evolve 1000

NB. the fitness values increase pretty slowly which is disappointing
NB. probably needs some mutation :)
-------------    end of script ga.ijs     ----------------------

ruby language features

Unsorted list of features, howto's, suggar and evils of ruby (on rails)

# THIS FILE CONTAINS INTERESTING SNIPPETS OF RUBY/RAILS
# in order to accelerate learning and find forgotten things
#  
#  Key shortcuts!
#  ctrl+shift+v  controller/view!
#  ctrl+k  find next word
#  ctrl+m maximize editor
#  
# 
# 
#   
BAD
-----------------------
model files do not contain the classes field information 
instead this is stored in different 'migration' files
create_table "periods" do |t|
    t.column "target_id", :integer
    t.column "target_type", :string
    t.column "start_at", :datetime
    t.column "end_at", :datetime
    t.column "wholeday", :boolean
    t.column "wholeweek", :boolean
    t.column "allweeks", :boolean
  end
 NO inbuild multi dimensional arrays
DANGER!!!!!
and is not && !!!!!!!!!!!!!!!!!!!!!!!!
return x==7 and y==8  => void value expression!!!
return x==7 && y==8  !!!
nr==0 (evaluates string.nil? !!!!!!!  "0"==0 -> false!!!!)
nr.to_i==0 !!

#ANNOYANCES:
+ operator for string is really baad :
cannot convert nil into String !!! 
puts "teacher "+ @lesson.teacher
 "last saved : "+ DateTime.now.to_s  #to_s !!! neccessary!!!!!!! (and ugly)
"nr"+rand(10).to_s#!!!

Language buggy: (see http://public.transcraft.co.uk/blog/index.html)
ActionController::RoutingError (Recognition failed for "/images/btnbg.gif"):

helpers are only for views!! (ApplicationController is what you need)

@links = Link.find_by_sql [
"SELECT * from links where link like '"+ @a +"%' order by id asc"]
  #endwith startwith
s = "Hello, world"
/^Hello/.match( s ) 	>> true
/world$/.match( s ) 		>> true
  
 
<!--bad philosopy : evaluation inside html comments?
<%#= datetime_select 'lesson', 'end_at'  %></p>-->
  
  -------------------------------------
Good
********************

class.byname:

  alle= eval(type+".find(:all)")
  Object.const_get("Array")

# default values
def initialize(definitions=[], word = nil)       
      @definitions = definitions
      @word = word
    end


rake db_schema_dump !!! instead of writing the migration files yourself

rake --help
rake migrate VERSION=n  #runs from 0 to n !!!!!!!!!!!


Customer.find_all [ "company = ?", company ]
und wenn man eine LIKE '%xx%' Abfrage erstellen möchte:
Customer.find_all [ " company LIKE ? ", '%#{company}%' ]

string arrays:
x= %w(Montag Dienstag) is short for 
y= ["Montag" ,"Dienstag"]

<%= sortable_element('listOrTableId' , :url => { :action => 'move' }) #, :update => 'test-id',:tag => 'tr',  :complete => visual_effect(:highlight, q.id))%>

<%= observe_field(:search,
	:frequency => 0.5,
	:update => :results,
	:url => { :action => :search }, 
	:loading => "Element.show('indicator_gif_id')",
	:complete => "Element.hide('indicator_gif_id')") 
	%>


/// HOW TOs  (mixed with 'good')

global functions !
put them in application.rb (ApplicationController)




Regular expressions
#substitute patterns (m=LineBreaks u=Unicode i=IgnoreCase)
a=a.gsub(/<img.*?>/mui, "")  # yeah right nice naming, suckers! 

send_file or send http response data
  send_data @person.picture, :filename => @person.filename, :type => "image/jpeg", :disposition => "inline"

require 'net/ftp'
 ftp = Net::FTP.new('ftp.netlab.co.jp') 
 ftp.login files = ftp.chdir('pub/lang/ruby/contrib')
  files = ftp.list('n*') 
  ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
   ftp.close

#reflection : 
list.class.reflect_on_all_associations

>>>>>>>regex<<<<<<<<
// greedy !!!!
puts "a[bcb]d[bebb]rerberb]w[bsdaeb]ega".scan(/\[b(.*)b/).inspect
=>cb]d[bebb]rerberb]w[bsdae

// .*? not greedy ++
puts "a[bcb]d[bebb]rerberb]w[bsdaeb]egab".scan(/\[b(.*?)b/).inspect
=> [["c"], ["e"], ["sdae"]]

#debug over ssh:
#ruby breakpointer [options] [server uri]
#ruby script/generate scaffold x // model + view!
#http://www.rubycentral.com/book/tut_modules.html modules


  require 'net/http'
    require 'uri'
    img='http://www.macdesktops.com/?res=TRUE&category=35'
      html=Net::HTTP.get URI.parse(img)

#switch cases
 def search
    @results = Search.find(params[:query])
    case @results
      when 0 then render :action=> "no_results"
      when 1 then render :action=> "show"
      when 2..10 then render :action=> "show_many"
    end
  end
  

module Action
  VERY_BAD = 0
  BAD      = 1
  def Action.sin(badness)
    # ...
  end
end

require "trig"
require "action"
##########
MIXINS
module Debug
  def whoAmI?
    "#{self.type.name} (\##{self.id}): #{self.to_s}"
  end
end
class Phonograph
  include Debug
  # ...
end
class EightTrack
  include Debug
  # ...
end
ph = Phonograph.new("West End Blues")
et = EightTrack.new("Surrealistic Pillow")
#ph.whoAmI? 	» 	"Phonograph (#537766170): West End Blues"
#et.whoAmI? 	» 	"EightTrack (#537765860): Surrealistic Pillow"
##########################33
time=5.minutes + 30.seconds ## cool !!!!!!

5.times do |i|
   File.open("temp.rb","w") { |f|
     f.puts "module Temp\ndef Temp.var() #{i}; end\nend"
   }
   load "temp.rb"
   puts Temp.var
 end
 ################
print "Enter your name: "
name = gets
#################

Argumentlisten variabler Länge
Was aber, wenn Sie eine variable Anzahl von Argumenten übergeben wollen oder mehrere Argumente mit einem einzigen Parameter auffangen wollen? Wenn Sie einen Stern vor den Namen des Parameters nach den ``normalen'' Parametern setzen, wird genau das gemacht.
def varargs(arg1, *rest)
  "Got #{arg1} and #{rest.join(', ')}"
end


y = Trig.sin(Trig::PI/4)
wrongdoing = Action.sin(Action::VERY_BAD)
# setup:
# rails <appname>
# ruby script\generate scaffold survey #!!  does the following too:
# ruby script\generate controller survey
# ruby script\generate model survey
#backward if
#def isanum=true
puts "It's not a number" if isanum.nil?

#$! variable!!
 rescue ScriptError, StandardError
    printf "ERR: %s\n", $! || 'exception raised'
#eval
eval(line).inspect

#regexp matching   & no brackets
if a =~ /^[-+]?\d+$/;
	puts "It's a number that may indicate positive or negative"
end

Does anyone know how to get an ID back, instead of a String?
@doctor = Doctor.find_by_name(params[:doctor][:name])
params[:parent][:doctor] = @doctor

#what is that?   yml intralanguage :(
#  database: verwurzelt_de_development
#  <<: *login


#Simplemost file IO:
IO.foreach("testfile") { |line| puts line }

arr = IO.readlines("testfile")

#Simple socket
require 'socket'
client = TCPSocket.open('localhost', 'finger')
client.send("oracle\n", 0)    # 0 means standard packet
puts client.readlines
client.close

#HTTP
require 'net/http'
h = Net::HTTP.new('www.pragmaticprogrammer.com', 80)
resp, data = h.get('/index.html', nil)
if resp.message == "OK"
  data.scan(/<img src="(.*?)"/) { |x| puts x }
end #get images!

#error handling:
  f = File.open("testfile")
begin
  f.each_line {|line| puts "Got #{line.dump}" }
  # .. process
  raise ArgumentError, "Name too big", caller
rescue ArgumentError
#rescue 
  # .. handle error
else
  puts "Congratulations-- no errors!"
ensure
  f.close unless f.nil?
end
#############
 # SICK : two mechanisms!!!
 def promptAndGet(prompt)
  print prompt
  res = readline.chomp
  throw :quitRequested if res == "!"
  return res
end

catch :quitRequested do
  name = promptAndGet("Name: ")
  age  = promptAndGet("Age:  ")
  sex  = promptAndGet("Sex:  ")
  # ..
  # process information
end
#############
  
require 'breakpoint'
Thread.new do
loop do
begin
breakpoint
rescue Exception
end
end
end


<script type="text/javascript" language="javascript" charset="utf-8">
// <![CDATA[
  Sortable.create('sortlist',{ghosting:false,constraint:false,hoverclass:'over',
    //onUpdate:function(sortable){alert(Sortable.serialize(sortable))},
    onChange:function(element){
	var	data=    Sortable.serialize(element.parentNode);
	var url="<%=url_for :controller=>'question',:action=>'move'%>";
	new Ajax.Request(url,{parameters:data});
    }
  });
// ]]>
</script>

Inputing non-ascii characters

My mobile phone (6600) doesn't have a Thai input method.
(You can buy a special software to do it)
After a lot of my thought experiments, I got an easy
example from my friend on this. You do a 2-level popup menu
to let people choose from the character table.
from appuifw import *

def thai_input():
    first_list = ['  '.join(thai_char[i:i+11]) for i in range(0,77,11)]
    y = popup_menu(first_list, u'select Thai char')
    if y is not None:
        x = popup_menu(thai_char[11*y:11*(y+1)], u'select Thai char')
        if x is not None:
            t.add(thai_char[11*y + x])

thai_char = [unichr(0x0e01+i) for i in range(77)]   # 77 thai characters

app.body = t = Text()
app.menu = [(u'thai', thai_input), (u'clear screen', t.clear)] 

# wait for user to exit program
import e32      
lock = e32.Ao_lock() 
app.exit_key_handler=lock.signal
lock.wait()


For other language, you can change the unicode offset (0x0e01)
and number of characters (77) to that of your language.
One requirement for this method is that the phone must be
able to display font in your language already.
(I have previously install Thai font on my 6600)
An alternative method to implement this will be manually drawing
your text (combile character from image font file).
I may do that some day.
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS