try another color:

 
try another fontsize: tiny small normal big huge
netsperience 2.x
web site design, programming, scripting, and seo/sem

dzone code snippets

Syndicate content
DZone Snippets: Store, sort and share source code, with tag goodness
Updated: 2 min 22 sec ago

Campaign contribution finder

Sat, 01/03/2009 - 03:47
// This code analyzes a dataset of more than 11,000 campaign contributions. It can be tweaked to analyze any CSV data.

import os

## Move into the directory where the database is.
os.chdir('DIRECTORYNAME')

open_file = open('FILENAME.txt', 'r')

lines = 0
person_end = 0
city_end = 0
state_end = 0
amount_end = 0
cityDict = {}

user_info = raw_input('Type a name, city or address. Partial words are ok.\n')


### Find the number of donors in a city
def find_city_number():
for line in open_file:
if line.find(user_info) >=1:
if cityDict.has_key(user_info):
cityDict[user_info] += 1
else:
cityDict[user_info] = 1

### Get the list of donations from city. Definitions break the line out by field.
def find_city_list():
open_file = open('FILENAME.txt', 'r')
for line in open_file:
person_end = (line.find(','))
person_name = line[:person_end]
city_end = (line.find(',', person_end + 1))
city_name = line[(person_end + 1):city_end]
state_end = (line.find(',', city_end + 1))
state_name = line[(city_end + 1):state_end]
amount_end = (line.find(',', state_end + 1))
amount = line[(state_end + 1):amount_end]
if line.find(user_info) >= 1:
print person_name + ';', city_name + ',', state_name + ';', '$' + amount

## Run the program, taking one city name and giving the count and list
find_city_number()
if cityDict == {}:
print 'No donors found.'
else:
print cityDict
find_city_list()

Ban by IP

Fri, 01/02/2009 - 17:28
PHP code to get user IP and compare to others in a file, and ban if there


$ip = $_SERVER['REMOTE_ADDR'];
$ipArray = preg_replace("#\r\n?|\n#","",file('IP.txt'));
foreach ($ipArray as $ipTest) {
if (substr_count($ip, $ipTest) != "0") {
header('location: http://google.com');
die();
}
}


Fastmail link with OTP

Fri, 01/02/2009 - 17:13
PHP code to read OTP from a file and create a link


$otp_file = "somefile.txt";
$trimmed = file('somefile.txt');
$otp = array_shift($trimmed);
file_put_contents($otp_file, $trimmed);
echo << Login (oriui)

Login (beta)
END;

fastmail sieve script for blackberry gmail app sync -- not quite there...

Fri, 01/02/2009 - 16:04
require ["envelope", "imapflags", "fileinto", "reject", "notify", "vacation", "regex", "relational", "comparator-i;ascii-numeric", "body", "copy"];

#NOTIFICATION: important mail is received into fastmail; notify push exchange account
if anyof(
header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "alias@myfastmail.com",
header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "gmailAccount@gmail.com",
header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "anotheraddress@fastmail.fm"
)
{
notify :method "mailto" :options ["workExchangeAccount@madeUp.com]","from","orig"] :message "$from$";
#stop; this continues for the forwarding rules and does NOT stop at this point
}
#Forwarding
#this test prevents the forward from the alias (i.e. [gmail account]@gmail.com) from being delivered twice since its in an otherwise forwarded pattern
if header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "alias@myfastmail.com"
{
stop;
}
if anyof(
header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "alias@myfastmail.com",
#header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "gmailAccount@gmail.com",
#above email is already at gmailAccount@gmail.com
header :contains ["to","cc","resent-to","X-Delivered-to","X-Remote-Delivered-To"] "anotheraddress@fastmail.fm"
)
{
#forwarding rule on gmail account is to forward all mail except for that received from fastmail forwarding address below
redirect "gmailAccount+Handheld@gmail.com";
keep;
stop;
}

How to extend methods on fly

Fri, 01/02/2009 - 15:41
Here is how i extend object methods on fly. It is very useful when doing testing and mocks, because my testing framework can create mocks for simple things like counting calls to some methods automatically without me defining all the mocks.

