DZone 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

Snippets

  • submit to reddit

Recent Snippets

                    
(ProtoObject withAllSubclasses asArray 
collect: [:each | each subclasses size]) asBag sortedElements
                
                    | myPen |
myPen := Pen new defaultNib: 2.
myPen up.
myPen goto: Sensor mousePoint.
myPen down.
[Sensor waitButton. Sensor yellowButtonPressed] whileFalse: 
    [Sensor redButtonPressed 
        ifTrue: [myPen goto: Sensor mousePoint]].                
                    GIFReadWriter putForm: Display onFileNamed: 'screenshot.GIF'                
                    dir := FileDirectory on: 'd:\\images'.
dir keysDo: [:name | form = Form fromBinaryStream: (dir fileNamed: name).
ImageReadWriter putForm: (form scaledToSize: 512@512) onFileNamed: 'scaled_',name;
putForm: (form scaledToSize: 80@80)onFileNamed: 'thumb_',name]                 
                    'http://some.server/dir/file' asUrl retrieveContents contentStream fileIn                
                    from http://simon.incutio.com/archive/2004/05/26/addLoadEvent

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
To add an event:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* more code to run on page load */ 
});
Tested on IE 5, 5.5 and 6 for Windows; IE 5 and Safari for Mac; Opera 7.5 and FireFox on Mac. Fails on Opera 6.                
                    This script lets you update your IP address at everydns.net

#!/usr/bin/env ruby
require 'optparse' 
require 'net/http' 
require 'cgi' 

class EveryDnsUpdater
  attr_accessor :user, :pass
  attr_reader :ip, :code, :body

  def params
    @params ||= {"ver" => "0.1"}
  end
      
  def host
    "dyn.everydns.net"
  end
  
  def query
    "/index.php?" + params.collect{ |k,v| "#{k}=#{CGI.escape(v)}"}.join('&')
  end
  
  def parse(body)
    @body   = body
    @code   = @body.scan(/Exit Code: (\d+)/i).to_s.to_i
    @ip     = @body.scan(/IP now: ([\d\.]+)/).to_s
  end
      
  def run
    Net::HTTP.start(host) do |http| 

      req = Net::HTTP::Get.new(query) 
      req.basic_auth(user, pass)
      response = http.request(req)
      case response
      when Net::HTTPSuccess
        parse(response.body)
        return @code
      else
        return response.code
      end
    end
  end
end

opts = OptionParser.new 
updater = EveryDnsUpdater.new

opts.banner = "Usage: everydns [options]"
opts.separator ""
opts.on("-u", "--user=USER", "User name") { |str| updater.user = str } 
opts.on("-p", "--pass=PASS", "Password") { |str| updater.pass = str } 
opts.on("-d", "--domain=DOMAIN", "Domain name you wish to update")  { |str| updater.params["domain"] = str } 
opts.on("-a", "--address=[IP]", "IP address you want to supply") { |str| updater.params["ip"] = str } 
opts.on_tail("-h", "--help")   { puts opts; exit } 

opts.parse(ARGV)

if ARGV.empty? or updater.user.nil? or updater.pass.nil? or updater.params["domain"].nil?
  puts opts
  exit
end

if updater.run == 0
  puts "IP address set to #{updater.ip} successfully..."
else
  puts "Not successful..."
  puts updater.body
end
                
                    
#!/usr/bin/env ruby

require 'yaml'
require 'rubygems'
require_gem 'net-ssh'

$stdout.sync = true

def help
  puts <<-USAGE
This tool allows you to conviniently deploy your projects on production
or staging servers.

  Useage:
    deploy <target>
    Please specify configuration in ~/.deployrc
    
  Example:  
    
    example ~/.deployrc:   
    
      hieraki:
        server: linux
        get: svn export svn://myserver/hieraki/trunk
        directory: /var/www/applications/hieraki
        test: RAILS_ENV=production rake

        after_test:
          - chmod 777 log/
          - chmod 666 log/*

        after_commit:
          - sudo /etc/init.d/apache reload    

  Note: 
  
    server, get and directory are required
    
    available hooks are
      - after_connect
      - after_deploy
      - after_test
      - after_commit
        
  USAGE
  exit
end

def do_exec(cmd)
  print "\n\n  #{cmd}\n    "
  
  stderr = ""
  $session.process.open( cmd ) do |cmd|
    cmd.on_exit do |p, status|
      if status == 0
        print "[done]\n" 
      else
        puts "    #{stderr}"        
        print "[failed]\n" 
        exit
      end
    end
    
    cmd.on_stderr do |p, data|
      stderr << data.gsub(/\n/, "\n    ")
    end    
    cmd.on_stdout do |p, data|
      STDOUT << data.gsub(/\n/, "\n    ")
    end                
  end  
end

# Batch jobs

def deploy
  puts      "\ndeploying"  

  print     "  creating dirs"
  do_exec   "mkdir -p #{$config['directory']}" 

  print     "  get"
  do_exec   "#{$config['get']} #{$config['deploy']}"
end

def test
  puts      "\ntesting"  
  do_exec   "cd #{$config['deploy']}; #{$config['test']}"
end

def commit
  puts      "\ncomitting"
  print     "  creating new link"
  do_exec   "ln -nfs #{$config['deploy']}/ #{$config['target']}"
end

def run_tasks(tasks)
  $config[tasks].to_a.each do |task|    
    do_exec "cd #{$config['deploy']}; #{task}" 
  end
end


app_name = ARGV[0] || help
$config = YAML::load(File.open(File.expand_path("~/.deployrc")))[app_name]

# compute deploy directory 
$config['deploy'] = $config['directory'] + "/#{Time.now.strftime("%Y%m%d-%H%M")}"
# compute target directory 
$config['target'] = $config['directory'] + "/latest"

puts "deploying #{app_name} to #{$config["server"]}"

$session = Net::SSH.start( $config["server"] )

run_tasks("after_connect")  
deploy
run_tasks("after_deploy")
test
run_tasks("after_test")
commit
run_tasks("after_commit")
puts ""
puts "success!"
                
                    Still using the delicious-py module
>>>import delicious
>>> delicious.get_userposts('dfdeshom').tags[1:]
[u'gnuplot', u'math math/culture', u'python', u'music', u'creativity', u'python', u'academia/culture advice gradschool', u'academia/culture advice gradschool', u'wordpress', u'python unicode', u'advice creativity', u'delicious', u'creativity', u'code programming tags', u'delicious', u'math/culture', u'wordpress', u'linux', u'wordpress', u'python', u'python', u'python', u'python', u'computer-algebra math number-theory python', u'php', u'haiti', u'delicious', u'haiti', u'delicious', u'creativity']
>>>
                
                    We are using python's delicious-py module

  
def get_popular_count(user="user"):
    import delicious
    notapi = delicious.DeliciousNOTAPI()

    #Get user's posts 
    user_posts = notapi.get_posts_by_user(user)

    data = '#tagID popularity\n' 
    
    #For each url, get how popular it is
    for i in range(len(user_posts)):
        data += str(i)+" "+str(len(notapi.get_posts_by_url(user_posts[i]["url"])))+'\n' 
    
    str1 = user + "-data" #file name
    data_file = file(str1,'w')
    data_file.write(data)
    data_file.close()

The resulting file will look like this:
$ less jemisa-data
#tagID popularity
0 6
1 744
2 928
3 120
4 1934
5 111
6 425
7 16
8 19
9 2
10 44
11 308
12 12
13 1
14 1
15 7
16 3
17 46
18 7
19 139
20 318
21 174
22 288
23 3
24 1
25 33
26 3
27 154