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

                    '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
                
                    Get http://www.ijg.org/files/jpegsrc.v6b.tar.gz, and then:

tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b
cp /usr/share/libtool/config.sub .
cp /usr/share/libtool/config.guess .
./configure --enable-shared --enable-static
make
sudo make install
sudo ranlib /usr/local/lib/libjpeg.a
                
                    
require 'RMagick'

maxwidth = 120
maxheight = 160
aspectratio = maxwidth.to_f / maxheight.to_f
imgfile = 'world'

pic = Magick::Image.read(imgfile + '.jpg').first
imgwidth = pic.columns
imgheight = pic.rows
imgratio = imgwidth.to_f / imgheight.to_f
imgratio > aspectratio ? scaleratio = maxwidth.to_f / imgwidth : scaleratio = maxheight.to_f / imgheight
thumb = pic.resize(scaleratio)

white_bg = Magick::Image.new(maxwidth, thumb.height)
pic = white_bg.composite(thumb, Magick::CenterGravity, Magick::OverCompositeOp)
pic.write(imgfile + '.thumb.jpg')
                
                    If we have the id for a post in <em>postid</em> and a limit of <em>num</em> and we want to find posts which share as many tags as possible with <em>postid</em>'s post, the following SQL will get you there.

SELECT p.*, COUNT(pt2.post_id) AS count FROM posts p, posts_tags pt, tags t, posts_tags pt2 WHERE pt.post_id=#{postid} AND t.id = pt.tag_id AND pt2.post_id != pt.post_id AND pt2.tag_id=pt.tag_id AND p.id = pt2.post_id GROUP BY pt2.post_id ORDER BY count DESC LIMIT #{num};")
                
                    Yet more code from Snippets itself. When you narrow down posts by tags, I only want you to see tags which are shared by other posts which also have the same current tags. This is more difficult than it sounds, and requires use of a subselect:

SELECT *, COUNT(pt.post_id) AS count FROM posts_tags pt, tags t WHERE pt.post_id IN (SELECT pt.post_id FROM posts_tags pt, tags t WHERE pt.tag_id = t.id AND (t.name IN ('rails', 'ruby')) GROUP BY pt.post_id HAVING COUNT(pt.post_id)=2) AND t.id = pt.tag_id GROUP BY pt.tag_id ORDER BY count DESC;
The first query (inside the subselect) finds all post IDs for posts which definitely contain any of the current tags. The outer query finds all OTHER tags associated with these posts, therefore we find all (and the quantity of) the tags related to the input tags.