For you on buzzwords, you can DRY up your tests and get rid of some repeating mocks using this technique.


module Magic
class Mock
def self.method instance, method_name, &new_method
mock_alias = Class.new
(instance.methods).each do |method|
mock_alias.send(:define_method, method) do |*args|
instance.send(method, *args)
end
end
mock = Class.new(mock_alias) do
define_method(method_name, &new_method)
end
mock.new
end
end
end

# usage
hello = "hello"
mock = Magic::Mock.method(hello , :to_s) do
super + " from mock"
end
puts mock.to_s # hello from mock
puts hello.to_s # hello


So for an example use in tests:


def assert_called object, method, message = nil
calls = 0
mock = Magic::Mock.method(object, method) do
calls += 1
super
end
yield(mock)
message ||= "Method #{method} was not called during block but was expected to."
assert_equal calls, 1, message
end


Then i can do in my tests:


def test_greet_calls_bark
assert_called (Dog.new, :bark) { |dog|
dog.greet
}
end


Instead of creating mock classes (more code), thus introducing fewer bugs to my tests:)

Sql server list dbcc useroptions

Fri, 01/02/2009 - 06:19
// description of your code here


if not object_id('tempdb..#options') is null
drop table #options;
go
create table #options (setOptions varchar(128), value varchar(50));
go
insert into #options
exec('
dbcc useroptions')
go
select * from #options

Flickr tag feeds

Fri, 01/02/2009 - 01:41
Replace "${tag}" in:

http://api.flickr.com/services/feeds/photos_public.gne?tags=${tag}&format=rss_200

Autoplay YouTube SWF using API, not autoplay=1

Thu, 01/01/2009 - 23:59
You need to

1. Download SWFobject, not link to YouTube's - http://code.google.com/p/swfobject/

2. Change swfobject.embedSWF("http://www.youtube.com/v/OdqhDcAoQuc to the URL of your video

the setTimeout is very important, it will not work without it - but you may be able to set the timer to less than 5000 milliseconds


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">




YouTube Javascript API Autostart





setTimeout('myytplayer.playVideo()',5000);





You need Flash player 8+ and JavaScript enabled to view this video.


// allowScriptAccess must be set to allow the Javascript from one domain to access the swf on the youtube domain
var params = { allowScriptAccess: "always" };
// this sets the id of the object or embed tag to 'myytplayer'. You then use this id to access the swf and make calls to the player's API
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/v/OdqhDcAoQuc&border=0&enablejsapi=1&playerapiid=ytplayer",
"ytapiplayer", "425", "344", "8", null, null, params, atts);




focus to first input (greasemonkey)

Thu, 01/01/2009 - 14:17
// kakšen kmet morš bit da ne daš fokusa na input


for (i=0; document.getElementsByTagName('input').length; i++) {
if(document.getElementsByTagName[i].type == 'text') {
document.getElementsByTagName[i].focus();
exit;
}
}

Malfromed split archive fix

Wed, 12/31/2008 - 20:03
Fix a malformed split archive

Turns files name *.001, *.002, *.003 into *.r01, *.r02, *.r03

require 'fileutils'
Dir.entries(File.dirname(__FILE__)).each { FileUtils.mv(File.join(File.dirname(__FILE__), entry), File.join(File.dirname(__FILE__), entry.gsub!(/\.(0)(\d+)\z/, '.r\2')), :verbose => true) if entry[/\.(0)(\d+)\z/]}

Any date to Mysql date

Wed, 12/31/2008 - 08:22
a little helper function which parses about any date and returns the same date in MySQL date/time format


function date_to_mysql($date) {
//if $date is not numeric, assume it's in textual format
if (!is_numeric($date)) {
$date=strtotime($date);
}
return date('Y-m-d H:i:s',$date);
}

Collapse a multi-dimensional hash into a single-dimensional hash

Wed, 12/31/2008 - 06:35

#!/usr/bin/env ruby

require 'test/unit'

class Hash
def flatten_keys(newhash={}, keys=nil)
self.each do |k, v|
k = k.to_s
keys2 = keys ? keys+"."+k : k
if v.is_a?(Hash)
v.flatten_keys(newhash, keys2)
else
newhash[keys2] = v
end
end
newhash
end
end

class FlattenKeysTest < Test::Unit::TestCase
def test_with_string_keys
test_hash = {
'bar' => {
'baz' => {
'quux' => 1,
'blargh' => 2,
'zap' => 3,
'zoo' => 4
}
},
'zing' => 5
}
expected_hash = {
'bar.baz.quux' => 1,
'bar.baz.blargh' => 2,
'bar.baz.zap' => 3,
'bar.baz.zoo' => 4,
'zing' => 5
}
assert_equal expected_hash, test_hash.flatten_keys
end

def test_with_symbol_keys
test_hash = {
:bar => {
:baz => {
:quux => 1,
:blargh => 2,
:zap => 3,
:zoo => 4
}
},
:zing => 5
}
expected_hash = {
'bar.baz.quux' => 1,
'bar.baz.blargh' => 2,
'bar.baz.zap' => 3,
'bar.baz.zoo' => 4,
'zing' => 5
}
assert_equal expected_hash, test_hash.flatten_keys
end
end

Stereolabels bug snippet

Tue, 12/30/2008 - 12:38
Trying to debug a problem with stereolabels.

- Working correctly in Firefox 3
- How it looks in IE 7
- How it looks in IE 7 after tabbing through the fields




Recipient
First Name Last Name E-mail Address


just a trial this is some opensource subsonic code

Tue, 12/30/2008 - 11:19
// this is just a trial. Below is some opensource subsonic code. I just want to see how this works.


public CTestInfoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
CTestInfo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}

