Cocktail Napkin 2009
Current Napkinbash safe_copy:
# example usage:
# create_archive $INSTALL_TARGET $BACKUPTMP
# safe_copy $BACKUPTMP $BACKUPPATH
# rm $BACKUPTMP
safe_copy() {
src=$1
destination=$2
increment=$3
if [[ -z "$3" ]]; then
increment=0
fi
if [[ ! -d "$destination" ]]; then
return 1
fi
file=$(basename $src).$increment
if [[ -f "$destination/$file" ]]; then
increment=$(( $increment + 1 ))
safe_copy $src $destination $increment
else
cp $src "$destination/$file"
fi
return 0
}Update JS Var via AJAX call
<script>
var globalVal = 'n/a';
function update_global_var() {
$.post( "/service/datetime",
{},
function(data) {
console.log(data);
var old_val = globalVal;
var new_val = data.datetime;
globalVal = new_val;
console.log('updating globalVar from', old_val, 'to', new_val);
},
"json" );
}
function check_var() { console.log('globalVar is curently:', globalVal); }
$(document).ready(function () {
console.log('beginning service calls - globalVal set to', globalVal);
setTimeout(function() { check_var(); }, 1000);
setTimeout('update_global_var()', 2000);
setTimeout(function() { check_var(); }, 6000);
setTimeout('update_global_var()', 8000);
setTimeout(function() { check_var(); }, 12000);
});
</script>Powerset Sample (would like to keep this somewhere where I can find it later)
def recursive_powerset(seq):
"""
Returns all the subsets of this set. This is a generator.
"""
if len(seq) <= 1:
yield seq
yield []
else:
for item in recursive_powerset(seq[1:]):
yield [seq[0]]+item
yield item
def gray_powerset(s):
"""
http://groups.google.com/group/comp.lang.python/browse_thread/thread/d9211cd6c65e1d3a/
"""
d = dict(zip(
(1<<i for i in range(len(s))),
(set([e]) for e in s)
))
subset = set()
yield subset
for i in range(1, 1<<len(s)):
subset = subset ^ d[i & -i]
yield subset
def kitzke_powerset(s):
l = len(s)
for i in range(2**l):
n = i
x = []
for j in range(l):
if n & 1:
x.append(s[j])
n >>= 1
#result.append(x)
yield x
def bhattacharya_powerset(s):
s = set(s)
def do_recursive(S):
if not S:
yield set([])
return
x=set([S.pop()])
for t in do_recursive(S):
yield t
yield t|x
return do_recursive(s.copy())
def xuniqueCombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xuniqueCombinations(items[i+1:],n-1):
yield [items[i]]+cc
def test():
JsonObj = simplejson.load(open(datasource))
print JsonObj['accounts'][random.choice(JsonObj['accounts'].keys())]
#compare_powersets()
test_unique_combinations(30,8)
#test_ucombo_limit()
def test_unique_combinations(set_size=10, result_size=4, time_limit=300):
t1 = time.time()
TestSet = range(set_size)
ResultSet = []
for r in xuniqueCombinations(TestSet, result_size):
ResultSet.append(r)
if time.time() - t1 > time_limit:
print 'time limit %s exceeded' % (time_limit)
break
Result = {
'time': time.time() - t1,
'result_set': len(ResultSet)
}
pprint(Result)
def test_ucombo_limit():
time_limit = 1
Result = {}
testkey = '__'
for n in range(30,31):
SubsetSizeList = range(n/2,n)
for s in SubsetSizeList:
testkey = 'xuniqueCombinations(%s,%s)' % (n,s)
print testkey
TestSet = range(n)
result_size = s
t1 = time.time()
success = True
for r in xuniqueCombinations(TestSet, result_size):
if time.time() - t1 > time_limit:
success = False
break
if success:
Result[testkey] = time.time() - t1
else:
Result[testkey] = 'fail'
pprint({'test_ucombo_limit' : Result})
def compare_powersets():
FxList = [recursive_powerset, gray_powerset, kitzke_powerset, bhattacharya_powerset]
TestSet = range(16)
Result = {}
for test_ in FxList:
n_ = test_.__name__
print 'testing %s' % (n_)
t1 = time.time()
powerset = []
for s in test_(TestSet):
powerset.append(s)
Result[n_] = {
'time': time.time() - t1,
'result_set': len(powerset)
}
pprint({'powerset comparison' : Result})UniversalCsvReader
class UniversalCsvParser:
"""
A parser that attempts to deal magically with troublesome encoding issues
and avoid errors like this:
_csv.Error: line contains NULL byte
The secret sauce:
conv_ = unicode(line, errors='ignore').replace("\0", "").encode('ascii', 'ignore')
And, no, the unicode_csv_reader found here did not work for me:
http://docs.python.org/library/csv.html#csv-examples
"""
delimiter = ','
skip_empty_lines = True
HeaderList = []
Log = []
Warnings = {}
def __init__(self, path):
self.path = path
def run(self):
RowList = self.read(self.path)
DataSet = []
for row in RowList:
DataSet .append(self.parse_row(row))
return DataSet
def parse_row(self, row):
ZipDict = dict(zip(self.HeaderList, row))
# here you can do transformations and return new dict or just return ZipDict
RowDict = {
}
return ZipDict # or RowDict
def read(self, path):
return csv.reader(self.file_to_utf8(path), delimiter=self.identify_delimiter())
def file_to_utf8(self, path):
for line in self.read_file(path):
conv_ = unicode(line, errors='ignore').replace("\0", "").encode('ascii', 'ignore')
if not self.skip_empty_lines or conv_.strip():
yield conv_
def identify_delimiter(self):
"""TO DO (csvreader's Sniffer didn't work in my first trial"""
return self.delimiter
def utf_8_encoder(self, unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8', errors='ignore')
def read_file(self, path):
"""
file-reading generator
"""
f = open(path, "rU")
for line in f:
yield line
f.close()
"""
A parser that attempts to deal magically with troublesome encoding issues
and avoid errors like this:
_csv.Error: line contains NULL byte
The secret sauce:
conv_ = unicode(line, errors='ignore').replace("\0", "").encode('ascii', 'ignore')
And, no, the unicode_csv_reader found here did not work for me:
http://docs.python.org/library/csv.html#csv-examples
"""
delimiter = ','
skip_empty_lines = True
HeaderList = []
Log = []
Warnings = {}
def __init__(self, path):
self.path = path
def run(self):
RowList = self.read(self.path)
DataSet = []
for row in RowList:
DataSet .append(self.parse_row(row))
return DataSet
def parse_row(self, row):
ZipDict = dict(zip(self.HeaderList, row))
# here you can do transformations and return new dict or just return ZipDict
RowDict = {
}
return ZipDict # or RowDict
def read(self, path):
return csv.reader(self.file_to_utf8(path), delimiter=self.identify_delimiter())
def file_to_utf8(self, path):
for line in self.read_file(path):
conv_ = unicode(line, errors='ignore').replace("\0", "").encode('ascii', 'ignore')
if not self.skip_empty_lines or conv_.strip():
yield conv_
def identify_delimiter(self):
"""TO DO (csvreader's Sniffer didn't work in my first trial"""
return self.delimiter
def utf_8_encoder(self, unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8', errors='ignore')
def read_file(self, path):
"""
file-reading generator
"""
f = open(path, "rU")
for line in f:
yield line
f.close()
logbook
http://www.atk-framework.com/
y kant tori read shaggs
jquery scroll
<?php
print $javascript->link('jcarousellite_1.0.1.min.js');
?>
<div id="text_list">
<ul>
<li>beginning</li>
</ul>
</div>
<script type="text/javascript">
$(document).ready( function() {
var TextList = [
'There has always been war between Oceania and Eastlandia',
'The only thing worse than being talked about is not being talked about',
'Between love and desire: assplode',
'Can I have another please?',
"They eff you up your mum and dad, they don't mean to but they do",
'Are you talking to me? Are you talking to me?',
'and in the end, the love you make is equal to the love you take.'
];
console.log(TextList);
$.each( TextList, function(i, item) {
console.log(item);
var $li = $('<li />').html(item);
$('#text_list').find('ul').append($li);
});
$(function() {
$('#text_list').jCarouselLite({
vertical: true,
visible: 1,
auto:2000,
speed:1000
});
});
});
</script>sample jquery json
<script type="text/javascript">
$(document).ready( function() {
var target = '#flickr_images';
var flickr_tag = 'disneyland,guest,relations';
var ajax_url = 'http://api.flickr.com/services/feeds/photos_public.gne?';
var ajax_qstr = 'tags='+flickr_tag+'&tagmode=all&format=json&jsoncallback=?';
$.getJSON( ajax_url + ajax_qstr,
function(data){
console.log(data);
$.each(data.items, function(i,item){
var $a = $('<a />').attr('href', item.link);
$("<img/>").attr("src", item.media.m).appendTo($a);
$a.appendTo(target);
if ( i == 3 ) return false;
});
});
});
</script>upgrading cake
# checkout latest $ svn co https://svn.cakephp.org/repo/trunk/cake/1.2.x.x cake_core # update latest $ cd cake_core_latest $ svn update # diff (list files only) $ diff --exclude=.svn -rq cake_core cake_core_latest # list changes $ diff --exclude=.svn -ru cake_core cake_core_latest # copy latest over master $ cp -rvf cake_core_latest/cake cake_core # check results $ diff --exclude=.svn -rq cake_core/cake cake_core_latest/cake
icons: component behavior php helper
python ungreedy
def re_ungreedy(re_, s):
r = re_.replace('%s', '(.*?)')
return re.search(r, s).groups()pigeon sketch more birds lots of pigeons
a map
Whence malt?
en bikini: http://en.wikipedia.org/wiki/File:World_Map_1689.JPG
Jackson Mystery Song? amazon youtube
$canvas = $('#sandbox');
$i = $('<iframe />');
$i.attr('src', 'http://google.com/').attr('width', '600').attr('height', '300').css('overflow', 'hidden').css('display', 'block').css('border','4px solid #ccc').css('padding','8px');
$canvas.append($i);<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^js\/?(.*)$ _js.htm?q=$1 [QSA,L]
RewriteRule ^rewrite(.*)\/?(.*)$ rewrite.php?q=$1 [QSA,L]
</IfModule>http://search.twitter.com/search?q=lastgoogle
find ~/qed/ -maxdepth 4 -name "*.conf" | xargs perl -w -i -p -e "s/VirtualHost 127.0.0.1/VirtualHost */g"
Reconfigure as Wikka Recent Changes Notifier as a handler
- enforce access through url: domain.com/wikka/$access_code/recent_changes
- add setting for $access_code
- check that url match $cron_code
- add setting for email, but default to wiki admin
- additional abuse check
- when called directly, display last
- on call, read page and parse out last_emailed.
- adding setting for max_frequency and if time() - last_emailed < $mail_no_more_than_every, exit
- upon email, edit page to include line: last_emailed=uts
- is it possible to pass additional parameters in the url? e.g. wikka/$access_code/recent_changes/3600 (for last 3600 s or 1 hr)
<?php
// handlers/page/test.php
$tpl = <<<XHTML
<div class="page">
This is a test handler. To disable, delete the file <tt>test.php</tt> from
<tt>/handlers/page/</tt> directory.
</div>
XHTML;
printf($tpl);
?>
// handlers/page/test.php
$tpl = <<<XHTML
<div class="page">
This is a test handler. To disable, delete the file <tt>test.php</tt> from
<tt>/handlers/page/</tt> directory.
</div>
XHTML;
printf($tpl);
?>
PHP Mail Configuration
Wikka Slowness: http://wikkawiki.org/ExtremeSlownessWorkaround
# copying svn dir sans svn dirs $ rsync -r --exclude=.svn /path/to/svn_dir /tmp
komodo.assertMacroVersion(2);
if (komodo.view) { komodo.view.setFocus() };
path_ = gViewMgr.currentView.document.file.path;
if ( prompt( 'current file path', path_) )
komodo.view.selection = path_;
if (komodo.view) { komodo.view.setFocus() };
path_ = gViewMgr.currentView.document.file.path;
if ( prompt( 'current file path', path_) )
komodo.view.selection = path_;
var D = {'a':1, 'b':2, 'c':1, 'd':3};
console.log('begin', D);
for ( k in D ) {
console.log('outer', k, ':', D[k]);
for ( k2 in D ) {
if ( k2 == k ) continue;
if ( D[k] != D[k2] ) continue;
console.log('removing dupe', k2, ':', D[k2] );
delete D[k2];
}
}
console.log('end', D);
console.log('begin', D);
for ( k in D ) {
console.log('outer', k, ':', D[k]);
for ( k2 in D ) {
if ( k2 == k ) continue;
if ( D[k] != D[k2] ) continue;
console.log('removing dupe', k2, ':', D[k2] );
delete D[k2];
}
}
console.log('end', D);
Page was generated in 9.3332 seconds!
Komodo Current File Path
prompt('current file path', gViewMgr.currentView.document.file.path)http://www.klenwell.com/press/2009/04/formencode-state/
http://www.phpied.com/3-ways-to-define-a-javascript-class/ / http://www.prototypejs.org/learn/class-inheritance
json class:
<script type="text/javascript">
function Speaker () {
this.type = name;
this.speak = function(message) {
alert(message);
};
}
function Machine(type) {
this.type = type;
this.Speaker = new Speaker();
this.speak = function(message) {
this.Speaker.speak(this.type + ' : ' + message);
};
}
var iPod = {
Speaker: new Speaker(),
speak: function (message) {
this.Speaker.speak(message);
}
}
var iPhone = new Machine('iPhone');
iPhone.speak('support iTunes');
iPod.speak('hey, it worked!');
</script>
function Speaker () {
this.type = name;
this.speak = function(message) {
alert(message);
};
}
function Machine(type) {
this.type = type;
this.Speaker = new Speaker();
this.speak = function(message) {
this.Speaker.speak(this.type + ' : ' + message);
};
}
var iPod = {
Speaker: new Speaker(),
speak: function (message) {
this.Speaker.speak(message);
}
}
var iPhone = new Machine('iPhone');
iPhone.speak('support iTunes');
iPod.speak('hey, it worked!');
</script>
tax calculator calculations: http://www.sacbee.com/1098/story/1627728.html
# A couple calculations # Income $30k / Car $10k Not Married: $192 -> monthly increase: $16 (2 Trips to McDonalds) Married: $192 2 Kids: $612 # Income $100k / Car $25k Not Married: $488 -> monthly: $40.67 (1 Video Game) Married: $534 2 Kids: $954 # My actual numbers are somewhere in between
windansea 02.18 pm
/* background: color image repeat attachment position */
background: #FFCC66 url("file or url name") no-repeat fixed right bottom;
background: #FFCC66 url("file or url name") no-repeat fixed right bottom;
Plato's Symposium
mysqldump dbname | ssh user@remoteserver "cat - > dbname.db"
pastebin: CakePhp Custom Pagination Methods
in case you missed 1978
perfect weather/dead oceancurrent
pastebin: Klenwell CakePhp Form Helper
python regex (I could have sworn I pasted this here before):
import re
# compile
html = "'<html>\n<head>\n<title>Title</title>\n</head>\n</html>"
regex = re.compile('<.*?>',)
result = regex.search(html)
print result.group()
# ungreedy
html = "'<html><head><title>Title</title>"
print re.search('<.*?>', html).group()
# substitution
dirty = "some alphanum and some other ^$#%&*%!"
rgx = r'[^a-zA-Z0-9]' # alphanum only!
clean = re.sub(rgx, '', dirty)
# compile
html = "'<html>\n<head>\n<title>Title</title>\n</head>\n</html>"
regex = re.compile('<.*?>',)
result = regex.search(html)
print result.group()
# ungreedy
html = "'<html><head><title>Title</title>"
print re.search('<.*?>', html).group()
# substitution
dirty = "some alphanum and some other ^$#%&*%!"
rgx = r'[^a-zA-Z0-9]' # alphanum only!
clean = re.sub(rgx, '', dirty)
CategorySpecial
[There are no comments on this page]