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 21-30 of 85 total

jaiku.py

// Set and view Jaiku statuses

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="28 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__URL__="http://snippets.dzone.com/posts/show/4223"

import sys, getopt, urllib2, xmlrpclib

import configreader

STATUS_MODE="STATUS"
VIEW_MODE="VIEW"

def set_status(settings, status):
	s=xmlrpclib.ServerProxy(settings["xmlrpcurl"])
	
	calldata={"user":settings["username"], "personal_key":settings["personalkey"], "message":status, "location":settings["location"]}
	
	try:
		s.presence.send(calldata)
	except:
		raise "Could not connect."

def view_status(settings):
	item=settings["itemdelimeter"]
	t1=settings["titledelimeter1"]
	t2=settings["titledelimeter2"]

	try:
		instream=urllib2.urlopen(
			settings["feedurlstart"]+settings["username"]+settings["feedurlend"]
		)

		for line in instream:
			if item in line:
				break

		title=instream.readline()

		instream.close()

		status=title[title.index(t1)+len(t1):title.index(t2)]

		return status

	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s [options]" % (sys.argv[0])
	print "\nWithout any options, uses status mode. Leftover args are concatenated to form message."
	print "\n-u|--username <username> specified in jaiku.conf"
	print "-p|--personal-key <key>"
	print "-l|--location <location>"
	print "-s|--status mode"
	print "-v|--view status"
	print "-c|--config <configfile>"
	print "-h|--help"

	sys.exit()

def main():
	global STATUS_MODE
	global VIEW_MODE

	systemArgs=sys.argv[1:]

	mode=STATUS_MODE

	settings={
		"config":"jaiku.conf",
		"xmlrpcurl":"http://api.jaiku.com/xmlrpc",
		"feedurlstart":"http://",
		"feedurlend":".jaiku.com/feed/atom",
		"itemdelimeter":"<entry>",
		"titledelimeter1":"<title>",
		"titledelimeter2":"</title>",
		"username":"mcandre",
		"personalkey":"",
		"location":""
	}

	optlist, args=[], []

	try:
		optlist, args=getopt.getopt(systemArgs, "u:p:l:svc:h", ["username=", "personal-key=", "location=", "status", "view", "config=", "help"])
	except e:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-u" or option=="--username":
			settings["username"]=value
		elif option=="-p" or option=="--personal-key":
			settings["personalkey"]=value
		elif option=="-l" or option=="--location":
			settings["location"]=value
		elif option=="-s" or option=="--status":
			mode=STATUS_MODE
		elif option=="-v" or option=="--view":
			mode=VIEW_MODE

	if mode==STATUS_MODE:
		if len(args)<1:
			usage()

		message=" ".join(args)

		set_status(settings, message)
	elif mode==VIEW_MODE:
		print view_status(settings)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

tiny.py

#!/usr/bin/env python

"""Converts long URLs to tiny URLs, with either tinyurl, urltea, or a custom url."""

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="22 Jun 2007 - 24 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__URL__="http://snippets.dzone.com/posts/show/4195"
__credits__="http://lateral.netmanagers.com.ar/weblog/2007/04/08.html#BB548"

import sys, getopt, urllib

import configreader

def tiny(url, settings):
	try:
		encodedurl=settings["posting url"]+urllib.urlencode({"url":url})
		instream=urllib.urlopen(encodedurl)
		tinyurl=instream.read()
		instream.close()

		if len(tinyurl)==0:
			return url

		if settings["service"]=="urltea" and len(settings["description"])>0:
				tinyurl+=settings["description delimeter"]+settings["description"]

		return tinyurl
	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s [options] <url1> <url2> <url3> ..." % (sys.argv[0])
	print "\nDefaults to urlTea unless specified in options or a config file."
	print "\n-s|--service [tinyurl|urltea]"
	print "-u|--custom-url <posting url>"
	print "-d|--description <comment> May only be used with urltea."
	print "-c|--config <configfile>"
	print "-h|--help (usage)"

	sys.exit()