Beállítás m?köd? ékezetes magyar oldalhoz

Tue, 12/30/2008 - 10:11

//Weboldalakba:



//PHP-ba:

header("Content-type: text/html; charset=utf-8");
mysql_query("set names 'utf8'"); //közvetlenül db_connect után

//PHPMyAdmin:

Minden tábla és adatbázis utf8_general_ci
MySQL kapcsolat illesztése szintén utf8_general_ci

All of our employees are veteran wow gold and wow power leveling

Tue, 12/30/2008 - 08:39
Welcome to www.wowmsale.com . We are a world class wow gold store online. We supply cheap wow gold, the cheapest wow gold to our loyal and reliable customers. You may buy cheap wow gold here. There is wow gold of sale; you can buy really cheap wow gold here. We have mass available stock of gold wow on most of the servers, so that we can do a really instant way of gold wow delivery. We know what our buyers need so we offer an instant way of cheap wow gold, the cheapest wow gold delivery.

wow power leveling is our primary service, we have been in the business that wow power leveling for 4 years! You can purchase our wow power leveling service at a much lower price than any of our competitors. We don't use any Bots or Macros to wow power leveling your character. So we can ensure your account is 100% safe. All of our employees are veteran World of Warcraft players, who personally wow power leveling your character, to provide even more safety to your account. As we know, when you first start a game of World of Warcraft, you will be taken to your race's starting area. All the races except wow gold trolls and gnomes begin in a unique location. So it takes a long time to wow power leveling a powerful character for many players, for the player's energy and time are limited. So please let us do this task for you, one of our wow power leveling service for you as a full- time job other than part-time.


wow game card provide professional,special Power Leveling wow game card service for World Of Warcarft.We have built our wow game card reputation on competitive pricing,speedy delivery,and reliable, consistent customer service.Your character wow game card is primarily leveled by our highly experienced veteran players. We have extensive knowledge of the game and know the best way to level your character as fast as possible. wow game card relies on strictly enforced internal policies to safeguard customer game accounts.With our standard order processing system , guaranteed wow game card security and high quality customer service, we are your best choice to enrich your wow life.






www.wow-accounts.org offer wow account,wofld of warcraft account

Mon, 12/29/2008 - 22:00
firstmouth1230

We will contact you to do a Face-to-Face wow account wow account wow accounts wow accounts buy wow account transaction to insure the safety of the gold once we prepare it for customers, therefore please make order with the character that you play most frequently online for the transaction. If possible, please let us know your buy wow account buy wow accounts buy wow accounts world of warcraft account world of warcraft account online time for us to contact you.


wow-accounts.org offer the cheapest game gold and Powerleveling,Feel free to contact us 24 hours a day, 7 days a week live chat and email.Your Game Gold also will be delivered to you in less than 45 minutes! We strive to offer the fastest and most reliable service on the web for all your gaming needs.


I’m writing this post not to trash “World of Warcraft” (how could I judge a game I’ve ugg sundance boots ugg uk stores short ugg boots sundance ugg boots cheap ugg boots uk tall ugg boots ugg uk sale ugg boots uk ugg short chestnut metallic ugg boots ugg classic tall boot cardy ugg boots uk mini ugg boots neglected for over a year?), not to castigate those of us who foolishly pay for things we’re not using (though I think I did), but to praise Blizzard for the easy — and kind of enjoyable — process of canceling one’s “WoW” account.

Use lambda in Ruby

Mon, 12/29/2008 - 12:18
Source: Robert Sosinski » Understanding Ruby Blocks, Procs and Lambdas [robertsosinski.com]


class Array
def iterate!(code)
self.each_with_index do |n, i|
self[i] = code.call(n)
end
end
end

array_1 = [1, 2, 3, 4]
array_2 = [2, 3, 4, 5]

square = lambda { |n| n ** 2}

array_1.iterate!(square)
array_2.iterate!(square)

puts array_1.inspect
puts array_2.inspect

# => [1, 4, 9, 16]
# => [4, 9, 16, 25]


This is eactly the same code as creating a proc [dzone.com] except the statement Proc.new has been changed to lambda. Lambda is slightly more advanced than Proc, as lambda handles specific code scenarios in a more controlled manner specifically validating the number of arguments supplied and allowing code to continue past an initial nested return statement. e.g.


# example-12.rb

def generic_return(code)
one, two = 1, 2
three, four = code.call(one, two)
return "Give me a #{three} and a #{four}"
end

puts generic_return(lambda { |x, y| return x + 2, y + 2 })

puts generic_return(Proc.new { |x, y| return x + 2, y + 2 })

puts generic_return(Proc.new { |x, y| x + 2; y + 2 })

puts generic_return(Proc.new { |x, y| [x + 2, y + 2] })

# => Give me a 3 and a 4
# => *.rb:11: unexpected return (LocalJumpError)
# => Give me a 4 and a
# => Give me a 3 and a 4


Finally just to recap a Proc is a type of block however a Proc can be implemented independently from the context in which it is finally used e.g.

square = Proc.new {|n| n** 2}


Create a Proc in Ruby

Mon, 12/29/2008 - 08:48
Source: Robert Sosinski » Understanding Ruby Blocks, Procs and Lambdas [robertsosinski.com]


# example-5.rb

class Array
def iterate!(code)
self.each_with_index do |n, i|
self[i] = code.call(n)
end
end
end

array_1 = [1, 2, 3, 4]
array_2 = [2, 3, 4, 5]

square = Proc.new do |n|
n ** 2
end

array_1.iterate!(square)
array_2.iterate!(square)

puts array_1.inspect
puts array_2.inspect

# => [1, 4, 9, 16]
# => [4, 9, 16, 25]


This code is similar to creating a block in Ruby [dzone.com] however a proc is a type of re-usable block of code whereas a basic block of code is hard-wired to the object.

wow account,wow accounts,buy account,world of warcraft account

Mon, 12/29/2008 - 02:11
Lastly,firstmouth1229
wow account buy wow account buy wow accounts buy wow accounts world of warcraft account world of warcraft account power leveled accounts tend to have lower quality gear than preowned accounts. Although there is a slight price difference, the 100% guarantee more than makes up for this!

On a different note it is wow account now also advisable to steer clear of Ebay when selling Wow Gold accounts, your auction is most likely to be removed and in the worst case senario your Wow account banned altogather. There are many sites, auctions springing up where you can safely sell your Wow account. These sites are specialist Gaming Auction wow accounts sites and are quite advanced now with seller verification built in.

In my next article i will be discussing the benefits and downfalls when selling Wow Gold Updated gold farming guides have provided new fast wow accounts gathering techniques to cope up with the increased demand for cash when the passage buy wow account to Northrend finally opens.