def main():
	systemArgs=sys.argv[1:]
	oplist, args=[], []

	settings={
		"config":"tiny.conf",
		"service":"urltea",
		"urltea url":"http://urltea.com/api/text/?url=",
		"tinyurl url":"http://tinyurl.com/api-create.php?",
		"description delimeter":"?",
		"description":""
	}

	try:
		optlist, args=getopt.getopt(systemArgs, "s:u:d:c:h", ["service=", "custom-url=", "description=", "config=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()
		elif option=="-s" or option=="--service":
			settings["service"]=value
		elif option=="-d" or option=="--description":
			settings["description"]=value

	if settings["service"]!="urltea" and len(settings["description"])>0:
		usage()

	try:
		settings["posting url"]=settings[settings["service"]+" url"]
	except:
		usage()

	for option, value in optlist:
		if option=="-u" or option=="--custom-url":
			settings["posting url"]=value

	if len(args)<1:
		usage()

	for u in args:
		print tiny(u, settings)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

tw.py

// Sets and views Twitter status

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="17 Jun 2007 - 28 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__credits__="Based on tweetyPy (http://muffinresearch.co.uk/archives/2007/03/24/tweetypy-python-based-cli-client-for-twitter/)"
__URL__="http://snippets.dzone.com/posts/show/4150"

import sys, getopt, getpass, urllib, urllib2

import configreader

STATUS_MODE="STATUS"
VIEW_MODE="VIEW"
COMMAND_MODE="COMMAND"

COMMANDS="""Command\t\tMeaning

d username\tDirect Text
@username\tReply
follow username\tReceive updates via phone or IM
leave username\tStop following username
leave all\tStop following all friends
remove username\tRemove username from friends list
delete username\tDelete username from friends list
get username\tGet the last update from username
get\tGet the most recent updates from all friends
nudge username\tTwitter aks what the person is currently up to
whois username\tGet username's bio
add phonenumber\tSend text invite. If already a member, invite will turn into a friend request.
accept username\tAccept username as a friend
deny username\tDeny username as friend"""

def usage():
	print "Usage: %s [options]" % (sys.argv[0])
	print "\nWithout any options, uses status mode. Leftover args are concatenated to form message."
	print "\n-u|--username <username> specified in tw.conf"
	print "-s|--status mode"
	print "-v|--view status"
	print "-l|--list-commands List Twitter commands"
	print "-c|--config <configfile>"
	print "-h|--help"

	sys.exit()

def set_status(settings, status):
	auth=urllib2.HTTPPasswordMgrWithDefaultRealm()
	auth.add_password(None, settings["rootauthurl"], settings["username"], settings["password"])
	authHandler=urllib2.HTTPBasicAuthHandler(auth)
	opener=urllib2.build_opener(authHandler)

	url="http://twitter.com/statuses/update.xml"
	post=urllib.urlencode({"status":status})

	request=urllib2.Request(url, post)
	request.add_header("User-Agent", settings["useragent"])

	try:
		response=opener.open(request)
	except IOError, e:
		raise "Could not connect."

def view_status(settings):
	url="http://twitter.com/"+settings["username"]
	message=""

	statusdelimeter1=settings["statusdelimeter1"]
	statusdelimeter2=settings["statusdelimeter2"]

	try:
		instream=urllib.urlopen(url)
		for line in instream:
			if statusdelimeter1 in line:
				message=line[
					line.index(statusdelimeter1)+len(statusdelimeter1):line.index(statusdelimeter2)
				]
				break
		instream.close()

		return message
				
	except IOError, e:
		raise "Could not connect."

def main():
	global STATUS_MODE
	global VIEW_MODE
	global COMMAND_MODE
	global COMMANDS

	sysArgs=sys.argv[1:]

	mode=STATUS_MODE

	settings={
		"config":"tw.conf",
		"username":"mcandre",
		"rootauthurl":"http://twitter.com/statuses/",
		"useragent":sys.argv[0]+" "+__version__,
		"statusdelimeter1":"<p class=\"entry-title entry-content\">",
		"statusdelimeter2":"</p>"
	}

	optlist, args=[], []
	try:
		optlist, args=getopt.getopt(sysArgs, "u:svlc:h", ["username=", "status", "view", "list-commands", "config=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-u" or option=="--username":
			settings["username"]=value
		elif option=="-s" or option=="--status":
			mode=STATUS_MODE
		elif option=="-v" or option=="--view":
			mode=VIEW_MODE
		elif option=="-l" or option=="--list=commands":
			mode=COMMAND_MODE

	if mode==STATUS_MODE:
		if len(args)<1:
			usage()

		message=" ".join(args)

		settings["password"]=getpass.getpass()

		set_status(settings, message)
	elif mode==VIEW_MODE:
		print view_status(settings)
	elif mode==COMMAND_MODE:
		print COMMANDS

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

Making Columns Render with Equal Height

A problem sometimes faced by web developers is trying to get two (or more) columns in a multi-column layout to be the same height when the content is variable. Rather than using an arbitrary hardcoded value, the heights can be equalized (to the tallest one) with this script.

Assuming two columns in div tags with ids of "leftside" and "rightside" this script will set the height of the shorter to the height of the taller one. The page must be in standards compliant mode with a valid doctype or IE will mess it up in quirks mode. For longer articles and discussion visit my home site... ERT
<script type="text/javascript">
function setH()
{
   var maxH = Math.max(document.getElementById('leftside').offsetHeight,document.getElementById('rightside').offsetHeight);
   document.getElementById('leftside').style.height=maxH+'px';
   document.getElementById('rightside').style.height=maxH+'px';
}
onload=setH;
</script>

Setting Element Height Dynamically

There are times when you need to control the height of an element based on the screen size. However youcan control the user setup, and of course there are browser differences so this snippet handles browser and object detection and sets the height during page load and for any re-sizing event.

An example of the snippet in action

  var minorOffset = (document.all)? 25 : 38;
   function setHgt()
   {
      var sHGT;
      srcobj=document.getElementById('main');
      if (self.innerHeight)
      {
	   sHGT = self.innerHeight;
	}
      else
      { 
         if (document.documentElement && document.documentElement.clientHeight)
         {
	      sHGT = document.documentElement.clientHeight;
         }
         else
         {
            if (document.body)
            {
              sHGT = document.body.clientHeight;
            }
         }
      }
      sHGT=sHGT-(document.getElementById('main').offsetTop+minorOffset);
  document.getElementById('main').style.height=sHGT+"px";
   }
window.onload=setHgt;
window.onresize=setHgt;

Javascript to put a hotkey on a Web Page

// description of your code here
This page will fire an event when the key specified in the
variable key1 is pressed.

Cd&
http://www.expertsrt.com

var key1="32";
var x='';
function handler(e) 
{
  if (document.all) {
  var evnt = window.event; 
  x=evnt.keyCode;
}
else
x=e.charCode;
if (x==key1) location.href='http://www.expertsrt.com';
}
if (!document.all){
window.captureEvents(Event.KEYPRESS);
window.onkeypress=handler;
}
else
{
document.onkeypress = handler;
} 

javascript window event handling manager

I've seen a lot of window.onload managers, so I generalized it for any window event handler. This assumes prototype.
// BurntoEventManager
// http://brentfitzgerald.com/
// January 2007

var BurntoEventManager = {
    handlers: {},
    add: function(handler_name, method) {
        if(this.handlers[handler_name] == null) {
            this.handlers[handler_name] = new Array();
        }
        this.handlers[handler_name].push(method);
        
        // Now update the window event handler
        window[handler_name] = function(evt) {
            this.handlers[handler_name].each(function(m) {
                m(evt);
            }.bind(this));
        }.bind(this);
    },
    
    clear: function(handler_name) {
        this.handlers[handler_name] = null;
        window[handler_name] = function() {};
    },
    
    get: function(handler_name) {
        return this.handlers[handler_name];
    }
}

For example, consider if later on in our application we want to add an onclick handler.
BurntoEventManager.add("onclick", function(evt) { alert(evt) });

Google PageRank Ruby Checker

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# $Id: google-pr.rb,v b205c14e4ef5 2007-01-15 13:53 +0300 $
# (C) 2006-2007 under terms of LGPL v2.1 
# by Vsevolod S. Balashov <vsevolod@balashov.name>
# based on 3rd party code snippets (see comments)

require 'uri'
require 'open-uri'

module SEO

  # http://blog.outer-court.com/archive/2004_06_27_index.html#108834386239051706
  class GooglePR

    def initialize(uri)
      @uri = uri
    end

    M=0x100000000 # modulo for unsigned int 32bit(4byte)

    def m1(a,b,c,d)
      (((a+(M-b)+(M-c))%M)^(d%M))%M # mix/power mod
    end

    def i2c(i)
      [i&0xff, i>>8&0xff, i>>16&0xff, i>>24&0xff]
    end

    def c2i(s,k=0)
      ((s[k+3].to_i*0x100+s[k+2].to_i)*0x100+s[k+1].to_i)*0x100+s[k].to_i
    end

    def mix(a,b,c)
      a = a%M; b = b%M; c = c%M
      a = m1(a,b,c, c >> 13); b = m1(b,c,a, a <<  8); c = m1(c,a,b, b >> 13)
      a = m1(a,b,c, c >> 12); b = m1(b,c,a, a << 16); c = m1(c,a,b, b >>  5)
      a = m1(a,b,c, c >>  3); b = m1(b,c,a, a << 10); c = m1(c,a,b, b >> 15)
      [a, b, c]
    end

    def old_cn(iurl = 'info:' + @uri)
      a = 0x9E3779B9; b = 0x9E3779B9; c = 0xE6359A60
      len = iurl.size 
      k = 0
      while (len >= k + 12) do
        a += c2i(iurl,k); b += c2i(iurl,k+4); c += c2i(iurl,k+8)
        a, b, c = mix(a, b, c)
        k = k + 12
      end
      a += c2i(iurl,k); b += c2i(iurl,k+4); c += (c2i(iurl,k+8) << 8) + len
      a,b,c = mix(a,b,c)
      return c
    end

    def cn
      ch = old_cn
      ch = ((ch/7) << 2) | ((ch-(ch/13).floor*13)&7)
      new_url = []
      20.times { i2c(ch).each { |i| new_url << i }; ch -= 9 }
      ('6' + old_cn(new_url).to_s).to_i
    end

    def request_uri
      # http://www.bigbold.com/snippets/posts/show/1260 + _ -> %5F
      "http://toolbarqueries.google.com/search?client=navclient-auto&hl=en&ch=#{cn}&ie=UTF-8&oe=UTF-8&features=Rank&q=info:#{URI.escape(@uri, /[^-.!~*'()a-zA-Z\d]/)}"
    end
 
    def page_rank(uri = @uri)
      @uri = uri if uri != @uri
      open(request_uri) { |f| return $1.to_i if f.string =~ /Rank_1:\d:(\d+)/ }
      nil
    end

    private :m1, :i2c, :c2i, :mix, :old_cn
    attr_accessor :uri
  end

end

if __FILE__ == $0 and 1 == ARGV.size
  puts SEO::GooglePR.new(ARGV[0]).page_rank
end

Python - Very Simple Parser

// Very Simple Parser

from sgmllib import SGMLParser

import urllib

class ParserHTML(SGMLParser):

	def scrivi(self):
		self.f = open('/tmp/fileOUT.html', 'w')

	def unknown_starttag(self, tag, attrs):

		value = 0
		startTAG = '<' + tag
		
		for i in attrs:
			if(i[0].lower() == i[1].lower() and not i[0] == i[1]):
				startTAG = startTAG[:-1] + ' ' + str(i[1])
				value = 1
			else:
				startTAG += ' ' + str(i[0]) + '="' + str(i[1]) + '"'
				value = 0
		
		if(value == 1): startTAG += '"'

		startTAG += '>'
		self.f.write(startTAG + "\n")

	def handle_data(self, data):

		self.f.write(data + "\n")

	def unknown_endtag(self, tag):

		self.f.write('</' + tag + '>' + "\n")

if __name__ == '__main__':

	p = ParserHTML()
	p.scrivi()
	p.feed(open('/tmp/fileIN.html', 'r').read())

nowww!

set redirect from www.example.com to example.com for nginx web server

server {
    listen       80;
    server_name  example.com www.example.com;
    if ( $host = www.example.com ) {
        rewrite ^\/(.*)$ http://example.com/$1 permanent;
    }

    .....
}
« Newer Snippets
Older Snippets »
Showing 21-30 of 85 total