Additions:
**Python Inheritance**
class Reveal(object):
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.__dict__)
class Yin(Reveal):
def __init__(self, yin=100):
self.yin = yin
self.lightness = True
self.darkness = False
self.balance = False
class Yan(Reveal):
def __init__(self, yan=100):
self.yan = yan
self.lightness = False
self.darkness = True
self.balance = False
class YinYan(Yin, Yan):
def __init__(self, yin, yan):
Yin.__init__(self, yin)
Yan.__init__(self, yan)
self.balance = True
yin = Yin(50)
yan = Yan(50)
yinyan = YinYan(50, 50)
print yin
print yan
print yinyan
# Prints
<Yin {'balance': False, 'yin': 50, 'lightness': True, 'darkness': False}>
<Yan {'balance': False, 'yan': 50, 'lightness': False, 'darkness': True}>
<YinYan {'balance': True, 'yin': 50, 'lightness': False, 'darkness': True, 'yan': 50}>
class Reveal(object):
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.__dict__)
class Yin(Reveal):
def __init__(self, yin=100):
self.yin = yin
self.lightness = True
self.darkness = False
self.balance = False
class Yan(Reveal):
def __init__(self, yan=100):
self.yan = yan
self.lightness = False
self.darkness = True
self.balance = False
class YinYan(Yin, Yan):
def __init__(self, yin, yan):
Yin.__init__(self, yin)
Yan.__init__(self, yan)
self.balance = True
yin = Yin(50)
yan = Yan(50)
yinyan = YinYan(50, 50)
print yin
print yan
print yinyan
# Prints
<Yin {'balance': False, 'yin': 50, 'lightness': True, 'darkness': False}>
<Yan {'balance': False, 'yan': 50, 'lightness': False, 'darkness': True}>
<YinYan {'balance': True, 'yin': 50, 'lightness': False, 'darkness': True, 'yan': 50}>
Additions:
to = 'YOUR_RECEPIENT@some_domain.com'
Deletions:
Additions:
**Send Email through Gmail with Python**
"""
Send an email programmatically through Gmail.
REFERENCES
http://snippets.dzone.com/posts/show/757
http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/
http://stackoverflow.com/questions/399129/#comment8985407_399240
"""
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
from os.path import abspath, dirname, join
SMTP_SERVER = 'smtp.gmail.com:587'
SMTP_USER = 'USER@gmail.com'
SMTP_PASS = 'PASS'
EMAIL_FROM = 'USER <%s>' % (SMTP_USER)
def send_gmail(to, subject, text, files=[]):
assert type(to) == list
assert type(files) == list
from_ = EMAIL_FROM
msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
smtp = smtplib.SMTP(SMTP_SERVER)
#smtp.set_debuglevel(1)
smtp.ehlo() # apparently this is required in python 2.5
smtp.starttls()
smtp.login(SMTP_USER, SMTP_PASS)
smtp.sendmail(from_, to, msg.as_string() )
smtp.close()
def test_email():
to = 'klenwell@gmail.com'
subject = "Python Gmail Test"
text = 'This is simply a test.'
send_gmail([to], subject, text)
print 'simple test complete'
"""
Send an email programmatically through Gmail.
REFERENCES
http://snippets.dzone.com/posts/show/757
http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/
http://stackoverflow.com/questions/399129/#comment8985407_399240
"""
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
from os.path import abspath, dirname, join
SMTP_SERVER = 'smtp.gmail.com:587'
SMTP_USER = 'USER@gmail.com'
SMTP_PASS = 'PASS'
EMAIL_FROM = 'USER <%s>' % (SMTP_USER)
def send_gmail(to, subject, text, files=[]):
assert type(to) == list
assert type(files) == list
from_ = EMAIL_FROM
msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
smtp = smtplib.SMTP(SMTP_SERVER)
#smtp.set_debuglevel(1)
smtp.ehlo() # apparently this is required in python 2.5
smtp.starttls()
smtp.login(SMTP_USER, SMTP_PASS)
smtp.sendmail(from_, to, msg.as_string() )
smtp.close()
def test_email():
to = 'klenwell@gmail.com'
subject = "Python Gmail Test"
text = 'This is simply a test.'
send_gmail([to], subject, text)
print 'simple test complete'
No Differences
Additions:
**Method Decorator**
def check_some_flag(method):
def wrapper(self, *args, **kwargs):
if not self.some_flag:
raise Exception("some_flag not set")
else:
result = method(self, *args, **kwargs)
return result
return wrapper
def check_some_flag(method):
def wrapper(self, *args, **kwargs):
if not self.some_flag:
raise Exception("some_flag not set")
else:
result = method(self, *args, **kwargs)
return result
return wrapper
Additions:
%%(python)
>>> import numpy
>>> x = [1,50,99]
>>> y = [2,1,0.5]
>>> a,b,c = numpy.polyfit(x,y,2)
>>> f = lambda x: a*x**2 + b*x + c
>>> f(1)
2.0
>>> f(20)
1.5528946272386506
>>> f(50)
1.0000000000000002
>>> f(90)
0.55435235318617249
>>> f(100)
0.49500208246563937
>>> f(99)
0.5
>>> import numpy
>>> x = [1,50,99]
>>> y = [2,1,0.5]
>>> a,b,c = numpy.polyfit(x,y,2)
>>> f = lambda x: a*x**2 + b*x + c
>>> f(1)
2.0
>>> f(20)
1.5528946272386506
>>> f(50)
1.0000000000000002
>>> f(90)
0.55435235318617249
>>> f(100)
0.49500208246563937
>>> f(99)
0.5
Additions:
[[https://www.google.com/search?hl=en&output=search&sclient=psy-ab&q=python+find+equation&btnK= python find roots of equation]]
Deletions:
Additions:
**Find Equation for Set of Points**
[[https://www.google.com/?hl=en&q=python+find+equation python find roots of equation]]
[[https://www.google.com/?hl=en&q=python+find+equation python find roots of equation]]
Additions:
Verizon Opt-Out Site: http://www.vzw.com/myprivacy
Additions:
**Somewhat Improved Wikka Installer Routine**
Deletions:
Additions:
**Somewhat Improved Wikka Installed Routined**
**IKEA Stand-Up Desks**
**IKEA Stand-Up Desks**
Deletions:
++IKEA Stand-Up Desks++
Additions:
++Somewhat Improved Wikka Installed Routined++
Diff for wikka.php:
%%
diff -r c8f8537f5e21 -r 4e091af5eacf php/wikka/wikka.php
--- a/php/wikka/wikka.php Tue Jan 17 10:01:24 2012 -0800
+++ b/php/wikka/wikka.php Tue Jan 17 11:43:38 2012 -0800
@@ -509,11 +509,15 @@
/**
* Compare versions, start installer if necessary.
+ * Wait to start installer below if this is an upgrade so we can limit access
+ * to admin users.
*/
-if (!isset($wakkaConfig['wakka_version'])) $wakkaConfig['wakka_version'] = 0;
-if ($wakkaConfig['wakka_version'] !== WAKKA_VERSION)
-{
- /**
+$is_new_install = ! isset($wakkaConfig['wakka_version']);
+$is_upgrade = $wakkaConfig['wakka_version'] !== WAKKA_VERSION;
+
+if ( $is_new_install ) {
+ $wakkaConfig['wakka_version'] = 0;
+ /**
* Start installer.
*
* Data entered by the user is submitted in $_POST, next action for the
@@ -590,6 +594,7 @@
exit;
}
+
/**
* Save session ID
*/
@@ -611,6 +616,39 @@
}
/**
+ * Check for upgrade. If so an user is admin, show setup page, else show
+ * a maintenance message to all other visitors.
+ */
+$is_admin = $wakka->IsAdmin($user);
+$at_install_step = ($_GET['installAction'] == 'writeconfig') && (isset($_POST['config']));
+$upgrade_allowed = $is_admin || $at_install_step;
+
+if ( $is_upgrade && $upgrade_allowed ) {
+ $installAction = 'default';
+ if (isset($_GET['installAction'])) $installAction = trim($_GET['installAction']); #312
+ if (file_exists('setup'.DIRECTORY_SEPARATOR.'header.php'))
+ include('setup'.DIRECTORY_SEPARATOR.'header.php'); else print '<em class="error">'.ERROR_SETUP_HEADER_MISSING.'</em>'; #89
+ if
+ (file_exists('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'))
+ include('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'); else print '<em class="error">'.ERROR_SETUP_FILE_MISSING.'</em>'; #89
+ if (file_exists('setup'.DIRECTORY_SEPARATOR.'footer.php'))
+ include('setup'.DIRECTORY_SEPARATOR.'footer.php'); else print '<em class="error">'.ERROR_SETUP_FOOTER_MISSING.'</em>'; #89
+ exit;
+}
+elseif ( $is_upgrade && $_GET['install_help'] ) {
+ print "<h2> POST,GET, SESSION variables</h2>";
+ print '<pre>';
+ var_dump($_POST);
+ var_dump($_GET);
+ var_dump($_SESSION);
+ print '</pre>';
+}
+elseif ( $is_upgrade ) {
+ die('<h2>Site Undergoing Temporary Maintenance</h2><h4>Please check back shortly.</h4>');
+}
+
+
+/**
* Run the engine.
*/
if (!isset($handler)) $handler='';
%%
++IKEA Stand-Up Desks++
Diff for wikka.php:
%%
diff -r c8f8537f5e21 -r 4e091af5eacf php/wikka/wikka.php
--- a/php/wikka/wikka.php Tue Jan 17 10:01:24 2012 -0800
+++ b/php/wikka/wikka.php Tue Jan 17 11:43:38 2012 -0800
@@ -509,11 +509,15 @@
/**
* Compare versions, start installer if necessary.
+ * Wait to start installer below if this is an upgrade so we can limit access
+ * to admin users.
*/
-if (!isset($wakkaConfig['wakka_version'])) $wakkaConfig['wakka_version'] = 0;
-if ($wakkaConfig['wakka_version'] !== WAKKA_VERSION)
-{
- /**
+$is_new_install = ! isset($wakkaConfig['wakka_version']);
+$is_upgrade = $wakkaConfig['wakka_version'] !== WAKKA_VERSION;
+
+if ( $is_new_install ) {
+ $wakkaConfig['wakka_version'] = 0;
+ /**
* Start installer.
*
* Data entered by the user is submitted in $_POST, next action for the
@@ -590,6 +594,7 @@
exit;
}
+
/**
* Save session ID
*/
@@ -611,6 +616,39 @@
}
/**
+ * Check for upgrade. If so an user is admin, show setup page, else show
+ * a maintenance message to all other visitors.
+ */
+$is_admin = $wakka->IsAdmin($user);
+$at_install_step = ($_GET['installAction'] == 'writeconfig') && (isset($_POST['config']));
+$upgrade_allowed = $is_admin || $at_install_step;
+
+if ( $is_upgrade && $upgrade_allowed ) {
+ $installAction = 'default';
+ if (isset($_GET['installAction'])) $installAction = trim($_GET['installAction']); #312
+ if (file_exists('setup'.DIRECTORY_SEPARATOR.'header.php'))
+ include('setup'.DIRECTORY_SEPARATOR.'header.php'); else print '<em class="error">'.ERROR_SETUP_HEADER_MISSING.'</em>'; #89
+ if
+ (file_exists('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'))
+ include('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'); else print '<em class="error">'.ERROR_SETUP_FILE_MISSING.'</em>'; #89
+ if (file_exists('setup'.DIRECTORY_SEPARATOR.'footer.php'))
+ include('setup'.DIRECTORY_SEPARATOR.'footer.php'); else print '<em class="error">'.ERROR_SETUP_FOOTER_MISSING.'</em>'; #89
+ exit;
+}
+elseif ( $is_upgrade && $_GET['install_help'] ) {
+ print "<h2> POST,GET, SESSION variables</h2>";
+ print '<pre>';
+ var_dump($_POST);
+ var_dump($_GET);
+ var_dump($_SESSION);
+ print '</pre>';
+}
+elseif ( $is_upgrade ) {
+ die('<h2>Site Undergoing Temporary Maintenance</h2><h4>Please check back shortly.</h4>');
+}
+
+
+/**
* Run the engine.
*/
if (!isset($handler)) $handler='';
%%
++IKEA Stand-Up Desks++
Deletions:
Additions:
IKEA Stand-Up Desks
http://news.ycombinator.com/item?id=3442809
http://www.ikea.com/us/en/catalog/products/00115992/
http://www.ikea.com/us/en/catalog/products/60111123/
http://news.ycombinator.com/item?id=3442809
http://www.ikea.com/us/en/catalog/products/00115992/
http://www.ikea.com/us/en/catalog/products/60111123/
Additions:
""<small>links and notes for later organization</small>"">>[[CocktailNapkin2011 2011 Napkin]]
[[CocktailNapkin2010 2010 Napkin]]
[[CocktailNapkin2010 2010 Napkin]]
Deletions:
%%(python)
import math, random
def roll_for(prob):
return random.random() < prob
def roll_for_100(prob):
roll = random.random() * 100
return roll < prob
print '%.2f' % (len(list(n for n in range(1000) if roll_for(.5))) / 10.0)
print '%.2f' % (len(list(n for n in range(1000) if roll_for_100(50))) / 10.0)
%%
http://stackoverflow.com/a/2774284
%%
import math
def circpts((x,y), r):
for xn in xrange(x-r, x+r+1):
ri = math.sqrt(r**2 - (xn-x)**2)
for yn in xrange(y-ri, y+ri+1):
yield xn,yn
pts = list(circpts((0,0), 3))
print pts
print [(x,y) for x,y in pts if x == 1]
# test a larger off-center circle
pts = list(circpts((2,5), 10))
area = math.pi * (10**2)
print len(pts), area
%%
http://paulbourke.net/geometry/circlearea/
%%
/*
Return TRUE if the point (x,y) is inside the circle.
Note that the edge is considered inside, see change below.
*/
int InsideCircle(double x,double y,CIRCLE c)
{
double dy,dx;
dx = c.cx - x;
dy = c.cy - y;
if (dx*dx + dy*dy <= c.r*c.r) /* Change to < to not include the edge */
return(TRUE);
else
return(FALSE);
}
%%
Webhosting.com 1and1.com URL Forwarding Thread: http://www.webhostingtalk.com/showthread.php?t=1106898
Mise:
['HHVVVH', 'HVHVVH', 'HVVHVH', 'HVVVHH', 'VHHVVH', 'VHVHVH', 'VHVVHH', 'VVHHVH', 'VVHVHH']
%%(python)
v = 'V'
h = 'H'
def order_markers():
order = {}
pos = range(6)
for p in pos:
marker = (p % 2 == 1) and h or v
if p < 2:
options = list(set(range(3)) - set(order.keys()))
else:
options = list(set(range(6)) - set(order.keys()))
place = random.choice(options)
order[place] = marker
sorder = sorted(order.items(), key=lambda t: t[0])
return [m for p,m in sorder]
orderings = []
for trial in range(100):
order = ''.join(order_markers())
orderings.append(order)
mise = list(set(orderings))
# H-last orderings
h_last = [o for o in mise if o[-1] == 'H']
%%
App Engine Pagination (with cursors):
http://www.learningtechnicalstuff.com/2010/04/pagedquery-easy-paging-using-cursors-on.html
http://stackoverflow.com/questions/3347700/datastore-cursor-paging-in-reverse-supported
http://www.gregtracy.com/revisiting-google-app-engines-pricing-changes
[[http://oscarbonilla.com/2009/05/visualizing-bayes-theorem/ Bayes Theorem]]
%%
P(A|B) = (P(B|A) * P(A)) / P(B)
P(A) -> Prob of A
P(A|B) -> Prob of A given B
%%
What this assumes: we know prob of A, B, and B given A. We want to know A given B. Applied: http://allendowney.blogspot.com/2011/10/all-your-bayes-are-belong-to-us.html
http://steshaw.org/economics-in-one-lesson/chap03p1.html
//"It was merely our old friend, the broken-window fallacy, in new clothing, and grown fat beyond recognition. This time it was supported by a whole bundle of related fallacies. It confused need with demand."//
//"To most people this seemed like an increase in total demand, as it partly was in terms of dollars of lower purchasing power. But what mainly took place was a diversion of demand to these particular products from others"//
**without diversion/need**: wealthy -> finance -> bonds (government/corp) -> demand (not need) -> GOP blockage/Corporate anxiety
**with diversion/need**: wealthy -> finance -> bonds -> need (war or commitment to social infrastructure) -> Government spending
> Some demands are more urgent than others. A marginal dollar is discretionary for the wealthy. The wealthy have the luxury of discretion, of demand. The poor have needs.
System Status in Fabric [[http://www.slideshare.net/ffunction/fabric-cuisine-and-watchdog-for-server-administration-in-python source]]
%%(python)
def sys_status():
disk_usage = run('df -kP')
mem_usage = run('cat /proc/meminfo')
cpu_usage = run('cat /proc/stat')
print 'Disk Usage, Mem Usage, CPU Usage:', disk_usage, mem_usage, cpu_usage
%%
[http://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard Filesystem Hierarchy Standard (FHS)] -> HUFHS (Home User FHS)
Load All Tests in Module
%%(python)
if __name__ == "__main__":
mod = sys.modules[globals()['__name__']]
suite = unittest.TestLoader().loadTestsFromModule(mod)
unittest.TextTestRunner(verbosity=2).run(suite)
%%
Polygon Points
%%(python)
>>> xs = [('x0','x1','x2','x3'), ('x4','x5','x6','x7')]
>>> ys = [('y0','y1','y2','y3'), ('y4','y5','y6','y7')]
>>> zip(xs,ys)
[(('x0', 'x1', 'x2', 'x3'), ('y0', 'y1', 'y2', 'y3')), (('x4', 'x5', 'x6', 'x7'), ('y4', 'y5', 'y6', 'y7'))]
%%
[[http://stackoverflow.com/questions/3593578/ matplotlib colormaps]]
dict obj
ref: http://stackoverflow.com/questions/1305532/
%%(python)
#
# Module Globals and Constants
#
data = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
def p(k,v): print 'setting', k, v, type(v)
nest = {
'y1' : {
't1' : {
'c1': 1,
'c2': [1,2,3]
},
't2' : {}
},
'y2' : {
}
}
#
# Data Structure
#
class ObjectDict(dict):
'''The recursive class for building and representing objects with.'''
seqs = tuple, list, set, frozenset
def __init__(self, obj):
for k, v in obj.iteritems():
if isinstance(v, dict):
setattr(self, k, ObjectDict(v))
elif isinstance(v, self.seqs):
vseq = []
for item in v:
if isinstance(item, dict):
vseq.append(ObjectDict(item))
else:
vseq.append(item)
setattr(self, k, vseq)
else:
setattr(self, k, v)
def __getitem__(self, val):
return self.__dict__[val]
def __repr__(self):
return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for
(k, v) in self.__dict__.iteritems()))
#
# Test
#
d = ObjectDict(data)
print d
assert d.a == 1
assert d.b.c == 2
assert d.d[1].foo == 'bar'
n = ObjectDict(nest)
print n
assert n.y1.t1.c1 == 1
assert n.y1.t1.c2 == [1,2,3]
assert n.y1.t2 == {}
%%
logarithms
~- ""logX = Y ---> e<sup>Y</sup> = X""
~- ""log<sub>X</sub>Y = Z ---> X<sup>Z</sup> = Y""
~- ""log<sub>2</sub>1024 = 10 ---> 2<sup>10</sup> = 1024""
~- http://repl.it/B4e
%%
Python 2.7.2 (default, Jul 20 2011, 02:32:18)
[GCC 4.2.1 (LLVM, Emscripten 1.5, Empythoned)] on linux2
import math
math.log.__doc__
=> 'log(x[, base])\n\nReturn the logarithm of x to the given base.\nIf the base not specified, returns the natural logarithm (base e) of x.'
math.pow(2, 10)
=> 1024.0
math.log(1024, 2)
=> 10.0
math.e
=> 2.7182818284590451
math.log(1, math.e)
=> 0.0
%%
Cron RPM
%%(python)
from random import randint
def cron_rpm(run_rate, job_rate):
"""runs per m (1000)"""
hr = 60
day = 24 * hr
tmap = {'hr': hr, 'day': day}
run_num, run_den = run_rate
job_num, job_den = job_rate
if run_den in tmap:
run_den = tmap[run_den]
if job_den in tmap:
job_den = tmap[job_den]
job_factor = float(job_den) / job_num
run_now = randint(1, int(run_den)) <= run_num * job_factor
return run_now
def test():
test_cases = [
# run_rate, job_rate, job_runs, expect
((5, 100), (1,1), 100, 5),
((1, 60), (1,3), 60, 3),
((3, 'day'), (30, 'hr'), 30*24, 3),
]
def run_test(run_rate, job_rate, runs, expect):
total = 0
for n in range(runs):
if cron_rpm(run_rate, job_rate):
total += 1
return total
for run_rate, job_rate, runs, expect in test_cases:
trials = 100
total_sum = 0
for n in range(trials):
total = run_test(run_rate, job_rate, runs, expect)
total_sum += total
avg = total_sum / float(trials)
print 'avg, expect (%s trials)' % (trials), '%.1f' % (avg), expect
test()
%%
Pyplot Example
%%(python)
# plot
import matplotlib.pyplot as pyplot
title = 'Conditional Probabilities'
xlabel = 'weeks'
ylabel = 'cond prob'
x1 = [x for x,y in first_probs]
y1 = [y for x,y in first_probs]
x2 = [x for x,y in other_probs]
y2 = [y for x,y in other_probs]
pyplot.plot(x1, y1, 'm-', label='first births')
pyplot.plot(x2, y2, 'b-', label='other births')
pyplot.title(title)
pyplot.xlabel(xlabel)
pyplot.ylabel(ylabel)
pyplot.xlim([25,50])
pyplot.legend(loc=2)
pyplot.show()
%%
[[https://www.google.com/adplanner/planning/site_profile?hl=en#siteDetails?identifier=reddit.com&lp=true www.google.com/adplanner]] disturbingly detailed informaton
python reconstructing a traceback:
%%(python)
import traceback, sys
trace_str = ''.join(traceback.format_tb(sys.exc_info()[2]))
%%
Pastebin20110628 - appswell min-tree.txt
State Machines
~- Difference between state machine and program?
Information / Entropy
~- Difference between energy, heat, radiation?
http://en.wikipedia.org/wiki/Deletionpedia
~- Only active February to September 2008
http://pastebin.com/CyxzKLSP
%%(python)
for i in range(8):
print 'left 1 << %s:' % (i), 1<<i
print 'right 2**8 >> %s:' % (i), 2**8>>i
OUTPUT:
left 1 << 0: 1
right 2**8 >> 0: 256
left 1 << 1: 2
right 2**8 >> 1: 128
left 1 << 2: 4
right 2**8 >> 2: 64
left 1 << 3: 8
right 2**8 >> 3: 32
left 1 << 4: 16
right 2**8 >> 4: 16
left 1 << 5: 32
right 2**8 >> 5: 8
left 1 << 6: 64
right 2**8 >> 6: 4
left 1 << 7: 128
right 2**8 >> 7: 2
%%
Python Decorators
%%(python)
"""
A simple demo of decorators
"""
from random import (randint, choice)
def cache_service(f):
"""simulates a cache that randomly finds data in it and then acts
accordingly"""
def wrapper():
cache = choice([True, False])
if cache:
print "cache found: will return that"
else:
print "cache not found: will call %s" % (f)
f()
return wrapper
def cache_resource(key, duration=60):
def inner_cache_data(fn):
def cacher(*args, **kwargs):
cache = choice(['cached data', False])
if cache:
print "cache found: will return that"
return cache
else:
print "cache not found: will call %s" % (fn)
data = fn(*args, **kwargs)
print "will now cache data with key %s for %ss" % (key, duration)
return data
return cacher
return inner_cache_data
@cache_service
def get_data_from_service():
print "getting data from service"
return 'data from service'
@cache_resource('resource-cache-key')
def get_data_from_resource():
print "getting data from resource"
return 'data from resource'
#
# Tests
#
for i in range(3):
print '\nrun get_data_from_service test %s' % (i)
print get_data_from_service()
for i in range(5):
print '\nrun get_data_from_resource test %s' % (i)
print 'returns: %s' % (get_data_from_resource())
%%
Arestin:
~- http://www.drugs.com/pro/arestin.html
~- http://www.arestin.com/
~- Sections
~~- Intro: not this, not that, just someone who's looked at trial results. No rec.
~~- Background: Why I Took It
~~~- Relationship with hygienist and office
~~~- History of bleeding gums: not terrible and better with improved dental hygiene
~~~- No choice
~~~- Then she presented the brochure: knew I'd been had.
~~- The Brochure
~~~- What it shows: the simple mental model: Wouldn't be surprised if Hyg believes it works.
~~~- What it hides, literally: Trial Data
~~~- What does the data show? stats (% effectiveness), real-world impact
~~- What If It Works? The Bigger Problem
~~~- 6 mos. Pocket reduced 1mm. What would it mean?
~~~- Reflexive dependency on drugs to handle problems
~~~- No discussion of alternatives: wait-and-see, increased cleaning, periodontal referral
~~- The Interface Problem: How to Reform Drug Usage in America
~~~- Trial Data
~~~- Probable Results
~~~- Cost to Consumer, Insurance, Government
~~~- Questions To Ask
~~~~- Can you explain trial results to me?
~~~~- Why do you think this will help me?
~~~~- Chance of Side effects: what does the data here mean?
~~~~- Would you take this drug if you were in my position? Would you prescribe it to your own child/partner?
~~~~- Do you receive any financial incentives that you think you should disclose?
Kindle:
~- https://kindle.amazon.com/your_highlights
ConnectBot Without Password: http://goo.gl/Mvx2F
Press: APC white screen issue
Julian Date in Python (2011.05.11)
%%
from datetime import datetime
juliandate = '%s%s' % (datetime.now().timetuple().tm_year, datetime.now().timetuple().tm_yday)
%%
More Encoding Issues (fixing encoding issue with hmac):
%%
input = unicode(special_chars).encode('utf-8')
%%
%%(python)
import hmac, sha, random
pound_sign = u'\u00A3'
cent_sign = u'\u00A2'
null_sign = u'\u0000'
random_sign = unichr(random.randint(1000,10000))
special_chars = 'derp... %s%s%s%s' % (pound_sign, cent_sign, null_sign,
random_sign)
# reproduces problem
try:
hmac_digest = hmac.new('key', special_chars, sha).hexdigest()
fail('expected exception')
except TypeError, e:
assert(str(e).find("can't encode characters") != -1)
# test unicode (ref: http://goo.gl/vJKlo)
input = unicode(special_chars).encode('utf-8')
assert(type(input) == str)
hmac_digest = hmac.new('key', input, sha).hexdigest()
print hmac_digest
%%
A test:
%%(python)
def test_encoding_normalization(self):
pound_sign = u'\u00A3'
cent_sign = u'\u00A2'
nonascii = 'derp... %s%s' % (pound_sign, cent_sign)
self.assertEqual(type(nonascii), unicode)
nonascii_str = nonascii.encode('utf-8')
nonascii_uni = nonascii_str.decode('utf-8')
ascii_str = nonascii_uni.encode('ascii', 'replace')
self.assertEqual(type(nonascii_str), str)
self.assertEqual(type(nonascii_uni), unicode)
# if default encoding is ascii, this fails
self.assertRaises(UnicodeDecodeError, unicode, nonascii_str)
self.assertRaises(UnicodeEncodeError, str, nonascii_uni)
# so to normalize either str or unicode, first decode, then encode
def normalize_utf8(input):
if type(input) == unicode:
input = input.encode('utf-8')
return input
for test_input in (nonascii_str, nonascii_uni, ascii_str):
normalized_input = normalize_utf8(test_input)
self.assertEqual(type(normalized_input), str)
# make sure no issues with string formatting
print 'string formatting: %s' % (normalized_input)
# convert utf8 str to ascii str
ascii_str = nonascii_str.decode('utf-8').encode('ascii', 'replace')
self.assertTrue(ascii_str.find('??') != -1)
%%
MYSQL: convert a squiggly (encoded) password to hex and back
%%
mysql> SELECT HEX('abc');
+------------+
| HEX('abc') |
+------------+
| 616263 |
+------------+
1 row in set (0.06 sec)
mysql> SELECT X'616263';
+-----------+
| X'616263' |
+-----------+
| abc |
+-----------+
1 row in set (0.00 sec)
%%
*[[http://news.ycombinator.com/item?id=2364369 Idle Thoughts on the Next Market Bubble]] (Hacker News comment)
*[[http://preposthumously.blogspot.com/2011/03/cocktail-purple-cloud.html Purple Cloud]]
*[[http://pongsocket.com/forum/post/376/#p376 TweetNest Forum Post]] (Fix for date offset)
[[http://www.facebook.com/album.php?aid=221580&id=575476957&l=c6b5ca1e54 A Day at the Zoo]]
*[[http://news.ycombinator.com/item?id=2090678 Why Chinese Mothers are Not Superior (from a female Chinese engineer)]] (news.ycombinator.com)
*[[http://krugman.blogs.nytimes.com/2011/01/06/the-repeal-the-senior-murdering-secret-muslim-president-act/ HR 2 (Krugman)]]
NYR: CE Francis
Additions:
print '%.2f' % (len(list(n for n in range(1000) if roll_for(.5))) / 10.0)
print '%.2f' % (len(list(n for n in range(1000) if roll_for_100(50))) / 10.0)
print '%.2f' % (len(list(n for n in range(1000) if roll_for_100(50))) / 10.0)
Deletions:
print '%.2f%%' % (len(list(n for n in range(1000) if roll_for_100(50))) / 10.0)
Additions:
import math, random
def roll_for(prob):
return random.random() < prob
def roll_for_100(prob):
roll = random.random() * 100
return roll < prob
print '%.2f%%' % (len(list(n for n in range(1000) if roll_for(.5))) / 10.0)
print '%.2f%%' % (len(list(n for n in range(1000) if roll_for_100(50))) / 10.0)
def roll_for(prob):
return random.random() < prob
def roll_for_100(prob):
roll = random.random() * 100
return roll < prob
print '%.2f%%' % (len(list(n for n in range(1000) if roll_for(.5))) / 10.0)
print '%.2f%%' % (len(list(n for n in range(1000) if roll_for_100(50))) / 10.0)
Additions:
# test a larger off-center circle
pts = list(circpts((2,5), 10))
area = math.pi * (10**2)
print len(pts), area
pts = list(circpts((2,5), 10))
area = math.pi * (10**2)
print len(pts), area
Additions:
http://stackoverflow.com/a/2774284
import math
def circpts((x,y), r):
for xn in xrange(x-r, x+r+1):
ri = math.sqrt(r**2 - (xn-x)**2)
for yn in xrange(y-ri, y+ri+1):
yield xn,yn
pts = list(circpts((0,0), 3))
print pts
print [(x,y) for x,y in pts if x == 1]
import math
def circpts((x,y), r):
for xn in xrange(x-r, x+r+1):
ri = math.sqrt(r**2 - (xn-x)**2)
for yn in xrange(y-ri, y+ri+1):
yield xn,yn
pts = list(circpts((0,0), 3))
print pts
print [(x,y) for x,y in pts if x == 1]
Additions:
http://paulbourke.net/geometry/circlearea/
/*
Return TRUE if the point (x,y) is inside the circle.
Note that the edge is considered inside, see change below.
*/
int InsideCircle(double x,double y,CIRCLE c)
{
double dy,dx;
dx = c.cx - x;
dy = c.cy - y;
if (dx*dx + dy*dy <= c.r*c.r) /* Change to < to not include the edge */
return(TRUE);
else
return(FALSE);
/*
Return TRUE if the point (x,y) is inside the circle.
Note that the edge is considered inside, see change below.
*/
int InsideCircle(double x,double y,CIRCLE c)
{
double dy,dx;
dx = c.cx - x;
dy = c.cy - y;
if (dx*dx + dy*dy <= c.r*c.r) /* Change to < to not include the edge */
return(TRUE);
else
return(FALSE);
Additions:
Webhosting.com 1and1.com URL Forwarding Thread: http://www.webhostingtalk.com/showthread.php?t=1106898
Additions:
Mise:
['HHVVVH', 'HVHVVH', 'HVVHVH', 'HVVVHH', 'VHHVVH', 'VHVHVH', 'VHVVHH', 'VVHHVH', 'VVHVHH']
v = 'V'
h = 'H'
def order_markers():
order = {}
pos = range(6)
for p in pos:
marker = (p % 2 == 1) and h or v
if p < 2:
options = list(set(range(3)) - set(order.keys()))
options = list(set(range(6)) - set(order.keys()))
place = random.choice(options)
order[place] = marker
sorder = sorted(order.items(), key=lambda t: t[0])
return [m for p,m in sorder]
orderings = []
for trial in range(100):
order = ''.join(order_markers())
orderings.append(order)
mise = list(set(orderings))
# H-last orderings
h_last = [o for o in mise if o[-1] == 'H']
['HHVVVH', 'HVHVVH', 'HVVHVH', 'HVVVHH', 'VHHVVH', 'VHVHVH', 'VHVVHH', 'VVHHVH', 'VVHVHH']
v = 'V'
h = 'H'
def order_markers():
order = {}
pos = range(6)
for p in pos:
marker = (p % 2 == 1) and h or v
if p < 2:
options = list(set(range(3)) - set(order.keys()))
options = list(set(range(6)) - set(order.keys()))
place = random.choice(options)
order[place] = marker
sorder = sorted(order.items(), key=lambda t: t[0])
return [m for p,m in sorder]
orderings = []
for trial in range(100):
order = ''.join(order_markers())
orderings.append(order)
mise = list(set(orderings))
# H-last orderings
h_last = [o for o in mise if o[-1] == 'H']
Additions:
App Engine Pagination (with cursors):
http://www.learningtechnicalstuff.com/2010/04/pagedquery-easy-paging-using-cursors-on.html
http://stackoverflow.com/questions/3347700/datastore-cursor-paging-in-reverse-supported
http://www.gregtracy.com/revisiting-google-app-engines-pricing-changes
http://www.learningtechnicalstuff.com/2010/04/pagedquery-easy-paging-using-cursors-on.html
http://stackoverflow.com/questions/3347700/datastore-cursor-paging-in-reverse-supported
http://www.gregtracy.com/revisiting-google-app-engines-pricing-changes
Additions:
What this assumes: we know prob of A, B, and B given A. We want to know A given B. Applied: http://allendowney.blogspot.com/2011/10/all-your-bayes-are-belong-to-us.html
Additions:
[[http://oscarbonilla.com/2009/05/visualizing-bayes-theorem/ Bayes Theorem]]
P(A|B) = (P(B|A) * P(A)) / P(B)
P(A) -> Prob of A
P(A|B) -> Prob of A given B
P(A|B) = (P(B|A) * P(A)) / P(B)
P(A) -> Prob of A
P(A|B) -> Prob of A given B
Additions:
**with diversion/need**: wealthy -> finance -> bonds -> need (war or commitment to social infrastructure) -> Government spending
Deletions:
Additions:
> Some demands are more urgent than others. A marginal dollar is discretionary for the wealthy. The wealthy have the luxury of discretion, of demand. The poor have needs.
Additions:
**with diversion/need**: wealthy -> finance -> bonds -> need (war or skilled workforce) -> Government spending
Deletions:
Additions:
//"It was merely our old friend, the broken-window fallacy, in new clothing, and grown fat beyond recognition. This time it was supported by a whole bundle of related fallacies. It confused need with demand."//
//"To most people this seemed like an increase in total demand, as it partly was in terms of dollars of lower purchasing power. But what mainly took place was a diversion of demand to these particular products from others"//
**without diversion/need**: wealthy -> finance -> bonds (government/corp) -> demand (not need) -> GOP blockage/Corporate anxiety
**with diversion/need**: wealthy -> finance -> bonds -> need (war) -> Government spending
//"To most people this seemed like an increase in total demand, as it partly was in terms of dollars of lower purchasing power. But what mainly took place was a diversion of demand to these particular products from others"//
**without diversion/need**: wealthy -> finance -> bonds (government/corp) -> demand (not need) -> GOP blockage/Corporate anxiety
**with diversion/need**: wealthy -> finance -> bonds -> need (war) -> Government spending
Deletions:
"To most people this seemed like an increase in total demand, as it partly was in terms of dollars of lower purchasing power. But what mainly took place was a diversion of demand to these particular products from others"
**without diversion/need: wealthy -> finance -> bonds (government/corp) -> demand (not need) -> GOP blockage/Corporate anxiety**
**with diversion/need: wealthy -> finance -> bonds -> need (war) -> Government spending**
Additions:
http://steshaw.org/economics-in-one-lesson/chap03p1.html
"It was merely our old friend, the broken-window fallacy, in new clothing, and grown fat beyond recognition. This time it was supported by a whole bundle of related fallacies. It confused need with demand."
"To most people this seemed like an increase in total demand, as it partly was in terms of dollars of lower purchasing power. But what mainly took place was a diversion of demand to these particular products from others"
**without diversion/need: wealthy -> finance -> bonds (government/corp) -> demand (not need) -> GOP blockage/Corporate anxiety**
**with diversion/need: wealthy -> finance -> bonds -> need (war) -> Government spending**
"It was merely our old friend, the broken-window fallacy, in new clothing, and grown fat beyond recognition. This time it was supported by a whole bundle of related fallacies. It confused need with demand."
"To most people this seemed like an increase in total demand, as it partly was in terms of dollars of lower purchasing power. But what mainly took place was a diversion of demand to these particular products from others"
**without diversion/need: wealthy -> finance -> bonds (government/corp) -> demand (not need) -> GOP blockage/Corporate anxiety**
**with diversion/need: wealthy -> finance -> bonds -> need (war) -> Government spending**
Additions:
System Status in Fabric [[http://www.slideshare.net/ffunction/fabric-cuisine-and-watchdog-for-server-administration-in-python source]]
def sys_status():
disk_usage = run('df -kP')
mem_usage = run('cat /proc/meminfo')
cpu_usage = run('cat /proc/stat')
print 'Disk Usage, Mem Usage, CPU Usage:', disk_usage, mem_usage, cpu_usage
def sys_status():
disk_usage = run('df -kP')
mem_usage = run('cat /proc/meminfo')
cpu_usage = run('cat /proc/stat')
print 'Disk Usage, Mem Usage, CPU Usage:', disk_usage, mem_usage, cpu_usage
Additions:
[http://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard Filesystem Hierarchy Standard (FHS)] -> HUFHS (Home User FHS)
Additions:
Load All Tests in Module
if __name__ == "__main__":
mod = sys.modules[globals()['__name__']]
suite = unittest.TestLoader().loadTestsFromModule(mod)
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == "__main__":
mod = sys.modules[globals()['__name__']]
suite = unittest.TestLoader().loadTestsFromModule(mod)
unittest.TextTestRunner(verbosity=2).run(suite)
Additions:
Polygon Points
>>> xs = [('x0','x1','x2','x3'), ('x4','x5','x6','x7')]
>>> ys = [('y0','y1','y2','y3'), ('y4','y5','y6','y7')]
>>> zip(xs,ys)
[(('x0', 'x1', 'x2', 'x3'), ('y0', 'y1', 'y2', 'y3')), (('x4', 'x5', 'x6', 'x7'), ('y4', 'y5', 'y6', 'y7'))]
>>> xs = [('x0','x1','x2','x3'), ('x4','x5','x6','x7')]
>>> ys = [('y0','y1','y2','y3'), ('y4','y5','y6','y7')]
>>> zip(xs,ys)
[(('x0', 'x1', 'x2', 'x3'), ('y0', 'y1', 'y2', 'y3')), (('x4', 'x5', 'x6', 'x7'), ('y4', 'y5', 'y6', 'y7'))]
Additions:
[[http://stackoverflow.com/questions/3593578/ matplotlib colormaps]]
Additions:
dict obj
ref: http://stackoverflow.com/questions/1305532/
# Module Globals and Constants
data = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
def p(k,v): print 'setting', k, v, type(v)
nest = {
'y1' : {
't1' : {
'c1': 1,
'c2': [1,2,3]
},
't2' : {}
},
'y2' : {
}
}
# Data Structure
class ObjectDict(dict):
'''The recursive class for building and representing objects with.'''
seqs = tuple, list, set, frozenset
def __init__(self, obj):
for k, v in obj.iteritems():
if isinstance(v, dict):
setattr(self, k, ObjectDict(v))
elif isinstance(v, self.seqs):
vseq = []
for item in v:
if isinstance(item, dict):
vseq.append(ObjectDict(item))
else:
vseq.append(item)
setattr(self, k, vseq)
setattr(self, k, v)
def __getitem__(self, val):
return self.__dict__[val]
def __repr__(self):
return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for
(k, v) in self.__dict__.iteritems()))
# Test
d = ObjectDict(data)
print d
assert d.a == 1
assert d.b.c == 2
assert d.d[1].foo == 'bar'
n = ObjectDict(nest)
print n
assert n.y1.t1.c1 == 1
assert n.y1.t1.c2 == [1,2,3]
assert n.y1.t2 == {}
ref: http://stackoverflow.com/questions/1305532/
# Module Globals and Constants
data = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
def p(k,v): print 'setting', k, v, type(v)
nest = {
'y1' : {
't1' : {
'c1': 1,
'c2': [1,2,3]
},
't2' : {}
},
'y2' : {
}
}
# Data Structure
class ObjectDict(dict):
'''The recursive class for building and representing objects with.'''
seqs = tuple, list, set, frozenset
def __init__(self, obj):
for k, v in obj.iteritems():
if isinstance(v, dict):
setattr(self, k, ObjectDict(v))
elif isinstance(v, self.seqs):
vseq = []
for item in v:
if isinstance(item, dict):
vseq.append(ObjectDict(item))
else:
vseq.append(item)
setattr(self, k, vseq)
setattr(self, k, v)
def __getitem__(self, val):
return self.__dict__[val]
def __repr__(self):
return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for
(k, v) in self.__dict__.iteritems()))
# Test
d = ObjectDict(data)
print d
assert d.a == 1
assert d.b.c == 2
assert d.d[1].foo == 'bar'
n = ObjectDict(nest)
print n
assert n.y1.t1.c1 == 1
assert n.y1.t1.c2 == [1,2,3]
assert n.y1.t2 == {}
Additions:
~- ""logX = Y ---> e<sup>Y</sup> = X""
Deletions:
Additions:
~- ""logX = Y ---> e<sup>Z</sup> = Y""
~- ""log<sub>2</sub>1024 = 10 ---> 2<sup>10</sup> = 1024""
~- ""log<sub>2</sub>1024 = 10 ---> 2<sup>10</sup> = 1024""
Deletions:
Additions:
~- ""log<sub>X</sub>Y = Z ---> X<sup>Z</sup> = Y""
Deletions:
Additions:
~- ""log<sub>X</sub>Y = Z"" ---> ""X<sup>Z</sup> = Y""
Deletions:
Additions:
~- ""log<sub>X</sub>Y = Z"" -> ""X<sup>Z</sup> = Y""
Additions:
~- ""log<sub>2</sub>1024 = 10""
Deletions:
Additions:
~- ""log<sub>2</sub>1024 = 10
Additions:
logarithms
~- http://repl.it/B4e
Python 2.7.2 (default, Jul 20 2011, 02:32:18)
[GCC 4.2.1 (LLVM, Emscripten 1.5, Empythoned)] on linux2
import math
math.log.__doc__
=> 'log(x[, base])\n\nReturn the logarithm of x to the given base.\nIf the base not specified, returns the natural logarithm (base e) of x.'
math.pow(2, 10)
=> 1024.0
math.log(1024, 2)
=> 10.0
math.e
=> 2.7182818284590451
math.log(1, math.e)
=> 0.0
~- http://repl.it/B4e
Python 2.7.2 (default, Jul 20 2011, 02:32:18)
[GCC 4.2.1 (LLVM, Emscripten 1.5, Empythoned)] on linux2
import math
math.log.__doc__
=> 'log(x[, base])\n\nReturn the logarithm of x to the given base.\nIf the base not specified, returns the natural logarithm (base e) of x.'
math.pow(2, 10)
=> 1024.0
math.log(1024, 2)
=> 10.0
math.e
=> 2.7182818284590451
math.log(1, math.e)
=> 0.0
Additions:
Cron RPM
def cron_rpm(run_rate, job_rate):
if cron_rpm(run_rate, job_rate):
def cron_rpm(run_rate, job_rate):
if cron_rpm(run_rate, job_rate):
Deletions:
def _rpm(run_rate, job_rate):
if _rpm(run_rate, job_rate):
Additions:
Cron RMP
from random import randint
def _rpm(run_rate, job_rate):
"""runs per m (1000)"""
hr = 60
day = 24 * hr
tmap = {'hr': hr, 'day': day}
run_num, run_den = run_rate
job_num, job_den = job_rate
if run_den in tmap:
run_den = tmap[run_den]
if job_den in tmap:
job_den = tmap[job_den]
job_factor = float(job_den) / job_num
run_now = randint(1, int(run_den)) <= run_num * job_factor
return run_now
def test():
test_cases = [
# run_rate, job_rate, job_runs, expect
((5, 100), (1,1), 100, 5),
((1, 60), (1,3), 60, 3),
((3, 'day'), (30, 'hr'), 30*24, 3),
]
def run_test(run_rate, job_rate, runs, expect):
total = 0
for n in range(runs):
if _rpm(run_rate, job_rate):
total += 1
return total
for run_rate, job_rate, runs, expect in test_cases:
trials = 100
total_sum = 0
for n in range(trials):
total = run_test(run_rate, job_rate, runs, expect)
total_sum += total
avg = total_sum / float(trials)
print 'avg, expect (%s trials)' % (trials), '%.1f' % (avg), expect
test()
from random import randint
def _rpm(run_rate, job_rate):
"""runs per m (1000)"""
hr = 60
day = 24 * hr
tmap = {'hr': hr, 'day': day}
run_num, run_den = run_rate
job_num, job_den = job_rate
if run_den in tmap:
run_den = tmap[run_den]
if job_den in tmap:
job_den = tmap[job_den]
job_factor = float(job_den) / job_num
run_now = randint(1, int(run_den)) <= run_num * job_factor
return run_now
def test():
test_cases = [
# run_rate, job_rate, job_runs, expect
((5, 100), (1,1), 100, 5),
((1, 60), (1,3), 60, 3),
((3, 'day'), (30, 'hr'), 30*24, 3),
]
def run_test(run_rate, job_rate, runs, expect):
total = 0
for n in range(runs):
if _rpm(run_rate, job_rate):
total += 1
return total
for run_rate, job_rate, runs, expect in test_cases:
trials = 100
total_sum = 0
for n in range(trials):
total = run_test(run_rate, job_rate, runs, expect)
total_sum += total
avg = total_sum / float(trials)
print 'avg, expect (%s trials)' % (trials), '%.1f' % (avg), expect
test()
Additions:
Pyplot Example
# plot
import matplotlib.pyplot as pyplot
title = 'Conditional Probabilities'
xlabel = 'weeks'
ylabel = 'cond prob'
x1 = [x for x,y in first_probs]
y1 = [y for x,y in first_probs]
x2 = [x for x,y in other_probs]
y2 = [y for x,y in other_probs]
pyplot.plot(x1, y1, 'm-', label='first births')
pyplot.plot(x2, y2, 'b-', label='other births')
pyplot.title(title)
pyplot.xlabel(xlabel)
pyplot.ylabel(ylabel)
pyplot.xlim([25,50])
pyplot.legend(loc=2)
pyplot.show()
# plot
import matplotlib.pyplot as pyplot
title = 'Conditional Probabilities'
xlabel = 'weeks'
ylabel = 'cond prob'
x1 = [x for x,y in first_probs]
y1 = [y for x,y in first_probs]
x2 = [x for x,y in other_probs]
y2 = [y for x,y in other_probs]
pyplot.plot(x1, y1, 'm-', label='first births')
pyplot.plot(x2, y2, 'b-', label='other births')
pyplot.title(title)
pyplot.xlabel(xlabel)
pyplot.ylabel(ylabel)
pyplot.xlim([25,50])
pyplot.legend(loc=2)
pyplot.show()
Additions:
python reconstructing a traceback:
Additions:
[[https://www.google.com/adplanner/planning/site_profile?hl=en#siteDetails?identifier=reddit.com&lp=true www.google.com/adplanner]] disturbingly detailed informaton
Additions:
import traceback, sys
trace_str = ''.join(traceback.format_tb(sys.exc_info()[2]))
trace_str = ''.join(traceback.format_tb(sys.exc_info()[2]))
Additions:
State Machines
~- Difference between state machine and program?
Information / Entropy
~- Difference between energy, heat, radiation?
http://en.wikipedia.org/wiki/Deletionpedia
~- Only active February to September 2008
~- Difference between state machine and program?
Information / Entropy
~- Difference between energy, heat, radiation?
http://en.wikipedia.org/wiki/Deletionpedia
~- Only active February to September 2008
Deletions:
Additions:
Pastebin20110628 - appswell min-tree.txt
Additions:
[[w20110626 w20110626]]
Deletions:
Additions:
w20110626
Additions:
http://pastebin.com/CyxzKLSP
Additions:
for i in range(8):
print 'left 1 << %s:' % (i), 1<<i
print 'right 2**8 >> %s:' % (i), 2**8>>i
OUTPUT:
left 1 << 0: 1
right 2**8 >> 0: 256
left 1 << 1: 2
right 2**8 >> 1: 128
left 1 << 2: 4
right 2**8 >> 2: 64
left 1 << 3: 8
right 2**8 >> 3: 32
left 1 << 4: 16
right 2**8 >> 4: 16
left 1 << 5: 32
right 2**8 >> 5: 8
left 1 << 6: 64
right 2**8 >> 6: 4
left 1 << 7: 128
right 2**8 >> 7: 2
print 'left 1 << %s:' % (i), 1<<i
print 'right 2**8 >> %s:' % (i), 2**8>>i
OUTPUT:
left 1 << 0: 1
right 2**8 >> 0: 256
left 1 << 1: 2
right 2**8 >> 1: 128
left 1 << 2: 4
right 2**8 >> 2: 64
left 1 << 3: 8
right 2**8 >> 3: 32
left 1 << 4: 16
right 2**8 >> 4: 16
left 1 << 5: 32
right 2**8 >> 5: 8
left 1 << 6: 64
right 2**8 >> 6: 4
left 1 << 7: 128
right 2**8 >> 7: 2
Additions:
Python Decorators
"""
A simple demo of decorators
"""
from random import (randint, choice)
def cache_service(f):
"""simulates a cache that randomly finds data in it and then acts
accordingly"""
def wrapper():
cache = choice([True, False])
if cache:
print "cache found: will return that"
else:
print "cache not found: will call %s" % (f)
f()
return wrapper
def cache_resource(key, duration=60):
def inner_cache_data(fn):
def cacher(*args, **kwargs):
cache = choice(['cached data', False])
if cache:
print "cache found: will return that"
return cache
else:
print "cache not found: will call %s" % (fn)
data = fn(*args, **kwargs)
print "will now cache data with key %s for %ss" % (key, duration)
return data
return cacher
return inner_cache_data
@cache_service
def get_data_from_service():
print "getting data from service"
return 'data from service'
@cache_resource('resource-cache-key')
def get_data_from_resource():
print "getting data from resource"
return 'data from resource'
#
# Tests
#
for i in range(3):
print '\nrun get_data_from_service test %s' % (i)
print get_data_from_service()
for i in range(5):
print '\nrun get_data_from_resource test %s' % (i)
print 'returns: %s' % (get_data_from_resource())
"""
A simple demo of decorators
"""
from random import (randint, choice)
def cache_service(f):
"""simulates a cache that randomly finds data in it and then acts
accordingly"""
def wrapper():
cache = choice([True, False])
if cache:
print "cache found: will return that"
else:
print "cache not found: will call %s" % (f)
f()
return wrapper
def cache_resource(key, duration=60):
def inner_cache_data(fn):
def cacher(*args, **kwargs):
cache = choice(['cached data', False])
if cache:
print "cache found: will return that"
return cache
else:
print "cache not found: will call %s" % (fn)
data = fn(*args, **kwargs)
print "will now cache data with key %s for %ss" % (key, duration)
return data
return cacher
return inner_cache_data
@cache_service
def get_data_from_service():
print "getting data from service"
return 'data from service'
@cache_resource('resource-cache-key')
def get_data_from_resource():
print "getting data from resource"
return 'data from resource'
#
# Tests
#
for i in range(3):
print '\nrun get_data_from_service test %s' % (i)
print get_data_from_service()
for i in range(5):
print '\nrun get_data_from_resource test %s' % (i)
print 'returns: %s' % (get_data_from_resource())
Additions:
~~~- Relationship with hygienist and office
~~~- History of bleeding gums: not terrible and better with improved dental hygiene
~~~- No choice
~~~- Then she presented the brochure: knew I'd been had.
~~~- What it shows: the simple mental model: Wouldn't be surprised if Hyg believes it works.
~~~- What it hides, literally: Trial Data
~~~- What does the data show? stats (% effectiveness), real-world impact
~~- What If It Works? The Bigger Problem
~~~- 6 mos. Pocket reduced 1mm. What would it mean?
~~~- Reflexive dependency on drugs to handle problems
~~~- No discussion of alternatives: wait-and-see, increased cleaning, periodontal referral
~~~~- Chance of Side effects: what does the data here mean?
~~~- History of bleeding gums: not terrible and better with improved dental hygiene
~~~- No choice
~~~- Then she presented the brochure: knew I'd been had.
~~~- What it shows: the simple mental model: Wouldn't be surprised if Hyg believes it works.
~~~- What it hides, literally: Trial Data
~~~- What does the data show? stats (% effectiveness), real-world impact
~~- What If It Works? The Bigger Problem
~~~- 6 mos. Pocket reduced 1mm. What would it mean?
~~~- Reflexive dependency on drugs to handle problems
~~~- No discussion of alternatives: wait-and-see, increased cleaning, periodontal referral
~~~~- Chance of Side effects: what does the data here mean?
Deletions:
Additions:
Arestin:
~- http://www.drugs.com/pro/arestin.html
~- http://www.arestin.com/
~- Sections
~~- Intro: not this, not that, just someone who's looked at trial results. No rec.
~~- Background: Why I Took It
~~- The Brochure
~~- Trial Data
~~- The Interface Problem: How to Reform Drug Usage in America
~~~- Trial Data
~~~- Probable Results
~~~- Cost to Consumer, Insurance, Government
~~~- Questions To Ask
~~~~- Can you explain trial results to me?
~~~~- Why do you think this will help me?
~~~~- Would you take this drug if you were in my position? Would you prescribe it to your own child/partner?
~~~~- Do you receive any financial incentives that you think you should disclose?
~- http://www.drugs.com/pro/arestin.html
~- http://www.arestin.com/
~- Sections
~~- Intro: not this, not that, just someone who's looked at trial results. No rec.
~~- Background: Why I Took It
~~- The Brochure
~~- Trial Data
~~- The Interface Problem: How to Reform Drug Usage in America
~~~- Trial Data
~~~- Probable Results
~~~- Cost to Consumer, Insurance, Government
~~~- Questions To Ask
~~~~- Can you explain trial results to me?
~~~~- Why do you think this will help me?
~~~~- Would you take this drug if you were in my position? Would you prescribe it to your own child/partner?
~~~~- Do you receive any financial incentives that you think you should disclose?
Additions:
Kindle:
~- https://kindle.amazon.com/your_highlights
~- https://kindle.amazon.com/your_highlights
Additions:
ConnectBot Without Password: http://goo.gl/Mvx2F
Press: APC white screen issue
Press: APC white screen issue
Additions:
Julian Date in Python (2011.05.11)
Deletions:
Additions:
Julian Date in Python
from datetime import datetime
juliandate = '%s%s' % (datetime.now().timetuple().tm_year, datetime.now().timetuple().tm_yday)
from datetime import datetime
juliandate = '%s%s' % (datetime.now().timetuple().tm_year, datetime.now().timetuple().tm_yday)
Additions:
A test:
def test_encoding_normalization(self):
pound_sign = u'\u00A3'
cent_sign = u'\u00A2'
nonascii = 'derp... %s%s' % (pound_sign, cent_sign)
self.assertEqual(type(nonascii), unicode)
nonascii_str = nonascii.encode('utf-8')
nonascii_uni = nonascii_str.decode('utf-8')
ascii_str = nonascii_uni.encode('ascii', 'replace')
self.assertEqual(type(nonascii_str), str)
self.assertEqual(type(nonascii_uni), unicode)
# if default encoding is ascii, this fails
self.assertRaises(UnicodeDecodeError, unicode, nonascii_str)
self.assertRaises(UnicodeEncodeError, str, nonascii_uni)
# so to normalize either str or unicode, first decode, then encode
def normalize_utf8(input):
if type(input) == unicode:
input = input.encode('utf-8')
return input
for test_input in (nonascii_str, nonascii_uni, ascii_str):
normalized_input = normalize_utf8(test_input)
self.assertEqual(type(normalized_input), str)
# make sure no issues with string formatting
print 'string formatting: %s' % (normalized_input)
# convert utf8 str to ascii str
ascii_str = nonascii_str.decode('utf-8').encode('ascii', 'replace')
self.assertTrue(ascii_str.find('??') != -1)
def test_encoding_normalization(self):
pound_sign = u'\u00A3'
cent_sign = u'\u00A2'
nonascii = 'derp... %s%s' % (pound_sign, cent_sign)
self.assertEqual(type(nonascii), unicode)
nonascii_str = nonascii.encode('utf-8')
nonascii_uni = nonascii_str.decode('utf-8')
ascii_str = nonascii_uni.encode('ascii', 'replace')
self.assertEqual(type(nonascii_str), str)
self.assertEqual(type(nonascii_uni), unicode)
# if default encoding is ascii, this fails
self.assertRaises(UnicodeDecodeError, unicode, nonascii_str)
self.assertRaises(UnicodeEncodeError, str, nonascii_uni)
# so to normalize either str or unicode, first decode, then encode
def normalize_utf8(input):
if type(input) == unicode:
input = input.encode('utf-8')
return input
for test_input in (nonascii_str, nonascii_uni, ascii_str):
normalized_input = normalize_utf8(test_input)
self.assertEqual(type(normalized_input), str)
# make sure no issues with string formatting
print 'string formatting: %s' % (normalized_input)
# convert utf8 str to ascii str
ascii_str = nonascii_str.decode('utf-8').encode('ascii', 'replace')
self.assertTrue(ascii_str.find('??') != -1)
No Differences
Additions:
hmac_digest = hmac.new('key', input, sha).hexdigest()
Deletions:
Additions:
More Encoding Issues (fixing encoding issue with hmac):
%%(python)
import hmac, sha, random
pound_sign = u'\u00A3'
cent_sign = u'\u00A2'
null_sign = u'\u0000'
random_sign = unichr(random.randint(1000,10000))
special_chars = 'derp... %s%s%s%s' % (pound_sign, cent_sign, null_sign,
random_sign)
# reproduces problem
try:
hmac_digest = hmac.new('key', special_chars, sha).hexdigest()
fail('expected exception')
except TypeError, e:
assert(str(e).find("can't encode characters") != -1)
# test unicode (ref: http://goo.gl/vJKlo)
input = unicode(special_chars).encode('utf-8')
assert(type(input) == str)
hmac_digest = hmac.new('user', input, sha).hexdigest()
print hmac_digest
%%(python)
import hmac, sha, random
pound_sign = u'\u00A3'
cent_sign = u'\u00A2'
null_sign = u'\u0000'
random_sign = unichr(random.randint(1000,10000))
special_chars = 'derp... %s%s%s%s' % (pound_sign, cent_sign, null_sign,
random_sign)
# reproduces problem
try:
hmac_digest = hmac.new('key', special_chars, sha).hexdigest()
fail('expected exception')
except TypeError, e:
assert(str(e).find("can't encode characters") != -1)
# test unicode (ref: http://goo.gl/vJKlo)
input = unicode(special_chars).encode('utf-8')
assert(type(input) == str)
hmac_digest = hmac.new('user', input, sha).hexdigest()
print hmac_digest
Additions:
MYSQL: convert a squiggly (encoded) password to hex and back
%%
mysql> SELECT HEX('abc');
+------------+
| HEX('abc') |
+------------+
| 616263 |
+------------+
1 row in set (0.06 sec)
mysql> SELECT X'616263';
+-----------+
| X'616263' |
+-----------+
| abc |
+-----------+
1 row in set (0.00 sec)
%%
%%
mysql> SELECT HEX('abc');
+------------+
| HEX('abc') |
+------------+
| 616263 |
+------------+
1 row in set (0.06 sec)
mysql> SELECT X'616263';
+-----------+
| X'616263' |
+-----------+
| abc |
+-----------+
1 row in set (0.00 sec)
%%
Additions:
*[[http://news.ycombinator.com/item?id=2364369 Idle Thoughts on the Next Market Bubble]] (Hacker News comment)
Additions:
*[[http://preposthumously.blogspot.com/2011/03/cocktail-purple-cloud.html Purple Cloud]]
*[[http://pongsocket.com/forum/post/376/#p376 TweetNest Forum Post]] (Fix for date offset)
*[[http://pongsocket.com/forum/post/376/#p376 TweetNest Forum Post]] (Fix for date offset)
Deletions:
* [[http://pongsocket.com/forum/post/376/#p376 TweetNest Forum Post]] (Fix for date offset)
Additions:
* [[http://preposthumously.blogspot.com/2011/03/cocktail-purple-cloud.html Purple Cloud]]
Additions:
* [[http://pongsocket.com/forum/post/376/#p376 TweetNest Forum Post]] (Fix for date offset)
Additions:
[[http://www.facebook.com/album.php?aid=221580&id=575476957&l=c6b5ca1e54 A Day at the Zoo]]
Additions:
*[[http://news.ycombinator.com/item?id=2090678 Why Chinese Mothers are Not Superior (from a female Chinese engineer)]] (news.ycombinator.com)
*[[http://krugman.blogs.nytimes.com/2011/01/06/the-repeal-the-senior-murdering-secret-muslim-president-act/ HR 2 (Krugman)]]
*[[http://krugman.blogs.nytimes.com/2011/01/06/the-repeal-the-senior-murdering-secret-muslim-president-act/ HR 2 (Krugman)]]
Deletions:
Additions:
[[http://krugman.blogs.nytimes.com/2011/01/06/the-repeal-the-senior-murdering-secret-muslim-president-act/ HR 2 (Krugman)]]
Deletions:
Additions:
http://krugman.blogs.nytimes.com/2011/01/06/the-repeal-the-senior-murdering-secret-muslim-president-act/
Additions:
NYR: CE Francis
Additions:
""<small>links and notes for later organization</small>"">>[[CocktailNapkin2010 2010 Napkin]]
[[CocktailNapkin2009 2009 Napkin]]
[[CocktailNapkin2009 2009 Napkin]]
Deletions:
Emotibot: \m/(><)\m/
[[http://www.google.com/images?q=241543903&um=1&ie=UTF-8&source=og&sa=N&hl=en&tab=wi&biw=1366&bih=643 241543903]]
Twitter Bot Bracketology
NYR: Create a profile online for the person you want to be in the New Year, and be that person next year. (C. E. Francis)
Restaurant Templates, Medical Office Templates
[[http://goo.gl/y48DK TIL]] How much warning we'd have if a killer asteroid were bearing down on Earth...
[[http://www.reddit.com/r/fffffffuuuuuuuuuuuu/comments/eia8p/sarah_and_satan_slay_salmon_down_by_the_seashore/ salmon]]
Enabled cron for wiki on new vps
http://upload.wikimedia.org/wikipedia/en/b/bd/Sports_Illustrated_Miracle_on_Ice_cover.jpg
A [[http://i.imgur.com/hVSy6.jpg meme]]: [[http://media.syracuse.com/post-standard/photo/sarah-palin-cca83c184f28f369_large.jpg 1]] [[http://twitter.com/SarahPalinUSA/status/8564233180545024 2]] [[http://twitter.com/ha_satan/status/8567572337262593 3]] [[http://www.cathedralgrove.eu/pictures/01-4-spawned-b.jpg 4]]
Updating WordPress: http://codex.wordpress.org/Updating_WordPress
Python list.get(n):
%%
list_get = lambda l,n: len(l) > n and l[n]
l = [0,1,2,3]
print list_get(l,0)
print list_get(l,3)
print list_get(l,4)
%%
Twitter Search API
~- wget -O- http://search.twitter.com/search.json?q=hi
~- https://github.com/liris/tweepy/commit/831ec87dd476cc177f13a7cb37484e16086d8786
~- http://groups.google.com/group/tweepy/browse_thread/thread/205ba6965fc50e07#
app engine [[http://code.google.com/appengine/docs/python/taskqueue/overview.html task queues]]
php int to hash (for ids):
%%
<?php
function int_to_hash($int, $set_key='limited') {
$CodesetList = array(
'full' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'limited' => 'abcdefghijklmnopqrstuvwxyz',
);
$pad = 100000;
$codeset = $CodesetList['limited'];
if ( isset($CodesetList[$set_key]) ) {
$codeset = $CodesetList[$set_key];
}
$hash = '';
$base = strlen($codeset);
$int += $pad;
while ($int > 0) {
$hash = substr($codeset, ($int % $base), 1) . $hash;
$int = floor($int/$base);
}
return $hash;
}
$TestSet = array(1,2,10,100,1000,10000,100000,999999,1000000);
print '<table>';
foreach ( $TestSet as $i ) {
printf('<tr><td>%s</td><td>%s</td></tr>', $i, int_to_hash($i));
}
print '</table>';
%%
mysql: "group by most recent"
That is: group results of a query such that only the most recent row of each group is returned
ref: http://www.artfulsoftware.com/infotree/queries.php?&bw=920#101
%%
# NOTE: this has not yet been tested
SELECT *
FROM (
SELECT *
FROM searches
WHERE terms = 'foo'
ORDER BY updated DESC
) AS s
LEFT JOIN results AS r ON r.id = s.result_id
GROUP BY result_id;
%%
python nltk unit test
%%
#!/usr/bin/python
"""
http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html
"""
import unittest
import nltk
import sys, os
from os.path import dirname, exists, join, abspath
from datetime import date
#
# set base dir
#
base_marker = "__base__" # add this file to base dir
def find_base(base=dirname(__file__)):
if exists(join(base, base_marker)):
return base
if abspath(base) == '/':
raise Exception("Can't find project base! I was expecting it to be ../ or ../../.")
return find_base(join(base, '..'))
sys.path.append(find_base())
class TestTagging_5_1(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testSimplePosTagger(self):
text = nltk.word_tokenize("And now for something completely different")
pos_tags = nltk.pos_tag(text)
self.assertEqual(pos_tags[2], ('for', 'IN'))
#print pos_tags
test_case_list = [TestTagging_5_1]
# main
if __name__ == "__main__":
for case in test_case_list:
suite = unittest.TestLoader().loadTestsFromTestCase(case)
unittest.TextTestRunner(verbosity=2).run(suite)
%%
[[http://freakonomics.blogs.nytimes.com/2010/08/09/what-do-you-want-to-hear-from-nassim-nicholas-taleb/comment-page-1/?apage=3#comments freakonomics blog NNT]]
bash pid example
%%
function start() {
if [[ -e $PID_FILE ]]; then
echo "server already running"
echo "if not running, try deleting pid file $PID_FILE"
exit 1
fi
paster serve development.ini &
PID=$!
sleep 1
echo $PID > $PID_FILE
echo 'server started'
}
function stop() {
if [[ ! -e $PID_FILE ]]; then
echo "pid file $PID_FILE not found"
echo "try 'ps aux' to stop manually"
exit 1
fi
PID=`cat $PID_FILE`
kill $PID
rm $PID_FILE
echo 'server stopped'
}
%%
bash find base: %%BASE=$(dirname $(readlink -fn $0))/..%%
parchment style: http://rlv.zcache.com/shakespeare_quotes_calendar-p1580846210289528122vxoc_400.jpg
[[http://groups.google.com/group/google-appengine-python/browse_thread/thread/1210c05bb37cb1be# app engine cron question]]
""<h5 id="nltk_meter">nltk example</h5>""http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html#a-pronouncing-dictionary %%(python)
import nltk
#pdl = nltk.corpus.cmudict.entries()
pd = nltk.corpus.cmudict.dict()
def meter(pron):
return ''.join([str(int(bool(int(c)))) for p in pron for c in p if c.isdigit()])
def get_meter_list(m):
return [w for w, p in pdl if meter(p) == m]
#print len(get_meter_list('0'))
#print len(get_meter_list('1'))
def tokenize(sent):
return [w.strip().lower() for w in sent.split(' ')]
def scan(line):
m = []
for w in tokenize(line):
m.append(meter(pd.get(w)[0]))
return ''.join(m)
sent = 'A rose is a rose is a rose is a rose'
print scan(sent)
%%
""<h5 id="python_buffer_capture">python buffer capture (assign stdout to a variable)</h5>""%%
class BufferTestCase(unittest.TestCase):
def openBuffer(self):
import StringIO, sys
self.old_buffer = sys.stdout
sys.stdout = self.new_buffer = StringIO.StringIO()
return self.old_buffer
def closeBuffer(self):
buffer_content = self.new_buffer.getvalue()
sys.stdout = self.old_buffer
self.new_buffer.close()
return buffer_content
def testBuffer(self):
self.openBuffer()
print 'hello'
buffer = self.closeBuffer()
self.assertEqual(buffer, 'hello\n')
%%
python string diff:
%%
from difflib import Differ
d = Differ()
print '\n'.join(list(d.compare(app_output, expect)))
%%
google group question: [[http://groups.google.com/group/google-appengine-python/browse_thread/thread/ca1b6838bc68d64a/5be4288579bc5a77?q=klenwell#5be4288579bc5a77 serve atom through appengine]]
python:
%%
import re
def re_ungreedy(re_, s):
r = re_.replace('%s', '(.*?)')
return re.search(r, s).groups()
re_ = "<h2>%s</h2>"
H2List = re_ungreedy(re_, '<h2>one</h2><h2>two</h2>')
%%
python debugger: ""<tt>import pdb; pdb.set_trace()</tt>""
php safe query builder
%%
function safe_sql($sqlf, $ParamList) {
$SafeParamList = array();
foreach ( $ParamList as $value ) {
$SafeParamList[] = mysql_real_escape_string($value);
}
$SprintfArgList = array_merge(array($sqlf), $SafeParamList);
return call_user_func_array('sprintf', $SprintfArgList);
}
%%
PEAR HTTP_Request2 [[http://pear.php.net/manual/en/package.http.http-request2.intro.php docs]] [[http://pear.php.net/package/HTTP_Request2/docs/latest/HTTP_Request2/HTTP_Request2.html api]]
%%
<?php
/*
HTTP_Request2 Demo
Lib File Tree
kw_pear\
HTTP\
Request2\
Request2.php
Net\
URL2.php
PEAR\
Exception.php
PEAR.php
*/
$wwwd = dirname(dirname(__FILE__));
$peard = sprintf('%s/%s', $wwwd, 'kw_pear');
$path_ext = implode(PATH_SEPARATOR, array(get_include_path(),
$peard));
# imports
ini_set('include_path', $path_ext);
require_once 'HTTP/Request2.php';
$UrlList = array(
'ok' => 'http://pear.php.net/package/HTTP_Request2/docs',
'404' => 'http://pear.php.net/package/HTTP_Request2/docs/null',
'fail' => 'bad url'
);
$TestList = array_keys($UrlList);
$test = $TestList[array_rand($TestList)];
$url = $UrlList[$test];
$Client = new HTTP_Request2();
$Client->setMethod(HTTP_Request2::METHOD_GET);
$Client->setUrl($url);
try {
$Response = $Client->send();
$code = $Response->getStatus();
$code_class = floor($Response->getStatus() / 100);
}
catch (HTTP_Request2_Exception $e) {
trigger_error(sprintf('http exception: %s',
$e->getMessage()), E_USER_ERROR);
}
if ( $code_class == 2 ) {
$output = htmlspecialchars($Response->getBody());
}
else {
$output = sprintf('unexpected response [%s]: %s',
$Response->getStatus(),
$Response->getReasonPhrase());
}
printf('<h4>test: %s</h4><pre>%s</pre>', $test, $output);
%%
copy with exclude: ""<tt>rsync -rv --exclude=.svn source/* dest</tt>""
wikka update page function:
%%
function update_page($page_name, $page_body, $WikkaObj) {
$updatef = "UPDATE %s SET latest='N' WHERE tag='%s'";
$insertf = "INSERT INTO %s SET tag='%s', body='%s', owner='%s', user='%s', note='%s', time=NOW(), latest='Y'";
$note = 'auto updating page';
$user = '(system)';
$table_prefix = $WikkaObj->GetConfigValue('table_prefix');
$table_name = sprintf('%spages', $table_prefix);
$page_name = mysql_real_escape_string($page_name);
$page_body = mysql_real_escape_string($page_body);
if ( $WikkaObj->existsPage($page_name, $table_prefix) ) {
# set all other revisions to old
$is_updated = $WikkaObj->Query(sprintf($updatef, $table_name, $page_name));
}
# add new revision
return $WikkaObj->Query( sprintf( $insertf,
$table_name,
$page_name,
$page_body,
'(Public)',
$user,
$note ));
%%
To call a script, you can make it as handler and put it at (as of 1.1.6.2) the directory named handlers/page/, ie like handlers/page/cron.changemail.php [[http://wikkawiki.org/RecentChangesNotifier?show_comments=1#comments source]]
%%
function log() {
datestamp=$(date "+%Y-%m-%d %H:%M:%S")
printf "[%s] %s\n" "$datestamp" "$1"
}
CACHE_FILE_COUNT=$(find /tmp -type f | wc -l)
if [ $CACHE_FILE_COUNT -gt 0 ]; then
log "$CACHE_FILE_COUNT files found in /tmp"
else
log "no files found in /tmp"
fi
%%
Office Hacks: during ethnic holidays, go up to people at random and ask if they have any plans. (e.g.: week before passover, ask Chinese co-worker: "so do you have any Passover plans this weekend?")
Against the [[http://corneredcat.com/Ethics/civilization.aspx Gun is Civilization Argument]]: Pastebin20100226
Pattern Request Page: jquery json ajax request with cakephp
[[http://news.ycombinator.com/threads?id=klenwell ycombo]]
[[http://i.imgur.com/OAvqY.jpg fly bomber]] (it's supafly)
[[http://www.youtube.com/watch?v=IKmCCIjgY4E classic olympic fail]]
[[http://groups.google.com/group/gdata-python-client-library-contributors/browse_thread/thread/eaa1bb7aecca54a7 gdata python question on google groups]]
[[http://images.google.com/imgres?imgurl=http://gregcookland.com/journal/uploaded_images/picComteRizzoli-766773.jpg&imgrefurl=http://gregcookland.com/journal/2008_06_15_archive.html&usg=__USS6LoobgDc3pWmwX-xN6gNekmI=&h=320&w=400&sz=29&hl=en&start=5&um=1&itbs=1&tbnid=Ey-NAsHfo6f9VM:&tbnh=99&tbnw=124&prev=/images%3Fq%3Dzaha%2Bhadid%2Byoung%26hl%3Den%26sa%3DG%26um%3D1 curious]]
copying DB in php
%%(php)
function _switch_database($new_db) {
$Dbo = ConnectionManager::getDataSource("default");
$old_db = $Dbo->config['database'];
$Dbo->reconnect(array('database'=>$new_db));
return $old_db;
}
function _copy_database($db, $new_db) {
$Dbo = ConnectionManager::getDataSource("default");
# get tables
$sql_show_tables_ = 'SHOW TABLES IN %s';
$extract_pattern = sprintf('{n}.TABLE_NAMES.Tables_in_%s', $db);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, $extract_pattern);
# create new database
$sql = sprintf('CREATE DATABASE %s', $new_db);
$Dbo->query($sql);
# copy tables
$sql1_t = 'CREATE TABLE %s.%s LIKE %s.%s';
$sql2_t = 'INSERT INTO %s.%s SELECT * FROM %s.%s';
foreach ( $TableList as $table ) {
$sql1 = sprintf($sql1_t, $new_db, $table, $db, $table);
$sql2 = sprintf($sql2_t, $new_db, $table, $db, $table);
$Dbo->query($sql1);
$Dbo->query($sql2);
}
# test table lists
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList1 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $new_db));
$TableList2 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$new_db");
if ( array_diff($TableList1, $TableList2) ) {
trigger_error('table lists in new db dows not match old', E_USER_WARNING);
return 0;
}
$this->Log_[] = "all tables in $db copied to $new_db";
# test query: count all records and compare
$old_db_count = 0;
$new_db_count = 0;
foreach ( $TableList as $table ) {
$sql_ = 'SELECT COUNT(*) as count_ FROM %s.%s';
$OldDb = $Dbo->query(sprintf($sql_, $db, $table));
$NewDb = $Dbo->query(sprintf($sql_, $new_db, $table));
$old_db_count += $OldDb[0][0]['count_'];
$new_db_count += $NewDb[0][0]['count_'];
}
$rand_table = $TableList[array_rand($TableList)];
if ( $old_db_count != $new_db_count ) {
$mt_ = 'record count for new db (%s) and old db (%s) does not match';
trigger_error(sprintf($mt_, $new_db_count, $old_db_count), E_USER_WARNING);
return 0;
}
else {
$mt_ = 'record count for new db (%s) and old db (%s)';
$this->Log_[] = sprintf($mt_, $new_db_count, $old_db_count);
return 1;
}
}
%%
php encoding tests
requires http://hsivonen.iki.fi/php-utf8/php-utf8.tar.gz
%%(php)
<?php
require('utf8.inc');
$char = 'Ü';
$h_char = htmlentities($char);
$utf8 = htmlspecialchars($char, ENT_QUOTES, 'UTF-8');
$h_utf8 = htmlentities($utf8);
$uni_char = utf8ToUnicode($char);
$data = array(
'$char' => $char,
'$h_char - htmlentities($char)' => $h_char,
'$utf8 - htmlspecialchars($char,ENT_QUOTES,\'UTF-8\')' =>
$utf8,
'htmlspecialchars(\'Ü\',ENT_QUOTES,\'UTF-8\')' =>
htmlspecialchars('Ü', ENT_QUOTES, 'UTF-8'),
'$h_utf8 - htmlentities($utf8)' =>
$h_utf8,
'strlen($char)' => strlen($char),
'strlen($h_char)' => strlen($h_char),
'strlen($utf8)' => strlen($utf8),
'strlen($h_utf8)' => strlen($h_utf8),
'ord($char)' => ord($char),
'ord($utf8)' => ord($utf8),
'utf8ToUnicode($char)' => $uni_char,
'dechex(ord($char))' => dechex(ord($char)),
'sprintf(\'&#x%s;\', dechex(ord($char)))' =>
sprintf('&#x%s;', dechex(ord($char))),
'sprintf(\'&#x%s;\', ord($char))' =>
sprintf('&#x%s;', ord($char)),
'sprintf(\'&#%s;\', $uni_char[0])' =>
sprintf('&#%s;', $uni_char[0]),
'sprintf("&#x%s;", dechex($uni_char[0]))' =>
sprintf("&#x%s;", dechex($uni_char[0])),
'iconv("UTF-8","ISO-8859-1//TRANSLIT",$char)' =>
iconv("UTF-8","ISO-8859-1//TRANSLIT",$char),
);
$xhtml = <<<XHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>sandbox</title></head>
<body>
<pre>
%s
</pre>
</body>
</html>
XHTML;
$charset = 'UTF-8'; #'ISO-8859-1';
header( 'Content-type: text/html; charset='.$charset );
printf($xhtml, print_r($data,1));
var_dump($char);
var_dump($h_char);
var_dump($utf8);
var_dump($h_utf8);
%%
jquery quiz
%%
== jQuiz: jQuirks ==
A short quiz on jQuery behavior.
===1. What will these lines of code produce?===
<code><pre>
var Test1El1 = $('div#Test1El1');
var Test1El2 = $('div').attr('id', 'Test1El2');
var Test1El3 = $('<div id="Test1El3" />');
console.log(Test1El1);
console.log(Test1El2);
console.log(Test1El3);
</pre></code>
===2. What will be the output of the code below?===
<code><pre>
var Test2El1 = $('<div id="Test2El1" />');
$(document.body).append(Test2El1);
var elid = Test2El1Test2El1.attr('id');
var Test2El2 = $(elid);
console.log(Test2El1);
console.log(elid);
console.log(Test2El2);
</pre></code>
===3. True or False===
<code><pre>
var id_ = 'test3id';
$('<div id="' + id_ + '" />').appendTo(document.body);
var Test3El1 = document.getElementById(id_);
var Test3El2 = $('#'+id_);
console.log(Test3El1.id == Test3El2.id);
</pre></code>
===4. True or False===
<code><pre>
var Test4El1 = $('<div id="Test4El" />').appendTo(document.body);
var Test4El2 = $(Test4El1);
console.log(Test4El1 == Test4El2);
console.log(Test4El1.attr('id') == Test4El2.attr('id'));
</pre></code>
===Given a document with the following table code, answer the next 2 questions:===
<code><pre>
<table id="Test5Table">
<tr id="Test5Tr1"><td>cell1</td><td>cell2</td></tr>
<tr id="Test5Tr2"><td>cell1</td><td>cell2</td></tr>
</table>
var Test5Table = $('<table id="Test5Table"><tr id="tr1"><td>cell1</td><td>cell2</td></tr><tr id="tr2"><td>cell1</td><td>cell2</td></tr></table>');
$(document.body).append(Test5Table);
</pre></code>
====5. What will the value of TableRows[0] be below?====
<code><pre>
var Test5Table = $('table#Test5Table');
var TableRows = Test5Table.find('tr');
console.log(TableRows[0].attr('id'));
</pre></code>
====6. What will the value of RowIds[0] be below?====
<code><pre>
var Test5Table = $('table#Test5Table');
var TableRows = Test5Table.find('tr');
var RowIds = [];
TableRows.each( function(i, El) {
RowIds.push(El.attr('id'));
});
console.log(RowIds[0]);
</pre></code>
===7. What will the value of FindEl be below?===
<code><pre>
// build and add element to our document
var elid = 'formbid-0.field';
var NewDiv = $('<div id="'+elid+'" />').text(elid);
$(document.body).append(NewDiv);
var jqid = NewDiv.attr('id');
var FindEl = $(document.body).find('#'+jqid); // note # sign
console.log(jqid, FindEl);
</pre></code>
<div style="display:none;">Answer:
<code><pre>
jesc = jqid.replace('.', '\\.');
var FindEl = $(document.body).find('#'+jesc);
console.log(jesc, FindEl);
</pre></code>
</div>
%%
**music on-demand**
[[http://www.reddit.com/r/programming/comments/aq59o/for_those_of_you_who_dont_know_about_it_firebug/c0iuayh this]] + http://www.dizzler.com/ + http://getfirebug.com/net.html
some cakephp code
%%
function render($action=NULL, $layout=NULL, $file=NULL) {
if ( $action == null ) {
$action = $this->view_action;
}
$output = parent::render($action, $layout, $file);
return $output;
}
function index()
{
$m = 'null';
if ( isset($this->params['pass'][0]) ) {
$m = $this->params['pass'][0];
}
#debug($this->params);
#debug($m);
if ( method_exists($this, $m) ) {
$this->view_action = sprintf('/journal/%s', $m);
return $this->$m();
}
else {
$this->set('error', 'page_not_found');
}
}
%%
Additions:
Emotibot: \m/(><)\m/
Additions:
[[http://www.google.com/images?q=241543903&um=1&ie=UTF-8&source=og&sa=N&hl=en&tab=wi&biw=1366&bih=643 241543903]]
Additions:
""<small>links and notes for later organization</small>"">>[[CocktailNapkin2009 2009 Napkin]]
[[CocktailQuestions Questions for Strangers]]>>
Twitter Bot Bracketology
NYR: Create a profile online for the person you want to be in the New Year, and be that person next year. (C. E. Francis)
Restaurant Templates, Medical Office Templates
[[CocktailQuestions Questions for Strangers]]>>
Twitter Bot Bracketology
NYR: Create a profile online for the person you want to be in the New Year, and be that person next year. (C. E. Francis)
Restaurant Templates, Medical Office Templates
Deletions:
[[CocktailNapkin2009 2009 Napkin]]
[[CocktailQuestions Questions for Strangers]]
Additions:
[[http://goo.gl/y48DK TIL]] How much warning we'd have if a killer asteroid were bearing down on Earth...
Deletions:
Additions:
[[http://goo.gl/y48DK TIL]] How much warning...
Additions:
[[http://www.reddit.com/r/fffffffuuuuuuuuuuuu/comments/eia8p/sarah_and_satan_slay_salmon_down_by_the_seashore/ salmon]]
Additions:
Enabled cron for wiki on new vps
Additions:
A [[http://i.imgur.com/hVSy6.jpg meme]]: [[http://media.syracuse.com/post-standard/photo/sarah-palin-cca83c184f28f369_large.jpg 1]] [[http://twitter.com/SarahPalinUSA/status/8564233180545024 2]] [[http://twitter.com/ha_satan/status/8567572337262593 3]] [[http://www.cathedralgrove.eu/pictures/01-4-spawned-b.jpg 4]]
Deletions:
Additions:
http://upload.wikimedia.org/wikipedia/en/b/bd/Sports_Illustrated_Miracle_on_Ice_cover.jpg
Additions:
A meme: [[http://media.syracuse.com/post-standard/photo/sarah-palin-cca83c184f28f369_large.jpg 1]] [[http://twitter.com/SarahPalinUSA/status/8564233180545024 2]] [[http://twitter.com/ha_satan/status/8567572337262593 3]] [[http://www.cathedralgrove.eu/pictures/01-4-spawned-b.jpg 4]]
Deletions:
Additions:
A meme: [[http://media.syracuse.com/post-standard/photo/sarah-palin-cca83c184f28f369_large.jpg 1]] [[http://twitter.com/SarahPalinUSA/status/8564233180545024 2]] [[http://twitter.com/ha_satan/status/8567572337262593 3]] [[http://media.washingtonpost.com/wp-dyn/content/photo/2007/06/26/PH2007062601922.jpg 4]]
Additions:
Updating WordPress: http://codex.wordpress.org/Updating_WordPress
Deletions:
Additions:
Updating Wordpress: http://codex.wordpress.org/Updating_WordPress
Additions:
Python list.get(n):
list_get = lambda l,n: len(l) > n and l[n]
l = [0,1,2,3]
print list_get(l,0)
print list_get(l,3)
print list_get(l,4)
list_get = lambda l,n: len(l) > n and l[n]
l = [0,1,2,3]
print list_get(l,0)
print list_get(l,3)
print list_get(l,4)
Additions:
~- http://groups.google.com/group/tweepy/browse_thread/thread/205ba6965fc50e07#
Additions:
Twitter Search API
~- wget -O- http://search.twitter.com/search.json?q=hi
~- https://github.com/liris/tweepy/commit/831ec87dd476cc177f13a7cb37484e16086d8786
~- wget -O- http://search.twitter.com/search.json?q=hi
~- https://github.com/liris/tweepy/commit/831ec87dd476cc177f13a7cb37484e16086d8786
Additions:
SpecialReading
Additions:
app engine [[http://code.google.com/appengine/docs/python/taskqueue/overview.html task queues]]
Additions:
php int to hash (for ids):
function int_to_hash($int, $set_key='limited') {
$CodesetList = array(
'full' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'limited' => 'abcdefghijklmnopqrstuvwxyz',
$pad = 100000;
$codeset = $CodesetList['limited'];
if ( isset($CodesetList[$set_key]) ) {
$codeset = $CodesetList[$set_key];
$hash = '';
$base = strlen($codeset);
$int += $pad;
while ($int > 0) {
$hash = substr($codeset, ($int % $base), 1) . $hash;
$int = floor($int/$base);
return $hash;
$TestSet = array(1,2,10,100,1000,10000,100000,999999,1000000);
print '<table>';
foreach ( $TestSet as $i ) {
printf('<tr><td>%s</td><td>%s</td></tr>', $i, int_to_hash($i));
print '</table>';
function int_to_hash($int, $set_key='limited') {
$CodesetList = array(
'full' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'limited' => 'abcdefghijklmnopqrstuvwxyz',
$pad = 100000;
$codeset = $CodesetList['limited'];
if ( isset($CodesetList[$set_key]) ) {
$codeset = $CodesetList[$set_key];
$hash = '';
$base = strlen($codeset);
$int += $pad;
while ($int > 0) {
$hash = substr($codeset, ($int % $base), 1) . $hash;
$int = floor($int/$base);
return $hash;
$TestSet = array(1,2,10,100,1000,10000,100000,999999,1000000);
print '<table>';
foreach ( $TestSet as $i ) {
printf('<tr><td>%s</td><td>%s</td></tr>', $i, int_to_hash($i));
print '</table>';
Additions:
mysql: "group by most recent"
That is: group results of a query such that only the most recent row of each group is returned
ref: http://www.artfulsoftware.com/infotree/queries.php?&bw=920#101
# NOTE: this has not yet been tested
SELECT *
FROM (
SELECT *
FROM searches
WHERE terms = 'foo'
ORDER BY updated DESC
) AS s
LEFT JOIN results AS r ON r.id = s.result_id
GROUP BY result_id;
That is: group results of a query such that only the most recent row of each group is returned
ref: http://www.artfulsoftware.com/infotree/queries.php?&bw=920#101
# NOTE: this has not yet been tested
SELECT *
FROM (
SELECT *
FROM searches
WHERE terms = 'foo'
ORDER BY updated DESC
) AS s
LEFT JOIN results AS r ON r.id = s.result_id
GROUP BY result_id;
Additions:
python nltk unit test
#!/usr/bin/python
"""
http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html
"""
import unittest
import sys, os
from os.path import dirname, exists, join, abspath
from datetime import date
#
# set base dir
#
base_marker = "__base__" # add this file to base dir
def find_base(base=dirname(__file__)):
if exists(join(base, base_marker)):
return base
if abspath(base) == '/':
raise Exception("Can't find project base! I was expecting it to be ../ or ../../.")
return find_base(join(base, '..'))
sys.path.append(find_base())
class TestTagging_5_1(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testSimplePosTagger(self):
text = nltk.word_tokenize("And now for something completely different")
pos_tags = nltk.pos_tag(text)
self.assertEqual(pos_tags[2], ('for', 'IN'))
#print pos_tags
test_case_list = [TestTagging_5_1]
# main
if __name__ == "__main__":
for case in test_case_list:
suite = unittest.TestLoader().loadTestsFromTestCase(case)
unittest.TextTestRunner(verbosity=2).run(suite)
#!/usr/bin/python
"""
http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html
"""
import unittest
import sys, os
from os.path import dirname, exists, join, abspath
from datetime import date
#
# set base dir
#
base_marker = "__base__" # add this file to base dir
def find_base(base=dirname(__file__)):
if exists(join(base, base_marker)):
return base
if abspath(base) == '/':
raise Exception("Can't find project base! I was expecting it to be ../ or ../../.")
return find_base(join(base, '..'))
sys.path.append(find_base())
class TestTagging_5_1(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testSimplePosTagger(self):
text = nltk.word_tokenize("And now for something completely different")
pos_tags = nltk.pos_tag(text)
self.assertEqual(pos_tags[2], ('for', 'IN'))
#print pos_tags
test_case_list = [TestTagging_5_1]
# main
if __name__ == "__main__":
for case in test_case_list:
suite = unittest.TestLoader().loadTestsFromTestCase(case)
unittest.TextTestRunner(verbosity=2).run(suite)
Additions:
[[http://freakonomics.blogs.nytimes.com/2010/08/09/what-do-you-want-to-hear-from-nassim-nicholas-taleb/comment-page-1/?apage=3#comments freakonomics blog NNT]]
Additions:
bash pid example
function start() {
if [[ -e $PID_FILE ]]; then
echo "server already running"
echo "if not running, try deleting pid file $PID_FILE"
exit 1
fi
paster serve development.ini &
PID=$!
sleep 1
echo $PID > $PID_FILE
echo 'server started'
function stop() {
if [[ ! -e $PID_FILE ]]; then
echo "pid file $PID_FILE not found"
echo "try 'ps aux' to stop manually"
exit 1
fi
PID=`cat $PID_FILE`
kill $PID
rm $PID_FILE
echo 'server stopped'
function start() {
if [[ -e $PID_FILE ]]; then
echo "server already running"
echo "if not running, try deleting pid file $PID_FILE"
exit 1
fi
paster serve development.ini &
PID=$!
sleep 1
echo $PID > $PID_FILE
echo 'server started'
function stop() {
if [[ ! -e $PID_FILE ]]; then
echo "pid file $PID_FILE not found"
echo "try 'ps aux' to stop manually"
exit 1
fi
PID=`cat $PID_FILE`
kill $PID
rm $PID_FILE
echo 'server stopped'
Additions:
bash find base: %%BASE=$(dirname $(readlink -fn $0))/..%%
Additions:
parchment style: http://rlv.zcache.com/shakespeare_quotes_calendar-p1580846210289528122vxoc_400.jpg
Additions:
[[http://groups.google.com/group/google-appengine-python/browse_thread/thread/1210c05bb37cb1be# app engine cron question]]
Additions:
""<h5 id="nltk_meter">nltk example</h5>""http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html#a-pronouncing-dictionary %%(python)
import nltk
#pdl = nltk.corpus.cmudict.entries()
pd = nltk.corpus.cmudict.dict()
def meter(pron):
return ''.join([str(int(bool(int(c)))) for p in pron for c in p if c.isdigit()])
def get_meter_list(m):
return [w for w, p in pdl if meter(p) == m]
#print len(get_meter_list('0'))
#print len(get_meter_list('1'))
def tokenize(sent):
return [w.strip().lower() for w in sent.split(' ')]
def scan(line):
m = []
for w in tokenize(line):
m.append(meter(pd.get(w)[0]))
return ''.join(m)
sent = 'A rose is a rose is a rose is a rose'
print scan(sent)
""<h5 id="python_buffer_capture">python buffer capture (assign stdout to a variable)</h5>""%%
import nltk
#pdl = nltk.corpus.cmudict.entries()
pd = nltk.corpus.cmudict.dict()
def meter(pron):
return ''.join([str(int(bool(int(c)))) for p in pron for c in p if c.isdigit()])
def get_meter_list(m):
return [w for w, p in pdl if meter(p) == m]
#print len(get_meter_list('0'))
#print len(get_meter_list('1'))
def tokenize(sent):
return [w.strip().lower() for w in sent.split(' ')]
def scan(line):
m = []
for w in tokenize(line):
m.append(meter(pd.get(w)[0]))
return ''.join(m)
sent = 'A rose is a rose is a rose is a rose'
print scan(sent)
""<h5 id="python_buffer_capture">python buffer capture (assign stdout to a variable)</h5>""%%
Deletions:
Additions:
""<h4 id="python_buffer_capture">python buffer capture (assign stdout to a variable)</h4>""
Deletions:
Additions:
""<h4 id="python_buffer_capture>python buffer capture (assign stdout to a variable)</h4>""
Deletions:
Additions:
python buffer capture (assign stdout to a variable):
class BufferTestCase(unittest.TestCase):
def openBuffer(self):
import StringIO, sys
self.old_buffer = sys.stdout
sys.stdout = self.new_buffer = StringIO.StringIO()
return self.old_buffer
def closeBuffer(self):
buffer_content = self.new_buffer.getvalue()
sys.stdout = self.old_buffer
self.new_buffer.close()
return buffer_content
def testBuffer(self):
self.openBuffer()
print 'hello'
buffer = self.closeBuffer()
self.assertEqual(buffer, 'hello\n')
class BufferTestCase(unittest.TestCase):
def openBuffer(self):
import StringIO, sys
self.old_buffer = sys.stdout
sys.stdout = self.new_buffer = StringIO.StringIO()
return self.old_buffer
def closeBuffer(self):
buffer_content = self.new_buffer.getvalue()
sys.stdout = self.old_buffer
self.new_buffer.close()
return buffer_content
def testBuffer(self):
self.openBuffer()
print 'hello'
buffer = self.closeBuffer()
self.assertEqual(buffer, 'hello\n')
Additions:
python string diff:
from difflib import Differ
d = Differ()
print '\n'.join(list(d.compare(app_output, expect)))
from difflib import Differ
d = Differ()
print '\n'.join(list(d.compare(app_output, expect)))
Additions:
google group question: [[http://groups.google.com/group/google-appengine-python/browse_thread/thread/ca1b6838bc68d64a/5be4288579bc5a77?q=klenwell#5be4288579bc5a77 serve atom through appengine]]
Additions:
python:
import re
def re_ungreedy(re_, s):
r = re_.replace('%s', '(.*?)')
return re.search(r, s).groups()
re_ = "<h2>%s</h2>"
H2List = re_ungreedy(re_, '<h2>one</h2><h2>two</h2>')
import re
def re_ungreedy(re_, s):
r = re_.replace('%s', '(.*?)')
return re.search(r, s).groups()
re_ = "<h2>%s</h2>"
H2List = re_ungreedy(re_, '<h2>one</h2><h2>two</h2>')
Additions:
python debugger: ""<tt>import pdb; pdb.set_trace()</tt>""
Additions:
php safe query builder
function safe_sql($sqlf, $ParamList) {
$SafeParamList = array();
foreach ( $ParamList as $value ) {
$SafeParamList[] = mysql_real_escape_string($value);
$SprintfArgList = array_merge(array($sqlf), $SafeParamList);
return call_user_func_array('sprintf', $SprintfArgList);
function safe_sql($sqlf, $ParamList) {
$SafeParamList = array();
foreach ( $ParamList as $value ) {
$SafeParamList[] = mysql_real_escape_string($value);
$SprintfArgList = array_merge(array($sqlf), $SafeParamList);
return call_user_func_array('sprintf', $SprintfArgList);
Additions:
PEAR HTTP_Request2 [[http://pear.php.net/manual/en/package.http.http-request2.intro.php docs]] [[http://pear.php.net/package/HTTP_Request2/docs/latest/HTTP_Request2/HTTP_Request2.html api]]
Additions:
/*
HTTP_Request2 Demo
Lib File Tree
kw_pear\
HTTP\
Request2\
Request2.php
Net\
URL2.php
PEAR\
Exception.php
PEAR.php
*/
$wwwd = dirname(dirname(__FILE__));
$peard = sprintf('%s/%s', $wwwd, 'kw_pear');
$path_ext = implode(PATH_SEPARATOR, array(get_include_path(),
$peard));
# imports
ini_set('include_path', $path_ext);
require_once 'HTTP/Request2.php';
$UrlList = array(
'ok' => 'http://pear.php.net/package/HTTP_Request2/docs',
'404' => 'http://pear.php.net/package/HTTP_Request2/docs/null',
'fail' => 'bad url'
);
$TestList = array_keys($UrlList);
$test = $TestList[array_rand($TestList)];
$url = $UrlList[$test];
$Client = new HTTP_Request2();
$Client->setMethod(HTTP_Request2::METHOD_GET);
$Client->setUrl($url);
try {
$Response = $Client->send();
$code = $Response->getStatus();
$code_class = floor($Response->getStatus() / 100);
catch (HTTP_Request2_Exception $e) {
trigger_error(sprintf('http exception: %s',
$e->getMessage()), E_USER_ERROR);
if ( $code_class == 2 ) {
$output = htmlspecialchars($Response->getBody());
else {
$output = sprintf('unexpected response [%s]: %s',
$Response->getStatus(),
$Response->getReasonPhrase());
printf('<h4>test: %s</h4><pre>%s</pre>', $test, $output);
HTTP_Request2 Demo
Lib File Tree
kw_pear\
HTTP\
Request2\
Request2.php
Net\
URL2.php
PEAR\
Exception.php
PEAR.php
*/
$wwwd = dirname(dirname(__FILE__));
$peard = sprintf('%s/%s', $wwwd, 'kw_pear');
$path_ext = implode(PATH_SEPARATOR, array(get_include_path(),
$peard));
# imports
ini_set('include_path', $path_ext);
require_once 'HTTP/Request2.php';
$UrlList = array(
'ok' => 'http://pear.php.net/package/HTTP_Request2/docs',
'404' => 'http://pear.php.net/package/HTTP_Request2/docs/null',
'fail' => 'bad url'
);
$TestList = array_keys($UrlList);
$test = $TestList[array_rand($TestList)];
$url = $UrlList[$test];
$Client = new HTTP_Request2();
$Client->setMethod(HTTP_Request2::METHOD_GET);
$Client->setUrl($url);
try {
$Response = $Client->send();
$code = $Response->getStatus();
$code_class = floor($Response->getStatus() / 100);
catch (HTTP_Request2_Exception $e) {
trigger_error(sprintf('http exception: %s',
$e->getMessage()), E_USER_ERROR);
if ( $code_class == 2 ) {
$output = htmlspecialchars($Response->getBody());
else {
$output = sprintf('unexpected response [%s]: %s',
$Response->getStatus(),
$Response->getReasonPhrase());
printf('<h4>test: %s</h4><pre>%s</pre>', $test, $output);
Additions:
copy with exclude: ""<tt>rsync -rv --exclude=.svn source/* dest</tt>""
Additions:
wikka update page function:
function update_page($page_name, $page_body, $WikkaObj) {
$updatef = "UPDATE %s SET latest='N' WHERE tag='%s'";
$insertf = "INSERT INTO %s SET tag='%s', body='%s', owner='%s', user='%s', note='%s', time=NOW(), latest='Y'";
$note = 'auto updating page';
$user = '(system)';
$table_prefix = $WikkaObj->GetConfigValue('table_prefix');
$table_name = sprintf('%spages', $table_prefix);
$page_name = mysql_real_escape_string($page_name);
$page_body = mysql_real_escape_string($page_body);
if ( $WikkaObj->existsPage($page_name, $table_prefix) ) {
# set all other revisions to old
$is_updated = $WikkaObj->Query(sprintf($updatef, $table_name, $page_name));
# add new revision
return $WikkaObj->Query( sprintf( $insertf,
$table_name,
$page_name,
$page_body,
'(Public)',
$user,
$note ));
function update_page($page_name, $page_body, $WikkaObj) {
$updatef = "UPDATE %s SET latest='N' WHERE tag='%s'";
$insertf = "INSERT INTO %s SET tag='%s', body='%s', owner='%s', user='%s', note='%s', time=NOW(), latest='Y'";
$note = 'auto updating page';
$user = '(system)';
$table_prefix = $WikkaObj->GetConfigValue('table_prefix');
$table_name = sprintf('%spages', $table_prefix);
$page_name = mysql_real_escape_string($page_name);
$page_body = mysql_real_escape_string($page_body);
if ( $WikkaObj->existsPage($page_name, $table_prefix) ) {
# set all other revisions to old
$is_updated = $WikkaObj->Query(sprintf($updatef, $table_name, $page_name));
# add new revision
return $WikkaObj->Query( sprintf( $insertf,
$table_name,
$page_name,
$page_body,
'(Public)',
$user,
$note ));
Additions:
To call a script, you can make it as handler and put it at (as of 1.1.6.2) the directory named handlers/page/, ie like handlers/page/cron.changemail.php [[http://wikkawiki.org/RecentChangesNotifier?show_comments=1#comments source]]
Additions:
function log() {
datestamp=$(date "+%Y-%m-%d %H:%M:%S")
printf "[%s] %s\n" "$datestamp" "$1"
}
CACHE_FILE_COUNT=$(find /tmp -type f | wc -l)
if [ $CACHE_FILE_COUNT -gt 0 ]; then
log "$CACHE_FILE_COUNT files found in /tmp"
else
log "no files found in /tmp"
fi
datestamp=$(date "+%Y-%m-%d %H:%M:%S")
printf "[%s] %s\n" "$datestamp" "$1"
}
CACHE_FILE_COUNT=$(find /tmp -type f | wc -l)
if [ $CACHE_FILE_COUNT -gt 0 ]; then
log "$CACHE_FILE_COUNT files found in /tmp"
else
log "no files found in /tmp"
fi
Additions:
Office Hacks: during ethnic holidays, go up to people at random and ask if they have any plans. (e.g.: week before passover, ask Chinese co-worker: "so do you have any Passover plans this weekend?")
$Dbo = ConnectionManager::getDataSource("default");
$old_db = $Dbo->config['database'];
$Dbo->reconnect(array('database'=>$new_db));
return $old_db;
$Dbo = ConnectionManager::getDataSource("default");
# get tables
$sql_show_tables_ = 'SHOW TABLES IN %s';
$extract_pattern = sprintf('{n}.TABLE_NAMES.Tables_in_%s', $db);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, $extract_pattern);
# create new database
$sql = sprintf('CREATE DATABASE %s', $new_db);
$Dbo->query($sql);
# copy tables
$sql1_t = 'CREATE TABLE %s.%s LIKE %s.%s';
$sql2_t = 'INSERT INTO %s.%s SELECT * FROM %s.%s';
foreach ( $TableList as $table ) {
$sql1 = sprintf($sql1_t, $new_db, $table, $db, $table);
$sql2 = sprintf($sql2_t, $new_db, $table, $db, $table);
$Dbo->query($sql1);
$Dbo->query($sql2);
}
# test table lists
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList1 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $new_db));
$TableList2 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$new_db");
if ( array_diff($TableList1, $TableList2) ) {
trigger_error('table lists in new db dows not match old', E_USER_WARNING);
return 0;
}
$this->Log_[] = "all tables in $db copied to $new_db";
# test query: count all records and compare
$old_db_count = 0;
$new_db_count = 0;
foreach ( $TableList as $table ) {
$sql_ = 'SELECT COUNT(*) as count_ FROM %s.%s';
$OldDb = $Dbo->query(sprintf($sql_, $db, $table));
$NewDb = $Dbo->query(sprintf($sql_, $new_db, $table));
$old_db_count += $OldDb[0][0]['count_'];
$new_db_count += $NewDb[0][0]['count_'];
}
$rand_table = $TableList[array_rand($TableList)];
if ( $old_db_count != $new_db_count ) {
$mt_ = 'record count for new db (%s) and old db (%s) does not match';
trigger_error(sprintf($mt_, $new_db_count, $old_db_count), E_USER_WARNING);
return 0;
}
else {
$mt_ = 'record count for new db (%s) and old db (%s)';
$this->Log_[] = sprintf($mt_, $new_db_count, $old_db_count);
return 1;
}
'$char' => $char,
'$h_char - htmlentities($char)' => $h_char,
'$utf8 - htmlspecialchars($char,ENT_QUOTES,\'UTF-8\')' =>
$utf8,
'htmlspecialchars(\'Ü\',ENT_QUOTES,\'UTF-8\')' =>
htmlspecialchars('Ü', ENT_QUOTES, 'UTF-8'),
'$h_utf8 - htmlentities($utf8)' =>
$h_utf8,
'strlen($char)' => strlen($char),
'strlen($h_char)' => strlen($h_char),
'strlen($utf8)' => strlen($utf8),
'strlen($h_utf8)' => strlen($h_utf8),
'ord($char)' => ord($char),
'ord($utf8)' => ord($utf8),
'utf8ToUnicode($char)' => $uni_char,
'dechex(ord($char))' => dechex(ord($char)),
'sprintf(\'&#x%s;\', dechex(ord($char)))' =>
sprintf('&#x%s;', dechex(ord($char))),
'sprintf(\'&#x%s;\', ord($char))' =>
sprintf('&#x%s;', ord($char)),
'sprintf(\'&#%s;\', $uni_char[0])' =>
sprintf('&#%s;', $uni_char[0]),
'sprintf("&#x%s;", dechex($uni_char[0]))' =>
sprintf("&#x%s;", dechex($uni_char[0])),
'iconv("UTF-8","ISO-8859-1//TRANSLIT",$char)' =>
iconv("UTF-8","ISO-8859-1//TRANSLIT",$char),
if ( $action == null ) {
$action = $this->view_action;
}
$output = parent::render($action, $layout, $file);
return $output;
$m = 'null';
if ( isset($this->params['pass'][0]) ) {
$m = $this->params['pass'][0];
}
#debug($this->params);
#debug($m);
if ( method_exists($this, $m) ) {
$this->view_action = sprintf('/journal/%s', $m);
return $this->$m();
}
else {
$this->set('error', 'page_not_found');
}
$Dbo = ConnectionManager::getDataSource("default");
$old_db = $Dbo->config['database'];
$Dbo->reconnect(array('database'=>$new_db));
return $old_db;
$Dbo = ConnectionManager::getDataSource("default");
# get tables
$sql_show_tables_ = 'SHOW TABLES IN %s';
$extract_pattern = sprintf('{n}.TABLE_NAMES.Tables_in_%s', $db);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, $extract_pattern);
# create new database
$sql = sprintf('CREATE DATABASE %s', $new_db);
$Dbo->query($sql);
# copy tables
$sql1_t = 'CREATE TABLE %s.%s LIKE %s.%s';
$sql2_t = 'INSERT INTO %s.%s SELECT * FROM %s.%s';
foreach ( $TableList as $table ) {
$sql1 = sprintf($sql1_t, $new_db, $table, $db, $table);
$sql2 = sprintf($sql2_t, $new_db, $table, $db, $table);
$Dbo->query($sql1);
$Dbo->query($sql2);
}
# test table lists
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList1 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $new_db));
$TableList2 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$new_db");
if ( array_diff($TableList1, $TableList2) ) {
trigger_error('table lists in new db dows not match old', E_USER_WARNING);
return 0;
}
$this->Log_[] = "all tables in $db copied to $new_db";
# test query: count all records and compare
$old_db_count = 0;
$new_db_count = 0;
foreach ( $TableList as $table ) {
$sql_ = 'SELECT COUNT(*) as count_ FROM %s.%s';
$OldDb = $Dbo->query(sprintf($sql_, $db, $table));
$NewDb = $Dbo->query(sprintf($sql_, $new_db, $table));
$old_db_count += $OldDb[0][0]['count_'];
$new_db_count += $NewDb[0][0]['count_'];
}
$rand_table = $TableList[array_rand($TableList)];
if ( $old_db_count != $new_db_count ) {
$mt_ = 'record count for new db (%s) and old db (%s) does not match';
trigger_error(sprintf($mt_, $new_db_count, $old_db_count), E_USER_WARNING);
return 0;
}
else {
$mt_ = 'record count for new db (%s) and old db (%s)';
$this->Log_[] = sprintf($mt_, $new_db_count, $old_db_count);
return 1;
}
'$char' => $char,
'$h_char - htmlentities($char)' => $h_char,
'$utf8 - htmlspecialchars($char,ENT_QUOTES,\'UTF-8\')' =>
$utf8,
'htmlspecialchars(\'Ü\',ENT_QUOTES,\'UTF-8\')' =>
htmlspecialchars('Ü', ENT_QUOTES, 'UTF-8'),
'$h_utf8 - htmlentities($utf8)' =>
$h_utf8,
'strlen($char)' => strlen($char),
'strlen($h_char)' => strlen($h_char),
'strlen($utf8)' => strlen($utf8),
'strlen($h_utf8)' => strlen($h_utf8),
'ord($char)' => ord($char),
'ord($utf8)' => ord($utf8),
'utf8ToUnicode($char)' => $uni_char,
'dechex(ord($char))' => dechex(ord($char)),
'sprintf(\'&#x%s;\', dechex(ord($char)))' =>
sprintf('&#x%s;', dechex(ord($char))),
'sprintf(\'&#x%s;\', ord($char))' =>
sprintf('&#x%s;', ord($char)),
'sprintf(\'&#%s;\', $uni_char[0])' =>
sprintf('&#%s;', $uni_char[0]),
'sprintf("&#x%s;", dechex($uni_char[0]))' =>
sprintf("&#x%s;", dechex($uni_char[0])),
'iconv("UTF-8","ISO-8859-1//TRANSLIT",$char)' =>
iconv("UTF-8","ISO-8859-1//TRANSLIT",$char),
if ( $action == null ) {
$action = $this->view_action;
}
$output = parent::render($action, $layout, $file);
return $output;
$m = 'null';
if ( isset($this->params['pass'][0]) ) {
$m = $this->params['pass'][0];
}
#debug($this->params);
#debug($m);
if ( method_exists($this, $m) ) {
$this->view_action = sprintf('/journal/%s', $m);
return $this->$m();
}
else {
$this->set('error', 'page_not_found');
}
Deletions:
$old_db = $Dbo->config['database'];
$Dbo->reconnect(array('database'=>$new_db));
return $old_db;
$Dbo = ConnectionManager::getDataSource("default");
# get tables
$sql_show_tables_ = 'SHOW TABLES IN %s';
$extract_pattern = sprintf('{n}.TABLE_NAMES.Tables_in_%s', $db);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, $extract_pattern);
# create new database
$sql = sprintf('CREATE DATABASE %s', $new_db);
$Dbo->query($sql);
# copy tables
$sql1_t = 'CREATE TABLE %s.%s LIKE %s.%s';
$sql2_t = 'INSERT INTO %s.%s SELECT * FROM %s.%s';
foreach ( $TableList as $table ) {
$sql1 = sprintf($sql1_t, $new_db, $table, $db, $table);
$sql2 = sprintf($sql2_t, $new_db, $table, $db, $table);
$Dbo->query($sql1);
$Dbo->query($sql2);
}
# test table lists
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList1 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $new_db));
$TableList2 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$new_db");
if ( array_diff($TableList1, $TableList2) ) {
trigger_error('table lists in new db dows not match old', E_USER_WARNING);
return 0;
}
$this->Log_[] = "all tables in $db copied to $new_db";
# test query: count all records and compare
$old_db_count = 0;
$new_db_count = 0;
foreach ( $TableList as $table ) {
$sql_ = 'SELECT COUNT(*) as count_ FROM %s.%s';
$OldDb = $Dbo->query(sprintf($sql_, $db, $table));
$NewDb = $Dbo->query(sprintf($sql_, $new_db, $table));
$old_db_count += $OldDb[0][0]['count_'];
$new_db_count += $NewDb[0][0]['count_'];
}
$rand_table = $TableList[array_rand($TableList)];
if ( $old_db_count != $new_db_count ) {
$mt_ = 'record count for new db (%s) and old db (%s) does not match';
trigger_error(sprintf($mt_, $new_db_count, $old_db_count), E_USER_WARNING);
return 0;
}
else {
$mt_ = 'record count for new db (%s) and old db (%s)';
$this->Log_[] = sprintf($mt_, $new_db_count, $old_db_count);
return 1;
}
'$char' => $char,
'$h_char - htmlentities($char)' => $h_char,
'$utf8 - htmlspecialchars($char,ENT_QUOTES,\'UTF-8\')' =>
$utf8,
'htmlspecialchars(\'Ü\',ENT_QUOTES,\'UTF-8\')' =>
htmlspecialchars('Ü', ENT_QUOTES, 'UTF-8'),
'$h_utf8 - htmlentities($utf8)' =>
$h_utf8,
'strlen($char)' => strlen($char),
'strlen($h_char)' => strlen($h_char),
'strlen($utf8)' => strlen($utf8),
'strlen($h_utf8)' => strlen($h_utf8),
'ord($char)' => ord($char),
'ord($utf8)' => ord($utf8),
'utf8ToUnicode($char)' => $uni_char,
'dechex(ord($char))' => dechex(ord($char)),
'sprintf(\'&#x%s;\', dechex(ord($char)))' =>
sprintf('&#x%s;', dechex(ord($char))),
'sprintf(\'&#x%s;\', ord($char))' =>
sprintf('&#x%s;', ord($char)),
'sprintf(\'&#%s;\', $uni_char[0])' =>
sprintf('&#%s;', $uni_char[0]),
'sprintf("&#x%s;", dechex($uni_char[0]))' =>
sprintf("&#x%s;", dechex($uni_char[0])),
'iconv("UTF-8","ISO-8859-1//TRANSLIT",$char)' =>
iconv("UTF-8","ISO-8859-1//TRANSLIT",$char),
if ( $action == null ) {
$action = $this->view_action;
}
$output = parent::render($action, $layout, $file);
return $output;
$m = 'null';
if ( isset($this->params['pass'][0]) ) {
$m = $this->params['pass'][0];
}
#debug($this->params);
#debug($m);
if ( method_exists($this, $m) ) {
$this->view_action = sprintf('/journal/%s', $m);
return $this->$m();
}
else {
$this->set('error', 'page_not_found');
}
Additions:
Against the [[http://corneredcat.com/Ethics/civilization.aspx Gun is Civilization Argument]]: Pastebin20100226
Deletions:
The thesis is a canard. Guns do not promote civilization. Civilization is the result of functioning social institutions (foremost, the state itself), cooperative behavior, and, as Oliver Wendell Holmes Jr. said, taxes.
Flaws:
1. "Reason or force, that's it." False dichotomy: in the sense that the force referred to is a very particular kind of force: lethal force. In civilized societies, this is a threat most people never (never!) face. Even when they do, a gun helps only in very narrow circumstances and does not "civilize" the situation. It glides over the much more complicated concept of contracts. Are these methods of reason or force? What do we do when they are broken?
2. "A mugger, even an armed one, can only make a successful living in a society where the state has granted him a force monopoly." No civilized society has ever granted him that monopoly. The state reserves that monopoly for itself. That is part of what makes it civilized. The mugger is trying to break that monopoly, to the detriment of civilization.
3. "When I carry a gun, I don't do so because I am looking for a fight, but because I'm looking to be left alone. The gun at my side means that I cannot be forced, only persuaded." This is narcissistic to the point of pathology. If you did this in any public place where I encountered you, you would be the threat. It is a provocative act that does not further the cause of civilization.
Additions:
Against the [[http://corneredcat.com/Ethics/civilization.aspx Gun is Civilization Argument]]:
The thesis is a canard. Guns do not promote civilization. Civilization is the result of functioning social institutions (foremost, the state itself), cooperative behavior, and, as Oliver Wendell Holmes Jr. said, taxes.
Flaws:
1. "Reason or force, that's it." False dichotomy: in the sense that the force referred to is a very particular kind of force: lethal force. In civilized societies, this is a threat most people never (never!) face. Even when they do, a gun helps only in very narrow circumstances and does not "civilize" the situation. It glides over the much more complicated concept of contracts. Are these methods of reason or force? What do we do when they are broken?
2. "A mugger, even an armed one, can only make a successful living in a society where the state has granted him a force monopoly." No civilized society has ever granted him that monopoly. The state reserves that monopoly for itself. That is part of what makes it civilized. The mugger is trying to break that monopoly, to the detriment of civilization.
3. "When I carry a gun, I don't do so because I am looking for a fight, but because I'm looking to be left alone. The gun at my side means that I cannot be forced, only persuaded." This is narcissistic to the point of pathology. If you did this in any public place where I encountered you, you would be the threat. It is a provocative act that does not further the cause of civilization.
The thesis is a canard. Guns do not promote civilization. Civilization is the result of functioning social institutions (foremost, the state itself), cooperative behavior, and, as Oliver Wendell Holmes Jr. said, taxes.
Flaws:
1. "Reason or force, that's it." False dichotomy: in the sense that the force referred to is a very particular kind of force: lethal force. In civilized societies, this is a threat most people never (never!) face. Even when they do, a gun helps only in very narrow circumstances and does not "civilize" the situation. It glides over the much more complicated concept of contracts. Are these methods of reason or force? What do we do when they are broken?
2. "A mugger, even an armed one, can only make a successful living in a society where the state has granted him a force monopoly." No civilized society has ever granted him that monopoly. The state reserves that monopoly for itself. That is part of what makes it civilized. The mugger is trying to break that monopoly, to the detriment of civilization.
3. "When I carry a gun, I don't do so because I am looking for a fight, but because I'm looking to be left alone. The gun at my side means that I cannot be forced, only persuaded." This is narcissistic to the point of pathology. If you did this in any public place where I encountered you, you would be the threat. It is a provocative act that does not further the cause of civilization.
Additions:
Pattern Request Page: jquery json ajax request with cakephp
Additions:
[[http://news.ycombinator.com/threads?id=klenwell ycombo]]
Additions:
[[http://i.imgur.com/OAvqY.jpg fly bomber]] (it's supafly)
Additions:
[[http://www.youtube.com/watch?v=IKmCCIjgY4E classic olympic fail]]
Additions:
function _switch_database($new_db) {
$Dbo = ConnectionManager::getDataSource("default");
$old_db = $Dbo->config['database'];
$Dbo->reconnect(array('database'=>$new_db));
return $old_db;
function _copy_database($db, $new_db) {
$Dbo = ConnectionManager::getDataSource("default");
$extract_pattern = sprintf('{n}.TABLE_NAMES.Tables_in_%s', $db);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, $extract_pattern);
$Dbo->query($sql);
$Dbo->query($sql1);
$Dbo->query($sql2);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $new_db));
# test query: count all records and compare
$old_db_count = 0;
$new_db_count = 0;
$sql_ = 'SELECT COUNT(*) as count_ FROM %s.%s';
$OldDb = $Dbo->query(sprintf($sql_, $db, $table));
$NewDb = $Dbo->query(sprintf($sql_, $new_db, $table));
$old_db_count += $OldDb[0][0]['count_'];
$new_db_count += $NewDb[0][0]['count_'];
$rand_table = $TableList[array_rand($TableList)];
if ( $old_db_count != $new_db_count ) {
$mt_ = 'record count for new db (%s) and old db (%s) does not match';
trigger_error(sprintf($mt_, $new_db_count, $old_db_count), E_USER_WARNING);
$mt_ = 'record count for new db (%s) and old db (%s)';
$this->Log_[] = sprintf($mt_, $new_db_count, $old_db_count);
return 1;
$Dbo = ConnectionManager::getDataSource("default");
$old_db = $Dbo->config['database'];
$Dbo->reconnect(array('database'=>$new_db));
return $old_db;
function _copy_database($db, $new_db) {
$Dbo = ConnectionManager::getDataSource("default");
$extract_pattern = sprintf('{n}.TABLE_NAMES.Tables_in_%s', $db);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, $extract_pattern);
$Dbo->query($sql);
$Dbo->query($sql1);
$Dbo->query($sql2);
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $db));
$ShowTables = $Dbo->query(sprintf($sql_show_tables_, $new_db));
# test query: count all records and compare
$old_db_count = 0;
$new_db_count = 0;
$sql_ = 'SELECT COUNT(*) as count_ FROM %s.%s';
$OldDb = $Dbo->query(sprintf($sql_, $db, $table));
$NewDb = $Dbo->query(sprintf($sql_, $new_db, $table));
$old_db_count += $OldDb[0][0]['count_'];
$new_db_count += $NewDb[0][0]['count_'];
$rand_table = $TableList[array_rand($TableList)];
if ( $old_db_count != $new_db_count ) {
$mt_ = 'record count for new db (%s) and old db (%s) does not match';
trigger_error(sprintf($mt_, $new_db_count, $old_db_count), E_USER_WARNING);
$mt_ = 'record count for new db (%s) and old db (%s)';
$this->Log_[] = sprintf($mt_, $new_db_count, $old_db_count);
return 1;
Deletions:
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$this->Model->query($sql);
$this->Model->query($sql1);
$this->Model->query($sql2);
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $db));
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $new_db));
# test query
$sql_ = 'SELECT COUNT(*) as counter FROM %s.TABLENAME';
$Result1 = $this->Model->query(sprintf($sql_, $db));
$Result2 = $this->Model->query(sprintf($sql_, $new_db));
if ( $Result1[0][0]['counter'] != $Result2[0][0]['counter'] ) {
trigger_error('test query failed', E_USER_WARNING);
$count = $Result1[0][0]['counter'];
$this->Log_[] = "count [$count] in '$db.TABLENAME' matches '$new_db.TABLENAME'";
return 1;
Additions:
[[http://groups.google.com/group/gdata-python-client-library-contributors/browse_thread/thread/eaa1bb7aecca54a7 gdata python question on google groups]]
Additions:
[[http://images.google.com/imgres?imgurl=http://gregcookland.com/journal/uploaded_images/picComteRizzoli-766773.jpg&imgrefurl=http://gregcookland.com/journal/2008_06_15_archive.html&usg=__USS6LoobgDc3pWmwX-xN6gNekmI=&h=320&w=400&sz=29&hl=en&start=5&um=1&itbs=1&tbnid=Ey-NAsHfo6f9VM:&tbnh=99&tbnw=124&prev=/images%3Fq%3Dzaha%2Bhadid%2Byoung%26hl%3Den%26sa%3DG%26um%3D1 curious]]
Additions:
copying DB in php
function _copy_database($db, $new_db) {
# get tables
$sql_show_tables_ = 'SHOW TABLES IN %s';
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
# create new database
$sql = sprintf('CREATE DATABASE %s', $new_db);
$this->Model->query($sql);
# copy tables
$sql1_t = 'CREATE TABLE %s.%s LIKE %s.%s';
$sql2_t = 'INSERT INTO %s.%s SELECT * FROM %s.%s';
foreach ( $TableList as $table ) {
$sql1 = sprintf($sql1_t, $new_db, $table, $db, $table);
$sql2 = sprintf($sql2_t, $new_db, $table, $db, $table);
$this->Model->query($sql1);
$this->Model->query($sql2);
# test table lists
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $db));
$TableList1 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $new_db));
$TableList2 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$new_db");
if ( array_diff($TableList1, $TableList2) ) {
trigger_error('table lists in new db dows not match old', E_USER_WARNING);
return 0;
$this->Log_[] = "all tables in $db copied to $new_db";
# test query
$sql_ = 'SELECT COUNT(*) as counter FROM %s.TABLENAME';
$Result1 = $this->Model->query(sprintf($sql_, $db));
$Result2 = $this->Model->query(sprintf($sql_, $new_db));
if ( $Result1[0][0]['counter'] != $Result2[0][0]['counter'] ) {
trigger_error('test query failed', E_USER_WARNING);
return 0;
$count = $Result1[0][0]['counter'];
$this->Log_[] = "count [$count] in '$db.TABLENAME' matches '$new_db.TABLENAME'";
return 1;
function _copy_database($db, $new_db) {
# get tables
$sql_show_tables_ = 'SHOW TABLES IN %s';
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $db));
$TableList = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
# create new database
$sql = sprintf('CREATE DATABASE %s', $new_db);
$this->Model->query($sql);
# copy tables
$sql1_t = 'CREATE TABLE %s.%s LIKE %s.%s';
$sql2_t = 'INSERT INTO %s.%s SELECT * FROM %s.%s';
foreach ( $TableList as $table ) {
$sql1 = sprintf($sql1_t, $new_db, $table, $db, $table);
$sql2 = sprintf($sql2_t, $new_db, $table, $db, $table);
$this->Model->query($sql1);
$this->Model->query($sql2);
# test table lists
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $db));
$TableList1 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$db");
$ShowTables = $this->Model->query(sprintf($sql_show_tables_, $new_db));
$TableList2 = Set::extract($ShowTables, "{n}.TABLE_NAMES.Tables_in_$new_db");
if ( array_diff($TableList1, $TableList2) ) {
trigger_error('table lists in new db dows not match old', E_USER_WARNING);
return 0;
$this->Log_[] = "all tables in $db copied to $new_db";
# test query
$sql_ = 'SELECT COUNT(*) as counter FROM %s.TABLENAME';
$Result1 = $this->Model->query(sprintf($sql_, $db));
$Result2 = $this->Model->query(sprintf($sql_, $new_db));
if ( $Result1[0][0]['counter'] != $Result2[0][0]['counter'] ) {
trigger_error('test query failed', E_USER_WARNING);
return 0;
$count = $Result1[0][0]['counter'];
$this->Log_[] = "count [$count] in '$db.TABLENAME' matches '$new_db.TABLENAME'";
return 1;
Additions:
php encoding tests
requires http://hsivonen.iki.fi/php-utf8/php-utf8.tar.gz
%%(php)
<?php
require('utf8.inc');
$char = 'Ü';
$h_char = htmlentities($char);
$utf8 = htmlspecialchars($char, ENT_QUOTES, 'UTF-8');
$h_utf8 = htmlentities($utf8);
$uni_char = utf8ToUnicode($char);
$data = array(
'$char' => $char,
'$h_char - htmlentities($char)' => $h_char,
'$utf8 - htmlspecialchars($char,ENT_QUOTES,\'UTF-8\')' =>
$utf8,
'htmlspecialchars(\'Ü\',ENT_QUOTES,\'UTF-8\')' =>
htmlspecialchars('Ü', ENT_QUOTES, 'UTF-8'),
'$h_utf8 - htmlentities($utf8)' =>
$h_utf8,
'strlen($char)' => strlen($char),
'strlen($h_char)' => strlen($h_char),
'strlen($utf8)' => strlen($utf8),
'strlen($h_utf8)' => strlen($h_utf8),
'ord($char)' => ord($char),
'ord($utf8)' => ord($utf8),
'utf8ToUnicode($char)' => $uni_char,
'dechex(ord($char))' => dechex(ord($char)),
'sprintf(\'&#x%s;\', dechex(ord($char)))' =>
sprintf('&#x%s;', dechex(ord($char))),
'sprintf(\'&#x%s;\', ord($char))' =>
sprintf('&#x%s;', ord($char)),
'sprintf(\'&#%s;\', $uni_char[0])' =>
sprintf('&#%s;', $uni_char[0]),
'sprintf("&#x%s;", dechex($uni_char[0]))' =>
sprintf("&#x%s;", dechex($uni_char[0])),
'iconv("UTF-8","ISO-8859-1//TRANSLIT",$char)' =>
iconv("UTF-8","ISO-8859-1//TRANSLIT",$char),
);
$xhtml = <<<XHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>sandbox</title></head>
<body>
<pre>
%s
</pre>
</body>
</html>
XHTML;
$charset = 'UTF-8'; #'ISO-8859-1';
header( 'Content-type: text/html; charset='.$charset );
printf($xhtml, print_r($data,1));
var_dump($char);
var_dump($h_char);
var_dump($utf8);
var_dump($h_utf8);
requires http://hsivonen.iki.fi/php-utf8/php-utf8.tar.gz
%%(php)
<?php
require('utf8.inc');
$char = 'Ü';
$h_char = htmlentities($char);
$utf8 = htmlspecialchars($char, ENT_QUOTES, 'UTF-8');
$h_utf8 = htmlentities($utf8);
$uni_char = utf8ToUnicode($char);
$data = array(
'$char' => $char,
'$h_char - htmlentities($char)' => $h_char,
'$utf8 - htmlspecialchars($char,ENT_QUOTES,\'UTF-8\')' =>
$utf8,
'htmlspecialchars(\'Ü\',ENT_QUOTES,\'UTF-8\')' =>
htmlspecialchars('Ü', ENT_QUOTES, 'UTF-8'),
'$h_utf8 - htmlentities($utf8)' =>
$h_utf8,
'strlen($char)' => strlen($char),
'strlen($h_char)' => strlen($h_char),
'strlen($utf8)' => strlen($utf8),
'strlen($h_utf8)' => strlen($h_utf8),
'ord($char)' => ord($char),
'ord($utf8)' => ord($utf8),
'utf8ToUnicode($char)' => $uni_char,
'dechex(ord($char))' => dechex(ord($char)),
'sprintf(\'&#x%s;\', dechex(ord($char)))' =>
sprintf('&#x%s;', dechex(ord($char))),
'sprintf(\'&#x%s;\', ord($char))' =>
sprintf('&#x%s;', ord($char)),
'sprintf(\'&#%s;\', $uni_char[0])' =>
sprintf('&#%s;', $uni_char[0]),
'sprintf("&#x%s;", dechex($uni_char[0]))' =>
sprintf("&#x%s;", dechex($uni_char[0])),
'iconv("UTF-8","ISO-8859-1//TRANSLIT",$char)' =>
iconv("UTF-8","ISO-8859-1//TRANSLIT",$char),
);
$xhtml = <<<XHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>sandbox</title></head>
<body>
<pre>
%s
</pre>
</body>
</html>
XHTML;
$charset = 'UTF-8'; #'ISO-8859-1';
header( 'Content-type: text/html; charset='.$charset );
printf($xhtml, print_r($data,1));
var_dump($char);
var_dump($h_char);
var_dump($utf8);
var_dump($h_utf8);
Additions:
jquery quiz
== jQuiz: jQuirks ==
A short quiz on jQuery behavior.
===1. What will these lines of code produce?===
<code><pre>
var Test1El1 = $('div#Test1El1');
var Test1El2 = $('div').attr('id', 'Test1El2');
var Test1El3 = $('<div id="Test1El3" />');
console.log(Test1El1);
console.log(Test1El2);
console.log(Test1El3);
</pre></code>
===2. What will be the output of the code below?===
<code><pre>
var Test2El1 = $('<div id="Test2El1" />');
$(document.body).append(Test2El1);
var elid = Test2El1Test2El1.attr('id');
var Test2El2 = $(elid);
console.log(Test2El1);
console.log(elid);
console.log(Test2El2);
</pre></code>
===3. True or False===
<code><pre>
var id_ = 'test3id';
$('<div id="' + id_ + '" />').appendTo(document.body);
var Test3El1 = document.getElementById(id_);
var Test3El2 = $('#'+id_);
console.log(Test3El1.id == Test3El2.id);
</pre></code>
===4. True or False===
<code><pre>
var Test4El1 = $('<div id="Test4El" />').appendTo(document.body);
var Test4El2 = $(Test4El1);
console.log(Test4El1 == Test4El2);
console.log(Test4El1.attr('id') == Test4El2.attr('id'));
</pre></code>
===Given a document with the following table code, answer the next 2 questions:===
<code><pre>
<table id="Test5Table">
<tr id="Test5Tr1"><td>cell1</td><td>cell2</td></tr>
<tr id="Test5Tr2"><td>cell1</td><td>cell2</td></tr>
</table>
var Test5Table = $('<table id="Test5Table"><tr id="tr1"><td>cell1</td><td>cell2</td></tr><tr id="tr2"><td>cell1</td><td>cell2</td></tr></table>');
$(document.body).append(Test5Table);
</pre></code>
====5. What will the value of TableRows[0] be below?====
<code><pre>
var Test5Table = $('table#Test5Table');
var TableRows = Test5Table.find('tr');
console.log(TableRows[0].attr('id'));
</pre></code>
====6. What will the value of RowIds[0] be below?====
<code><pre>
var Test5Table = $('table#Test5Table');
var TableRows = Test5Table.find('tr');
var RowIds = [];
TableRows.each( function(i, El) {
RowIds.push(El.attr('id'));
});
console.log(RowIds[0]);
</pre></code>
===7. What will the value of FindEl be below?===
<code><pre>
// build and add element to our document
var elid = 'formbid-0.field';
var NewDiv = $('<div id="'+elid+'" />').text(elid);
$(document.body).append(NewDiv);
var jqid = NewDiv.attr('id');
var FindEl = $(document.body).find('#'+jqid); // note # sign
console.log(jqid, FindEl);
</pre></code>
<div style="display:none;">Answer:
<code><pre>
jesc = jqid.replace('.', '\\.');
var FindEl = $(document.body).find('#'+jesc);
console.log(jesc, FindEl);
</pre></code>
</div>
== jQuiz: jQuirks ==
A short quiz on jQuery behavior.
===1. What will these lines of code produce?===
<code><pre>
var Test1El1 = $('div#Test1El1');
var Test1El2 = $('div').attr('id', 'Test1El2');
var Test1El3 = $('<div id="Test1El3" />');
console.log(Test1El1);
console.log(Test1El2);
console.log(Test1El3);
</pre></code>
===2. What will be the output of the code below?===
<code><pre>
var Test2El1 = $('<div id="Test2El1" />');
$(document.body).append(Test2El1);
var elid = Test2El1Test2El1.attr('id');
var Test2El2 = $(elid);
console.log(Test2El1);
console.log(elid);
console.log(Test2El2);
</pre></code>
===3. True or False===
<code><pre>
var id_ = 'test3id';
$('<div id="' + id_ + '" />').appendTo(document.body);
var Test3El1 = document.getElementById(id_);
var Test3El2 = $('#'+id_);
console.log(Test3El1.id == Test3El2.id);
</pre></code>
===4. True or False===
<code><pre>
var Test4El1 = $('<div id="Test4El" />').appendTo(document.body);
var Test4El2 = $(Test4El1);
console.log(Test4El1 == Test4El2);
console.log(Test4El1.attr('id') == Test4El2.attr('id'));
</pre></code>
===Given a document with the following table code, answer the next 2 questions:===
<code><pre>
<table id="Test5Table">
<tr id="Test5Tr1"><td>cell1</td><td>cell2</td></tr>
<tr id="Test5Tr2"><td>cell1</td><td>cell2</td></tr>
</table>
var Test5Table = $('<table id="Test5Table"><tr id="tr1"><td>cell1</td><td>cell2</td></tr><tr id="tr2"><td>cell1</td><td>cell2</td></tr></table>');
$(document.body).append(Test5Table);
</pre></code>
====5. What will the value of TableRows[0] be below?====
<code><pre>
var Test5Table = $('table#Test5Table');
var TableRows = Test5Table.find('tr');
console.log(TableRows[0].attr('id'));
</pre></code>
====6. What will the value of RowIds[0] be below?====
<code><pre>
var Test5Table = $('table#Test5Table');
var TableRows = Test5Table.find('tr');
var RowIds = [];
TableRows.each( function(i, El) {
RowIds.push(El.attr('id'));
});
console.log(RowIds[0]);
</pre></code>
===7. What will the value of FindEl be below?===
<code><pre>
// build and add element to our document
var elid = 'formbid-0.field';
var NewDiv = $('<div id="'+elid+'" />').text(elid);
$(document.body).append(NewDiv);
var jqid = NewDiv.attr('id');
var FindEl = $(document.body).find('#'+jqid); // note # sign
console.log(jqid, FindEl);
</pre></code>
<div style="display:none;">Answer:
<code><pre>
jesc = jqid.replace('.', '\\.');
var FindEl = $(document.body).find('#'+jesc);
console.log(jesc, FindEl);
</pre></code>
</div>
Additions:
[[http://www.reddit.com/r/programming/comments/aq59o/for_those_of_you_who_dont_know_about_it_firebug/c0iuayh this]] + http://www.dizzler.com/ + http://getfirebug.com/net.html
Deletions:
Additions:
**music on-demand**
http://www.reddit.com/r/programming/comments/aq59o/for_those_of_you_who_dont_know_about_it_firebug/c0iuayh + http://www.dizzler.com/ + http://getfirebug.com/net.html
http://www.reddit.com/r/programming/comments/aq59o/for_those_of_you_who_dont_know_about_it_firebug/c0iuayh + http://www.dizzler.com/ + http://getfirebug.com/net.html
Additions:
[[CocktailNapkin2009 2009 Napkin]]
Deletions:
# 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
%%(python)
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()
[[http://images.google.com/images?imgcolor=teal&imgtbs=clz&hl=en&um=1&q=esselte+journal&sa=N&start=0&ndsp=20&imgsz=l&imgc=specific#start=0&imgtbs=cl&imgc=specific&imgcolor=teal logbook]]
http://www.atk-framework.com/
[[http://images.google.com/images?hl=en&source=hp&q=y%20kant%20tori%20read&um=1&ie=UTF-8&sa=N&tab=wi y kant tori read]] [[http://images.google.com/images?hl=en&um=1&sa=1&q=shaggs&aq=f&oq=&aqi=g10&start=0 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: [[http://upload.wikimedia.org/wikipedia/commons/0/08/Crystal_Clear_app_kget.png component]] [[http://upload.wikimedia.org/wikipedia/commons/3/3a/Crystal_Clear_app_kexi.png behavior]] [[http://upload.wikimedia.org/wikipedia/commons/2/27/Crystal_Clear_mimetype_php.png php]] [[http://upload.wikimedia.org/wikipedia/commons/b/bb/Crystal_Clear_app_khelpcenter.png helper]]
python ungreedy
def re_ungreedy(re_, s):
r = re_.replace('%s', '(.*?)')
return re.search(r, s).groups()
[[http://commons.wikimedia.org/wiki/File:Carrier_Pigeon_(PSF).jpg pigeon sketch]] [[http://commons.wikimedia.org/wiki/Category:John_Gould:The_Birds_of_Europe more birds]] [[http://commons.wikimedia.org/w/index.php?title=Special:Search&ns0=1&ns6=1&ns12=1&ns14=1&redirs=1&search=pigeon&limit=500&offset=20 lots of pigeons]]
[[http://maps.google.com/maps?f=d&source=s_d&saddr=5+First+American+Way,+Santa+Ana,+CA,+92707&daddr=7068+Sepulveda+Blvd,+Van+Nuys,+CA+91405&hl=en&geocode=&mra=ls&sll=37.0625,-95.677068&sspn=47.167389,79.013672&ie=UTF8&z=10 a map]]
Whence malt?
en bikini: http://en.wikipedia.org/wiki/File:World_Map_1689.JPG
Jackson Mystery Song? [[http://www.amazon.com/Japan-Jackson-5/dp/B000BQ1HBO amazon]] [[http://www.youtube.com/watch?v=zd7JU8g-mfs 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 [[http://wikkawiki.org/RecentChangesNotifier?show_comments=1#comments Wikka Recent Changes Notifier]] as a [[http://docs.wikkawiki.org/HandlerInfo 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)
<?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);
?>
[[http://us2.php.net/manual/en/mail.configuration.php PHP Mail Configuration]]
Wikka Slowness: http://wikkawiki.org/ExtremeSlownessWorkaround
# copying svn dir sans svn dirs
$ rsync -r --exclude=.svn /path/to/svn_dir /tmp
%%(javascript)
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_;
%%(javascript)
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);
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:
%%(javascript)
<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>
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
[[http://surfshot.s3.amazonaws.com/media/1/0/1087692-large.jpg windansea 02.18 pm]]
%%(css)
/* background: color image repeat attachment position */
background: #FFCC66 url("file or url name") no-repeat fixed right bottom;
[[http://www.amazon.com/Symposium-Phaedrus-Everymans-Library-Plato/dp/0375411747/ref=si3_rdr_bb_product Plato's Symposium]]
mysqldump dbname | ssh user@remoteserver "cat - > dbname.db"
pastebin: [[Paste20090117 CakePhp Custom Pagination Methods]]
[[http://www.youtube.com/watch?v=P5RDn5Y0D_0&feature=related in case you missed 1978]]
[[http://img160.imageshack.us/img160/6940/socalnowca6.png perfect weather/dead ocean]][[http://cdip.ucsd.edu/models/socal_now.gif current]]
pastebin: [[Paste20090110 Klenwell CakePhp Form Helper]]
python regex (I could have sworn I pasted this here before):
%%(python)
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)
Additions:
some cakephp code
function render($action=NULL, $layout=NULL, $file=NULL) {
if ( $action == null ) {
$action = $this->view_action;
$output = parent::render($action, $layout, $file);
return $output;
function index()
{
$m = 'null';
if ( isset($this->params['pass'][0]) ) {
$m = $this->params['pass'][0];
#debug($this->params);
#debug($m);
if ( method_exists($this, $m) ) {
$this->view_action = sprintf('/journal/%s', $m);
return $this->$m();
else {
$this->set('error', 'page_not_found');
function render($action=NULL, $layout=NULL, $file=NULL) {
if ( $action == null ) {
$action = $this->view_action;
$output = parent::render($action, $layout, $file);
return $output;
function index()
{
$m = 'null';
if ( isset($this->params['pass'][0]) ) {
$m = $this->params['pass'][0];
#debug($this->params);
#debug($m);
if ( method_exists($this, $m) ) {
$this->view_action = sprintf('/journal/%s', $m);
return $this->$m();
else {
$this->set('error', 'page_not_found');
Additions:
bash 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
# 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
Additions:
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>
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);
Additions:
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})
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})
Additions:
DataSet = []
for row in RowList:
DataSet .append(self.parse_row(row))
return DataSet
for row in RowList:
DataSet .append(self.parse_row(row))
return DataSet
Deletions:
DataSet = {
return ParsedSet
Additions:
and avoid errors like this:
_csv.Error: line contains NULL byte
The secret sauce:
http://docs.python.org/library/csv.html#csv-examples
file-reading generator
_csv.Error: line contains NULL byte
The secret sauce:
http://docs.python.org/library/csv.html#csv-examples
file-reading generator
Deletions:
straight file read for debug
Additions:
UniversalCsvReader
class UniversalCsvParser:
"""
A parser that attempts to deal magically with troublesome encoding issues
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)
ParsedSet = self.parse_file(RowList)
# here you can do transformations and return new dict or just return ZipDict
DataSet = {
}
return ParsedSet
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):
"""
straight file read for debug
"""
f = open(path, "rU")
for line in f:
yield line
f.close()
class UniversalCsvParser:
"""
A parser that attempts to deal magically with troublesome encoding issues
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)
ParsedSet = self.parse_file(RowList)
# here you can do transformations and return new dict or just return ZipDict
DataSet = {
}
return ParsedSet
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):
"""
straight file read for debug
"""
f = open(path, "rU")
for line in f:
yield line
f.close()
Additions:
[[http://images.google.com/images?imgcolor=teal&imgtbs=clz&hl=en&um=1&q=esselte+journal&sa=N&start=0&ndsp=20&imgsz=l&imgc=specific#start=0&imgtbs=cl&imgc=specific&imgcolor=teal logbook]]
Additions:
http://www.atk-framework.com/
Additions:
[[http://images.google.com/images?hl=en&source=hp&q=y%20kant%20tori%20read&um=1&ie=UTF-8&sa=N&tab=wi y kant tori read]] [[http://images.google.com/images?hl=en&um=1&sa=1&q=shaggs&aq=f&oq=&aqi=g10&start=0 shaggs]]
Deletions:
Additions:
[[http://images.google.com/images?hl=en&source=hp&q=y%20kant%20tori%20read&um=1&ie=UTF-8&sa=N&tab=wi y kant tori read]]
Additions:
jquery scroll
print $javascript->link('jcarousellite_1.0.1.min.js');
<div id="text_list">
<ul>
<li>beginning</li>
</ul>
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
});
print $javascript->link('jcarousellite_1.0.1.min.js');
<div id="text_list">
<ul>
<li>beginning</li>
</ul>
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
});
Additions:
sample jquery json
$(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;
});
});
});
$(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;
});
});
});
Additions:
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
# 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
Additions:
icons: [[http://upload.wikimedia.org/wikipedia/commons/0/08/Crystal_Clear_app_kget.png component]] [[http://upload.wikimedia.org/wikipedia/commons/3/3a/Crystal_Clear_app_kexi.png behavior]] [[http://upload.wikimedia.org/wikipedia/commons/2/27/Crystal_Clear_mimetype_php.png php]] [[http://upload.wikimedia.org/wikipedia/commons/b/bb/Crystal_Clear_app_khelpcenter.png helper]]
Additions:
r = re_.replace('%s', '(.*?)')
Deletions:
Additions:
return re.search(r, s).groups()
Deletions:
Additions:
python ungreedy
def re_ungreedy(re_, s):
r = re_ % ('(.*?)')
return re.search(r, s).groups()[0]
def re_ungreedy(re_, s):
r = re_ % ('(.*?)')
return re.search(r, s).groups()[0]
Additions:
[[http://commons.wikimedia.org/wiki/File:Carrier_Pigeon_(PSF).jpg pigeon sketch]] [[http://commons.wikimedia.org/wiki/Category:John_Gould:The_Birds_of_Europe more birds]] [[http://commons.wikimedia.org/w/index.php?title=Special:Search&ns0=1&ns6=1&ns12=1&ns14=1&redirs=1&search=pigeon&limit=500&offset=20 lots of pigeons]]
Deletions:
Additions:
[[http://commons.wikimedia.org/wiki/File:Carrier_Pigeon_(PSF).jpg pigeon sketch]]
Additions:
[[http://maps.google.com/maps?f=d&source=s_d&saddr=5+First+American+Way,+Santa+Ana,+CA,+92707&daddr=7068+Sepulveda+Blvd,+Van+Nuys,+CA+91405&hl=en&geocode=&mra=ls&sll=37.0625,-95.677068&sspn=47.167389,79.013672&ie=UTF8&z=10 a map]]
Additions:
Whence malt?
Additions:
en bikini: http://en.wikipedia.org/wiki/File:World_Map_1689.JPG
Additions:
Jackson Mystery Song? [[http://www.amazon.com/Japan-Jackson-5/dp/B000BQ1HBO amazon]] [[http://www.youtube.com/watch?v=zd7JU8g-mfs youtube]]
Additions:
$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);
$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);
Additions:
RewriteRule ^rewrite(.*)\/?(.*)$ rewrite.php?q=$1 [QSA,L]
Deletions:
Additions:
<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>
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>
Additions:
[[CocktailQuestions Questions for Strangers]]
Additions:
http://search.twitter.com/search?q=lastgoogle
Additions:
%%(php)
<?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);
?>
<?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);
?>
Additions:
%%find ~/qed/ -maxdepth 4 -name "*.conf" | xargs perl -w -i -p -e "s/VirtualHost 127.0.0.1/VirtualHost */g"%%
Additions:
http://www.klenwell.com/press/2009/04/formencode-state/
Deletions:
# in controller
class FormencodeState(object):
"""
State class for formencode
Although NOT well documented, to use the state argument in the to_python
method in the context of schema that does complex, multistep validation,
the state argument must be an object that formencode can hang additional
attributes from, else you get errors like:
Module formencode.schema:114 in _to_python
>> state.full_dict = value_dict
<type 'exceptions.AttributeError'>: 'dict' object has no attribute 'full_dict'
"""
pass
...
Validator = SourceDataPreValidator()
ControllerState = FormencodeState()
ControllerState.source = 'csv'
Validator.to_python(DataValue, ControllerState)
# in validator
class SourceDataPreValidator(formencode.validators.FormValidator):
"""normalize data from either a form submission or a csv file upload and validate"""
validate_partial_form = True
def _to_python(self, value, state):
"""normalize csv input"""
if state.source == 'csv':
value['normal_data'] = self._normalize_csv_data(value.get('csv_import_file'), state)
elif state.source == 'form':
pass
return value
def _normalize_import_data(self, csv_file_string, state):
NormalDataList = []
ImportedLines = csv_file_string.split('\n')
for i in range(len(ImportedLines)):
ColValues = ImportedLines[i].split(',')
fpre = 'csv_import-' + str(i)
NormalDataList.append((fpre + '.id', str(ColValues[1])))
NormalDataList.append((fpre + '.amount', str(ColValues[2])))
NormalDataList.append((fpre + '.date',
self._importdate_to_python_date(ColValues[4])))
return NormalDataList
def _importdate_to_python_date(self, datestr):
"""some code to convert a date string to object"""
pass
Additions:
~~- adding setting for max_frequency and if time() - last_emailed < $mail_no_more_than_every, exit
Deletions:
Additions:
~- enforce access through url: domain.com/wikka/$access_code/recent_changes
~- 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 < max_mail_frequency, 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)
~- 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 < max_mail_frequency, 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)
Deletions:
Additions:
~- enforce access through url: domain.com/wikka/$access_code/mail_changes_to_admin
~- add setting for $access_code
~- add setting for $access_code
Deletions:
~- add setting for $cron_code
Additions:
Reconfigure as [[http://wikkawiki.org/RecentChangesNotifier?show_comments=1#comments Wikka Recent Changes Notifier]] as a [[http://docs.wikkawiki.org/HandlerInfo handler]]
~- enforce security through url: domain.com/wikka/$cron_code/mail_changes_to_admin
~- add setting for $cron_code
~- check that url match $cron_code
~- add setting for email, but default to wiki admin
~- enforce security through url: domain.com/wikka/$cron_code/mail_changes_to_admin
~- add setting for $cron_code
~- check that url match $cron_code
~- add setting for email, but default to wiki admin
Deletions:
Additions:
Reconfigure as [[http://wikkawiki.org/RecentChangesNotifier?show_comments=1#comments Wikka Recent Changes Notifier]] as a [[http://docs.wikkawiki.org/HandlerInfo handler]]
Additions:
[[http://us2.php.net/manual/en/mail.configuration.php PHP Mail Configuration]]
Additions:
Wikka Slowness: http://wikkawiki.org/ExtremeSlownessWorkaround
Additions:
# copying svn dir sans svn dirs
$ rsync -r --exclude=.svn /path/to/svn_dir /tmp
$ rsync -r --exclude=.svn /path/to/svn_dir /tmp
Additions:
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_;
Additions:
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);
Page was generated in 9.3332 seconds!
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!
Additions:
Komodo Current File Path
prompt('current file path', gViewMgr.currentView.document.file.path)
prompt('current file path', gViewMgr.currentView.document.file.path)
Deletions:
(
[op] => max supported int: 2^52 or 4503599627370496
[bc] => max supported int >= 2^999 or 5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688
)
Deletions:
<?php
$max = 1000;
foreach ( range(1,$max) as $x )
{
if (
! ( pow(2,$x)+1 > pow(2,$x) ) ||
! ( pow(2,$x)-1 < pow(2,$x) ) ||
! ( pow(2,$x-1)*2 == pow(2,$x) )
) break;
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['op'] = "max supported int: 2^$maxpow or $maxint\n";
foreach ( range(1,$max) as $x )
{
if (
! ( bccomp(bcadd(bcpow(2,$x),1), bcpow(2,$x)) == 1 ) ||
! ( bccomp(bcsub(bcpow(2,$x),1), bcpow(2,$x)) == -1 ) ||
! ( bccomp(bcmul(bcpow(2,$x-1),2), bcpow(2,$x)) == 0 )
) break;
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['bc'] = "max supported int >= 2^$maxpow or $maxint\n";
printf("<pre>%s</pre>", print_r($Result,1));
?>
Additions:
%%(php)
<?php
$max = 1000;
foreach ( range(1,$max) as $x )
{
if (
! ( pow(2,$x)+1 > pow(2,$x) ) ||
! ( pow(2,$x)-1 < pow(2,$x) ) ||
! ( pow(2,$x-1)*2 == pow(2,$x) )
) break;
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['op'] = "max supported int: 2^$maxpow or $maxint\n";
foreach ( range(1,$max) as $x )
{
if (
! ( bccomp(bcadd(bcpow(2,$x),1), bcpow(2,$x)) == 1 ) ||
! ( bccomp(bcsub(bcpow(2,$x),1), bcpow(2,$x)) == -1 ) ||
! ( bccomp(bcmul(bcpow(2,$x-1),2), bcpow(2,$x)) == 0 )
) break;
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['bc'] = "max supported int >= 2^$maxpow or $maxint\n";
printf("<pre>%s</pre>", print_r($Result,1));
?>
Array
(
[op] => max supported int: 2^52 or 4503599627370496
[bc] => max supported int >= 2^999 or 5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688
)
<?php
$max = 1000;
foreach ( range(1,$max) as $x )
{
if (
! ( pow(2,$x)+1 > pow(2,$x) ) ||
! ( pow(2,$x)-1 < pow(2,$x) ) ||
! ( pow(2,$x-1)*2 == pow(2,$x) )
) break;
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['op'] = "max supported int: 2^$maxpow or $maxint\n";
foreach ( range(1,$max) as $x )
{
if (
! ( bccomp(bcadd(bcpow(2,$x),1), bcpow(2,$x)) == 1 ) ||
! ( bccomp(bcsub(bcpow(2,$x),1), bcpow(2,$x)) == -1 ) ||
! ( bccomp(bcmul(bcpow(2,$x-1),2), bcpow(2,$x)) == 0 )
) break;
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['bc'] = "max supported int >= 2^$maxpow or $maxint\n";
printf("<pre>%s</pre>", print_r($Result,1));
?>
Array
(
[op] => max supported int: 2^52 or 4503599627370496
[bc] => max supported int >= 2^999 or 5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688
)
Additions:
formencode state: http://wiki.pylonshq.com/display/pylonscookbook/The+other+FormEncode+manual+(UNFINISHED) (see bottom)
# in controller
class FormencodeState(object):
"""
State class for formencode
Although NOT well documented, to use the state argument in the to_python
method in the context of schema that does complex, multistep validation,
the state argument must be an object that formencode can hang additional
attributes from, else you get errors like:
Module formencode.schema:114 in _to_python
>> state.full_dict = value_dict
<type 'exceptions.AttributeError'>: 'dict' object has no attribute 'full_dict'
"""
pass
...
Validator = SourceDataPreValidator()
ControllerState = FormencodeState()
ControllerState.source = 'csv'
Validator.to_python(DataValue, ControllerState)
# in validator
class SourceDataPreValidator(formencode.validators.FormValidator):
"""normalize data from either a form submission or a csv file upload and validate"""
validate_partial_form = True
def _to_python(self, value, state):
"""normalize csv input"""
if state.source == 'csv':
value['normal_data'] = self._normalize_csv_data(value.get('csv_import_file'), state)
elif state.source == 'form':
pass
return value
def _normalize_import_data(self, csv_file_string, state):
NormalDataList = []
ImportedLines = csv_file_string.split('\n')
for i in range(len(ImportedLines)):
ColValues = ImportedLines[i].split(',')
fpre = 'csv_import-' + str(i)
NormalDataList.append((fpre + '.id', str(ColValues[1])))
NormalDataList.append((fpre + '.amount', str(ColValues[2])))
NormalDataList.append((fpre + '.date',
self._importdate_to_python_date(ColValues[4])))
return NormalDataList
def _importdate_to_python_date(self, datestr):
"""some code to convert a date string to object"""
pass
# in controller
class FormencodeState(object):
"""
State class for formencode
Although NOT well documented, to use the state argument in the to_python
method in the context of schema that does complex, multistep validation,
the state argument must be an object that formencode can hang additional
attributes from, else you get errors like:
Module formencode.schema:114 in _to_python
>> state.full_dict = value_dict
<type 'exceptions.AttributeError'>: 'dict' object has no attribute 'full_dict'
"""
pass
...
Validator = SourceDataPreValidator()
ControllerState = FormencodeState()
ControllerState.source = 'csv'
Validator.to_python(DataValue, ControllerState)
# in validator
class SourceDataPreValidator(formencode.validators.FormValidator):
"""normalize data from either a form submission or a csv file upload and validate"""
validate_partial_form = True
def _to_python(self, value, state):
"""normalize csv input"""
if state.source == 'csv':
value['normal_data'] = self._normalize_csv_data(value.get('csv_import_file'), state)
elif state.source == 'form':
pass
return value
def _normalize_import_data(self, csv_file_string, state):
NormalDataList = []
ImportedLines = csv_file_string.split('\n')
for i in range(len(ImportedLines)):
ColValues = ImportedLines[i].split(',')
fpre = 'csv_import-' + str(i)
NormalDataList.append((fpre + '.id', str(ColValues[1])))
NormalDataList.append((fpre + '.amount', str(ColValues[2])))
NormalDataList.append((fpre + '.date',
self._importdate_to_python_date(ColValues[4])))
return NormalDataList
def _importdate_to_python_date(self, datestr):
"""some code to convert a date string to object"""
pass
Additions:
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>
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>
Deletions:
var dog = {
name: "Fido",
breed: "beagle",
speak: function () {
alert('ruff ruff');
Additions:
json class (http://www.prototypejs.org/learn/class-inheritance):
%%(javascript)
var dog = {
name: "Fido",
breed: "beagle",
speak: function () {
alert('ruff ruff');
}
}
%%(javascript)
var dog = {
name: "Fido",
breed: "beagle",
speak: function () {
alert('ruff ruff');
}
}
Additions:
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
# 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
Additions:
[[http://surfshot.s3.amazonaws.com/media/1/0/1087692-large.jpg windansea 02.18 pm]]
Deletions:
Additions:
http://surfshot.s3.amazonaws.com/media/1/0/1087692-large.jpg
Additions:
%%(css)
/* background: color image repeat attachment position */
background: #FFCC66 url("file or url name") no-repeat fixed right bottom;
/* background: color image repeat attachment position */
background: #FFCC66 url("file or url name") no-repeat fixed right bottom;
Additions:
[[http://www.amazon.com/Symposium-Phaedrus-Everymans-Library-Plato/dp/0375411747/ref=si3_rdr_bb_product Plato's Symposium]]
Additions:
mysqldump dbname | ssh user@remoteserver "cat - > dbname.db"
Additions:
pastebin: [[Paste20090117 CakePhp Custom Pagination Methods]]
pastebin: [[Paste20090110 Klenwell CakePhp Form Helper]]
pastebin: [[Paste20090110 Klenwell CakePhp Form Helper]]
Deletions:
Additions:
[[http://www.youtube.com/watch?v=P5RDn5Y0D_0&feature=related in case you missed 1978]]
Additions:
[[http://img160.imageshack.us/img160/6940/socalnowca6.png perfect weather/dead ocean]][[http://cdip.ucsd.edu/models/socal_now.gif current]]
Deletions:
Additions:
[[http://cdip.ucsd.edu/models/socal_now.gif perfect weather/dead ocean]]
Additions:
pastebin: [[Paste20090110 Klenwell Form Helper]]
Deletions:
Additions:
pastebin: Paste20090110
Additions:
python regex (I could have sworn I pasted this here before):
%%(python)
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)
%%
%%(python)
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)
%%
Additions:
[[CocktailNapkin2008 2008 Napkin]]
[[CocktailNapkin2007 2007 Napkin]]
[[CocktailNapkin2007 2007 Napkin]]
Deletions:
SpecialCakePhpModelTesting
mysql: value in one table not another
%%(mysql)SELECT somecol FROM a WHERE somecol NOT IN ( SELECT somecol FROM b )%%
%%CREATE TABLE db2.table LIKE db1.table;
INSERT INTO db2.table SELECT * FROM db1.table;%%
[[http://www.nytimes.com/2008/11/10/opinion/10krugman.html in defense of public works projects]]
cakephp form "multiple models": [[http://book.cakephp.org/view/189/Automagic-Form-Elements Form Helper]] [[http://book.cakephp.org/view/125/Data-Validation Data Validation]] [[http://book.cakephp.org/view/75/Saving-Your-Data Models]] [[http://bakery.cakephp.org/articles/view/improved-advance-validation-with-parameters bakery article]] [[http://teknoid.wordpress.com/2008/06/09/15-essential-cakephp-tips/ teknoid tips]]
waves 11/5 in oside: [[http://surfshot.s3.amazonaws.com/media/1/0/1043981-large.jpg 1]] [[http://surfshot.s3.amazonaws.com/media/1/0/1043975-large.jpg 2]] [[http://surfshot.s3.amazonaws.com/media/1/0/1043980-large.jpg 3]]
[[SpecialCrondSample Sample cron.d file]]
http://forum.notebookreview.com/showthread.php?t=294364 [[http://accessories.us.dell.com/sna/products/Motherboards/productdetail.aspx?c=us&l=en&s=bsd&cs=04&sku=TT359&mfgpid=192256&chassisid=8544#Overview order]]
HG: Add path to new repository:
%%
# web server paths
[paths]
# virtual/path (http:/domain/name = /real/path)
test = /home/klenwell/root/tmp/hgtest
new_repo = /path/to/repo
[web]
style = gitweb
contact = admin@email.com
description = mercurial repositories
name = central repository
%%
http://bitchphd.blogspot.com/
[[http://www.nytimes.com/slideshow/2008/08/31/travel/0831-BIARRITZ_index.html photos that actually make me want to travel again]]
http://freakonomics.blogs.nytimes.com/2008/08/20/have-economic-debates-changed-since-1977/index.html?hp
http://garfield.nfshost.com/?s=lasagna&p=2
[[http://www.nytimes.com/2008/08/17/books/review/Donadio-t.html?8bu&emc=bu blurbs]]
python [[http://docs.python.org/lib/node46.html re]]:
%%(python)
try:
result = re.search(pattern, subject, re.S).groups()[0]
return result
except Exception, e:
return False
%%
logrotate: http://linux.about.com/od/commands/l/blcmdl8_logrota.htm http://www.linux.com/articles/48390
[[http://www.newyorker.com/talk/comment/2008/07/28/080728taco_talk_cassidy For some twenty years, politicians of both parties have been using free-market rhetoric as a cover for favors to big campaign contributors.]]
linux autostop: ""<tt>ps aux | grep 'foo' | awk '{print $2}' | xargs kill -9</tt>""
[[http://www.nytimes.com/2008/07/20/business/20debt.html?th&emc=th junk fees]]
[[http://www.faqts.com/knowledge_base/view.phtml/aid/30990/fid/53 js __file__]]
[[http://ask.slashdot.org/askslashdot/08/07/18/0046220.shtml os for old machines]]
[[http://nltk.sourceforge.net/index.php/Getting_Started python nltk]] [[http://www.abisource.org/projects/link-grammar/ link grammar parser]]
[[http://www.nytimes.com/2008/07/13/magazine/13officer-t.html?pagewanted=all 2nd Amendment as Foreign Policy Issue]]
[[http://judson.blogs.nytimes.com/2008/07/15/lets-get-rid-of-darwinism/index.html Against Darwinism]]
[[http://it.slashdot.org/comments.pl?sid=613269&cid=24182529 columbo 2.0]]
[[http://arstechnica.com/news.ars/post/20080708-hands-on-googles-lively-social-3d-world-is-20-percent-done.html Google Lively]] (for sonnet monkeys?)
[[http://tech.slashdot.org/article.pl?sid=08/07/08/0116238 Handling Flash Crowds from your Garage]]
AVG alternatives: [[http://www.clamwin.com/ clamwin]] [[http://www.avast.com/ avast]]
[[http://www.makelinux.net/kernel_map linux kernel map]]
To Do: take a charge in the break room
[[http://www.bbc.co.uk/languages/spanish/ BBC Spanish]] [[http://www.bravenewtraveler.com/2008/02/04/8-free-online-resources-for-learning-a-new-language/ free language lessons]]
I'll have to check this out when I get home: http://icanhaslolpron.com
[[http://sites.google.com/ Google wiki]]
http://www.worldcat.org/
bad housing news: [[http://calculatedrisk.blogspot.com/2008/03/real-case-shiller-house-price-index.html calculatedrisk]] [[http://sdhpi.blogspot.com/2008/05/is-this-bottom.html sdhpi]] [[http://en.wikipedia.org/wiki/Case-Shiller_index Case-Shiller]]
[[http://tech.slashdot.org/comments.pl?sid=592263&cid=23904759 /. troll of the day and riposte]]
""<tt>A[HREF*="myspace.com"]:after { content: " [BRAIN DAMAGE WARNING]"!important ; color: red }</tt>"" ([[http://tech.slashdot.org/comments.pl?sid=592263&cid=23904767 source]])
[[http://www.nytimes.com/2008/06/17/science/17mund.html steampunk web]] (almost literally)
.hg [[http://www.selenic.com/mercurial/wiki/index.cgi/UsingExtensions extensions]]:
%%(python)
[extensions]
# Enable the 'glog' graphical log extension
hgext.graphlog =
# Enable CVS style variable substitution
hgext.keyword =
%%
[[http://seehuhn.de/pages/pdate python dates and times]] (I'm always forgetting this crap):
%%(python)
import datetime, time
print datetime.datetime.now() # current local datetime
print time.time() # unix timestamp
%%
[[http://www.simulation-argument.com/classic.html simulation argument]]
a pythonic tribute to [[http://forums.xkcd.com/viewtopic.php?f=11&t=23249 xkcd]]: ""<code>xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([str(int(k in t)) for t in [c,d]]),2)])[k] or x</code>""
more django: [[http://www.djangoproject.com/documentation/modelforms/ modelforms]] [[http://www.djangoproject.com/documentation/newforms/#modelmultiplechoicefield forms]]
rent or buy: http://www.nytimes.com/2008/05/28/business/28leonhardt.html [[http://www.nytimes.com/2007/04/10/business/2007_BUYRENT_GRAPHIC.html? calculator]]
[[http://en.wikipedia.org/wiki/Pitaya dragonfruit]]
[[http://code.google.com/apis/ajaxlibs/ google ajaxlibs]] ([[http://developers.slashdot.org/developers/08/05/28/144218.shtml /.]])
[[http://www.nytimes.com/2008/05/28/dining/28flavor.html flavor-tripping]]
[[http://home.netcom.com/~tjensen/ptr/ch1x.htm pointers]] (to the point)
[[http://www.fonts500.com/?page=1 500 Fonts]] [[http://thepiratebay.org/tor/3660252/500_Fonts_from_fonts500.com all at once]]
[[http://tech.slashdot.org/comments.pl?sid=565231&cid=23559299 leave it to Jesus 666]]
[[http://www.djangoproject.com/documentation/forms/ django forms]] [[http://www.djangoproject.com/documentation/newforms/ django newforms]] [[http://code.google.com/appengine/articles/djangoforms.html django form validation]] [[http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms/widgets.py django form tests (examples)]] [[http://www.djangoproject.com/documentation/form_wizard/ django forms wizard]]
scripps 05.23: [[http://surfshot.s3.amazonaws.com/media/9/7/975364-large.jpg 1]] [[http://surfshot.s3.amazonaws.com/media/9/7/975363-large.jpg 2]] [[http://surfshot.s3.amazonaws.com/media/9/7/975370-large.jpg 3]]
http://code.google.com/p/google-app-engine-samples/wiki/GoogleAppEngineSamples [[http://groups.google.com/group/google-appengine/browse_frm/thread/d3673d0ec7ead0e2 djangoforms]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/13d1f026d46bd35f model keys]]
[[http://archive.ics.uci.edu/ml/ lots of data]] (courtesy of my alma mater)
[[http://highscalability.com/how-i-learned-stop-worrying-and-love-using-lot-disk-space-scale querying gapp]]
http://img143.imageshack.us/img143/3660/fbooknb5.png
sessions: [[http://groups.google.com/group/google-appengine/browse_frm/thread/1c459b2ca7a6e643/2311877beffe0403?lnk=gst&q=session#2311877beffe0403 datastore]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/f162c186c3e68f1a/1ea824e3bebd5801?lnk=gst&q=session#1ea824e3bebd5801 class]] [[http://code.google.com/appengine/docs/python/appcaching.html appcaching]]
[[http://entertainment.slashdot.org/comments.pl?sid=556912&cid=23461200 mythbuntu]]
[[http://www.rinkworks.com/words/collective.shtml words for groups of animals]]
[[http://kwap.appspot.com/ klenwell @ google app engine]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/c9e8a906a88a8102 links to good gapp tips]]
[[http://us2.php.net/manual/en/function.debug-backtrace.php#72534 php debug]]
[[http://www.nytimes.com/2008/05/13/world/middleeast/13girls.html?_r=1&hp=&pagewanted=all Project Alia]]
[[http://entertainment.slashdot.org/entertainment/08/05/13/0316251.shtml free as in beer beer]]
[[http://www.msnbc.msn.com/id/23359042/from/ET/ no plastic surgery!]]
[[http://www.housingmaps.com/ housingmaps.com]]
on fonts: [[http://fontstruct.fontshop.com/ fontstruct]] [[http://www.sweeperscalendar.com/variorum/1129/ the prophecy]]
stupid lambda tricks: ""<code>in_dict_list = lambda dic, k, v: v in [d[k] for d in dic]</code>""
[[http://www.nytimes.com/2008/05/08/fashion/08PUNK.html?_r=1&oref=slogin steampunk]] ""=="" [[http://en.wikipedia.org/wiki/Tomorrowland#Tomorrowland_1998 tomorrowland 1998]]
[[http://code.google.com/appengine/docs/gettingstarted/ google app engine]] [[http://blog.wachob.com/2008/04/google-appengin.html scaling with gae]] [[http://perspectives.mvdirona.com/2008/04/21/GoogleApplicationEngine.aspx a review]] [[http://code.google.com/appengine/docs/python/purepython.html python in gae]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/dc927ba00944027f gApp on ubuntu]] [[http://code.google.com/p/rietveld/source/browse gApp example code]]
[[http://aspn.activestate.com/ASPN/docs/Komodo/4.3/komodo-js-api.html komodo js api]]
[[http://en.wikipedia.org/wiki/AI_Winter AI Winter]] [[http://www.nytimes.com/2008/05/03/technology/03koller.html?th&emc=th is over]]
http://www.gnu.org/software/diction/ http://www.link.cs.cmu.edu/link/ [[http://alanhorkan.livejournal.com/16062.html overview]] [[http://papyr.com/hypertextbooks/grammar/gramchek.htm tests]] [[http://en.wikipedia.org/wiki/Grammar_checker wikipedia]]
[[http://pidgin.im/ pidgin]] (nice home page)
[[http://www.herecomeseverybody.org/2008/04/looking-for-the-mouse.html the sitcom]] [[http://tech.slashdot.org/tech/08/04/27/1422258.shtml (./)]] | [[http://tech.slashdot.org/article.pl?sid=08/04/30/1515229 Berners-Lee on Web]]
[[http://www.shoutcast.com/directory/index.phtml shoutcast streams]] see also [[http://lifehacker.com/384545/superior-alternatives-to-crappy-windows-software vlc]]
[[http://yro.slashdot.org/comments.pl?sid=537280&cid=23231314 /. life lessons: if arrested...]]
[[http://politics.slashdot.org/comments.pl?sid=228403&cid=18513137 John McCain ad hominem]]
[[http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references HTML entities]]
[[http://en.wikipedia.org/wiki/Simon-Ehrlich_wager Simon-Ehrlich Wager]] [[http://krugman.blogs.nytimes.com/2008/04/22/limits-to-growth-and-related-stuff/ Krugman]]
[[http://www.selenic.com/pipermail/mercurial/2007-April/012921.html removing a file from a python repo without deleting]] **use hg rm -A** (e.g. hg rm -A dir/*)
[[http://www.nytimes.com/2008/04/24/books/24garn.html?_r=1&th&emc=th&oref=slogin kleinzahler]]
[[http://www.ocfamily.com/t-FeatureStory_BabyNames_0408.aspx oc baby names]]
[[http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml komodo edit]] [[http://community.activestate.com/faq/komodo-file-locations saving preference file]]
[[http://code.google.com/apis/igoogle/ igoogle API]]
[[http://tech.slashdot.org/article.pl?sid=08/04/16/121225&from=rss Yahoo Analytics (IndexTools)]]
[[http://www.pseudocoder.com/archives/2007/02/27/cakephp-cache-performance/ cakephp cache benchmark]]
%%(bash)
# cron.d file
# to activate, link to /etc/cron.d: ln -s <path>/fname.cron /etc/cron.d/link_name
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# M H DM MO DW USER SCRIPT
%%
[[http://www.nytimes.com/2008/04/21/opinion/21krugman.html the commodities bubble]]
[[http://tech.slashdot.org/comments.pl?sid=526820&cid=23115228 oss binary blobs]]
emacs: [[http://www.google.com/search?q=customize+emacs+-scribd.com&hl=en&lr=&as_qdr=all&start=10&sa=N customize]] [[http://www.google.com/search?hl=en&lr=&as_qdr=all&q=+site:www.gnu.org+customize+emacs+-scribd.com manual]] [[http://www.gnu.org/software/emacs/tour/ tour]]
[[http://forums.xkcd.com/viewtopic.php?f=11&t=11935&st=0&sk=t&sd=a&start=440#p693630 a mighty daemon]]
[[http://w-shadow.com/blog/2008/04/12/simple-text-summarizer-in-php/ simple text summarizer]] [[http://www.symfony-project.org/askeet/1_0/21 simple search engine]]
ny times: [[http://www.nytimes.com/2008/04/13/business/13cash.html?th=&emc=th&pagewanted=all wall st. sleaze]] [[http://www.nytimes.com/2008/04/14/business/media/14link.html?th=&emc=th&pagewanted=all some guy who wrote a program to write 200,000 books]]
cakephp: [[http://book.cakephp.org/view/32/installation#advanced-installation-35 shared core setup]] [[http://bakery.cakephp.org/articles/view/maintaining-an-application-independant-code-library app-indy lib]] [[http://manual.cakephp.org/chapter/plugins plugins]]
[[http://bakery.cakephp.org/ <a href="http://mushpup.org/">pw</a>: m{d/u}l11]]
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP [[http://dev.mysql.com/doc/refman/4.1/en/timestamp.html mysql.com]]
python encoding: [[http://mail.python.org/pipermail/python-list/2007-May/442985.html nutshell]] [[http://www.reportlab.com/i18n/python_unicode_tutorial.html unicode tutorial]]
python on web: [[http://www.modpython.org/ modpython]] [[http://www.zope.org/ zope]] [[http://code.google.com/appengine/docs/gettingstarted/ google webapp]]
[[http://code.google.com/appengine/docs/whatisgoogleappengine.html google app engine]]
vim: [[http://www.linux.com/articles/54159 marks and jumps]]
PHP PCRE Issue: [[http://us3.php.net/manual/en/ref.pcre.php#77790 cause]] [[http://www.phpinsider.com/smarty-forum/viewtopic.php?p=48604 cause]] [[http://bugs.php.net/bug.php?id=40846 bugs.php.net]] [[http://tracker.moodle.org/browse/MDL-11237?focusedCommentId=34538#action_34538 a solution]]
[[http://en.wikipedia.org/wiki/Moby_Project Moby Project]] [[http://www.nzdl.org/ELKB/download.html Roget's]]
[[http://cb.vu/unixtoolbox.xhtml unix cheat sheet]]
[[http://www.dell.com/content/products/productdetails.aspx/vostronb_1400?c=us&cs=04&l=en&s=bsd&~tab=bundlestab vostro 1400]]
[[http://www.interest.com/content/calculators/rentvsbuy.asp rent v. buy]] [[http://www.bloomberg.com/invest/calculators/mortgage.html bloomberg mortgage calculator]]
[[SpecialBCAA BCAA]]
[[http://garfieldminusgarfield.tumblr.com/ Garfield - Garfield = Existential Humor]]
Cool Dingbats: [[http://www.bittbox.com/fonts/dingbats-roundup-16-incredibly-detailed-useful-and-free-dingbat-fonts/ bittbox.com]]
Tivo for Radio: [[http://www.handcoding.com/archives/2005/03/20/ripping-npr-to-mp3-for-an-ipod/ excellent tutorial]] [[http://streamripper.sourceforge.net/ streamripper]] (windows or linux)
OS Flash Dev: [[http://www.mtasc.org/ MTASC]] [[http://www.flashdevelop.org/community/viewtopic.php?t=305 flashdevelop.org]] [[http://fgpwiki.corewatch.net/index.php/How_do_I_get_Started game dev]]
""CakePhp"" config: [[http://www.virtualapplicationserver.com/CakePHP_MultipleInstallNotes.html multiple apps on single site]] [[http://bakery.cakephp.org/articles/view/hosting-admin-urls-on-a-subdomain admin subdomain]]
SSL on Debian ""Apache2"": [[http://ilovett.com/blog/projects/installing-ssl-on-debian-apache2 ilovett.com]] [[http://www.debian-administration.org/articles/349 debian-administration.org]]
[[http://slashdot.org/article.pl?sid=08/01/06/1731247 Goodbye Cruel Word]]: Hello, [[http://www.lyx.org/ lyx]]!
Fun with apache logs: [[http://russell.dyerhouse.com/cgi-bin/article.cgi?article_id=82 set-up]] [[http://www.builderau.com.au/program/unix/soa/Managing-and-parsing-your-Apache-logs/0,339024638,320280756,00.htm parsing]] [[http://crazytoon.com/2007/05/31/apache-how-do-you-set-up-log-rotation-and-archiving-for-apache-logs/ archiving logs]] [[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Additions:
SpecialCakePhpModelTesting
Additions:
%%(mysql)SELECT somecol FROM a WHERE somecol NOT IN ( SELECT somecol FROM b )%%
Deletions:
Additions:
mysql: value in one table not another
%%(mysql)SELECT field FROM a WHERE field NOT IN ( SELECT field FROM b )%%
%%(mysql)SELECT field FROM a WHERE field NOT IN ( SELECT field FROM b )%%
Additions:
%%CREATE TABLE db2.table LIKE db1.table;
INSERT INTO db2.table SELECT * FROM db1.table;%%
INSERT INTO db2.table SELECT * FROM db1.table;%%
Additions:
[[http://www.nytimes.com/2008/11/10/opinion/10krugman.html in defense of public works projects]]
Additions:
cakephp form "multiple models": [[http://book.cakephp.org/view/189/Automagic-Form-Elements Form Helper]] [[http://book.cakephp.org/view/125/Data-Validation Data Validation]] [[http://book.cakephp.org/view/75/Saving-Your-Data Models]] [[http://bakery.cakephp.org/articles/view/improved-advance-validation-with-parameters bakery article]] [[http://teknoid.wordpress.com/2008/06/09/15-essential-cakephp-tips/ teknoid tips]]
Deletions:
Additions:
cakephp form "multiple models": [[http://bakery.cakephp.org/articles/view/improved-advance-validation-with-parameters bakery article]] [[http://teknoid.wordpress.com/2008/06/09/15-essential-cakephp-tips/ teknoid tips]]
Deletions:
[[http://teknoid.wordpress.com/2008/06/09/15-essential-cakephp-tips/ teknoid tips]]
Additions:
cakephp form "multiple models": [[http://bakery.cakephp.org/articles/view/improved-advance-validation-with-parameters bakery article]]
[[http://teknoid.wordpress.com/2008/06/09/15-essential-cakephp-tips/ teknoid tips]]
[[http://teknoid.wordpress.com/2008/06/09/15-essential-cakephp-tips/ teknoid tips]]
Additions:
waves 11/5 in oside: [[http://surfshot.s3.amazonaws.com/media/1/0/1043981-large.jpg 1]] [[http://surfshot.s3.amazonaws.com/media/1/0/1043975-large.jpg 2]] [[http://surfshot.s3.amazonaws.com/media/1/0/1043980-large.jpg 3]]
Deletions:
Additions:
waves 11/5: [[http://surfshot.s3.amazonaws.com/media/1/0/1043981-large.jpg 1]] [[http://surfshot.s3.amazonaws.com/media/1/0/1043975-large.jpg 2]] [[http://surfshot.s3.amazonaws.com/media/1/0/1043980-large.jpg 3]]
Additions:
[[SpecialCrondSample Sample cron.d file]]
Additions:
http://forum.notebookreview.com/showthread.php?t=294364 [[http://accessories.us.dell.com/sna/products/Motherboards/productdetail.aspx?c=us&l=en&s=bsd&cs=04&sku=TT359&mfgpid=192256&chassisid=8544#Overview order]]
Deletions:
Additions:
http://forum.notebookreview.com/showthread.php?t=294364
Additions:
HG: Add path to new repository:
# web server paths
[paths]
# virtual/path (http:/domain/name = /real/path)
test = /home/klenwell/root/tmp/hgtest
new_repo = /path/to/repo
[web]
style = gitweb
contact = admin@email.com
description = mercurial repositories
name = central repository
# web server paths
[paths]
# virtual/path (http:/domain/name = /real/path)
test = /home/klenwell/root/tmp/hgtest
new_repo = /path/to/repo
[web]
style = gitweb
contact = admin@email.com
description = mercurial repositories
name = central repository
Additions:
http://bitchphd.blogspot.com/
Additions:
[[http://www.nytimes.com/slideshow/2008/08/31/travel/0831-BIARRITZ_index.html photos that actually make me want to travel again]]
Additions:
http://freakonomics.blogs.nytimes.com/2008/08/20/have-economic-debates-changed-since-1977/index.html?hp
Additions:
http://garfield.nfshost.com/?s=lasagna&p=2
Additions:
[[http://www.nytimes.com/2008/08/17/books/review/Donadio-t.html?8bu&emc=bu blurbs]]
Additions:
python [[http://docs.python.org/lib/node46.html re]]:
try:
result = re.search(pattern, subject, re.S).groups()[0]
return result
except Exception, e:
return False
try:
result = re.search(pattern, subject, re.S).groups()[0]
return result
except Exception, e:
return False
Additions:
logrotate: http://linux.about.com/od/commands/l/blcmdl8_logrota.htm http://www.linux.com/articles/48390
Additions:
[[http://www.newyorker.com/talk/comment/2008/07/28/080728taco_talk_cassidy For some twenty years, politicians of both parties have been using free-market rhetoric as a cover for favors to big campaign contributors.]]
Additions:
linux autostop: ""<tt>ps aux | grep 'foo' | awk '{print $2}' | xargs kill -9</tt>""
Additions:
[[http://www.nytimes.com/2008/07/20/business/20debt.html?th&emc=th junk fees]]
Additions:
[[http://www.faqts.com/knowledge_base/view.phtml/aid/30990/fid/53 js __file__]]
Additions:
[[http://ask.slashdot.org/askslashdot/08/07/18/0046220.shtml os for old machines]]
Additions:
[[http://nltk.sourceforge.net/index.php/Getting_Started python nltk]] [[http://www.abisource.org/projects/link-grammar/ link grammar parser]]
Additions:
[[http://www.nytimes.com/2008/07/13/magazine/13officer-t.html?pagewanted=all 2nd Amendment as Foreign Policy Issue]]
Additions:
[[http://judson.blogs.nytimes.com/2008/07/15/lets-get-rid-of-darwinism/index.html Against Darwinism]]
Additions:
[[http://it.slashdot.org/comments.pl?sid=613269&cid=24182529 columbo 2.0]]
Additions:
[[http://tech.slashdot.org/article.pl?sid=08/07/08/0116238 Handling Flash Crowds from your Garage]]
Deletions:
Additions:
[[http://arstechnica.com/news.ars/post/20080708-hands-on-googles-lively-social-3d-world-is-20-percent-done.html Google Lively]] (for sonnet monkeys?)
Additions:
[[http://www.klenwell.com/is/SpecialCocktailNapkin/edit Handling Flash Crowds from your Garage]]
Additions:
AVG alternatives: [[http://www.clamwin.com/ clamwin]] [[http://www.avast.com/ avast]]
Additions:
[[http://www.makelinux.net/kernel_map linux kernel map]]
Additions:
ThumbDrive
Additions:
To Do: take a charge in the break room
Additions:
[[http://www.bbc.co.uk/languages/spanish/ BBC Spanish]] [[http://www.bravenewtraveler.com/2008/02/04/8-free-online-resources-for-learning-a-new-language/ free language lessons]]
I'll have to check this out when I get home: http://icanhaslolpron.com
I'll have to check this out when I get home: http://icanhaslolpron.com
Deletions:
Additions:
I'll have to check this out when I get home: icanhaslolpron.com
Additions:
[[http://sites.google.com/ Google wiki]]
Additions:
http://www.worldcat.org/
Additions:
bad housing news: [[http://calculatedrisk.blogspot.com/2008/03/real-case-shiller-house-price-index.html calculatedrisk]] [[http://sdhpi.blogspot.com/2008/05/is-this-bottom.html sdhpi]] [[http://en.wikipedia.org/wiki/Case-Shiller_index Case-Shiller]]
Additions:
[[http://tech.slashdot.org/comments.pl?sid=592263&cid=23904759 /. troll of the day and riposte]]
Additions:
""<tt>A[HREF*="myspace.com"]:after { content: " [BRAIN DAMAGE WARNING]"!important ; color: red }</tt>"" ([[http://tech.slashdot.org/comments.pl?sid=592263&cid=23904767 source]])
No Differences
Additions:
[[http://www.nytimes.com/2008/06/17/science/17mund.html steampunk web]] (almost literally)
Additions:
.hg [[http://www.selenic.com/mercurial/wiki/index.cgi/UsingExtensions extensions]]:
Deletions:
Additions:
.hg:
[extensions]
# Enable the 'glog' graphical log extension
hgext.graphlog =
# Enable CVS style variable substitution
hgext.keyword =
[extensions]
# Enable the 'glog' graphical log extension
hgext.graphlog =
# Enable CVS style variable substitution
hgext.keyword =
Additions:
print datetime.datetime.now() # current local datetime
print time.time() # unix timestamp
print time.time() # unix timestamp
Deletions:
print time.time()
Additions:
[[http://seehuhn.de/pages/pdate python dates and times]] (I'm always forgetting this crap):
import datetime, time
print time.time()
import datetime, time
print time.time()
Deletions:
import datetime
Additions:
python now:
%%(python)
import datetime
print datetime.datetime.now()
%%(python)
import datetime
print datetime.datetime.now()
Additions:
[[http://www.simulation-argument.com/classic.html simulation argument]]
[[http://forums.xkcd.com/viewtopic.php?f=11&t=11935&st=0&sk=t&sd=a&start=440#p693630 a mighty daemon]]
[[http://forums.xkcd.com/viewtopic.php?f=11&t=11935&st=0&sk=t&sd=a&start=440#p693630 a mighty daemon]]
Deletions:
...
# decapitate parent
os.chdir("/")
os.setsid()
os.umask(0)
# fork #2
try:
pid = os.fork()
if pid > 0:
print "pid: %d" % pid
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# A Mighty Daemon has been spawned. Hail Satan!
# Get pointer to "/dev/null"
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
...
Additions:
a pythonic tribute to [[http://forums.xkcd.com/viewtopic.php?f=11&t=23249 xkcd]]: ""<code>xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([str(int(k in t)) for t in [c,d]]),2)])[k] or x</code>""
Deletions:
# php: print x = ( isset($C[$k]) ) ? $C[$k] : ( isset($D[$k]) ? $D[$k] : 'default');
xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([str(int(k in t)) for t in [c,d]]),2)])[k] or x
C = {'a':1, 'b':2}
D = {'needle':'got it!', 'a':23}
C1 = D
D1 = C
X = 'default'
K = 'needle'
print xkcd(X,K,C,D)
print xkcd(X,'missing',C,D)
print xkcd(X,K,C1,D1)
Additions:
xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([str(int(k in t)) for t in [c,d]]),2)])[k] or x
Deletions:
Additions:
xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([(str(int(k in t))) for t in [c,d]]),2)])[k] or x
Deletions:
Additions:
a pythonic tribute to xkcd:
# php: print x = ( isset($C[$k]) ) ? $C[$k] : ( isset($D[$k]) ? $D[$k] : 'default');
xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([str((int(k in t))) for t in [c,d]]),2)])[k] or x
C = {'a':1, 'b':2}
D = {'needle':'got it!', 'a':23}
C1 = D
D1 = C
X = 'default'
K = 'needle'
print xkcd(X,K,C,D)
print xkcd(X,'missing',C,D)
print xkcd(X,K,C1,D1)
# php: print x = ( isset($C[$k]) ) ? $C[$k] : ( isset($D[$k]) ? $D[$k] : 'default');
xkcd = lambda x,k,c,d: (({k:False},d,c)[int(''.join([str((int(k in t))) for t in [c,d]]),2)])[k] or x
C = {'a':1, 'b':2}
D = {'needle':'got it!', 'a':23}
C1 = D
D1 = C
X = 'default'
K = 'needle'
print xkcd(X,K,C,D)
print xkcd(X,'missing',C,D)
print xkcd(X,K,C1,D1)
Additions:
more django: [[http://www.djangoproject.com/documentation/modelforms/ modelforms]] [[http://www.djangoproject.com/documentation/newforms/#modelmultiplechoicefield forms]]
Additions:
rent or buy: http://www.nytimes.com/2008/05/28/business/28leonhardt.html [[http://www.nytimes.com/2007/04/10/business/2007_BUYRENT_GRAPHIC.html? calculator]]
Additions:
[[http://en.wikipedia.org/wiki/Pitaya dragonfruit]]
Additions:
[[http://code.google.com/apis/ajaxlibs/ google ajaxlibs]] ([[http://developers.slashdot.org/developers/08/05/28/144218.shtml /.]])
Additions:
[[http://www.nytimes.com/2008/05/28/dining/28flavor.html flavor-tripping]]
Additions:
[[http://home.netcom.com/~tjensen/ptr/ch1x.htm pointers]] (to the point)
Additions:
[[http://www.fonts500.com/?page=1 500 Fonts]] [[http://thepiratebay.org/tor/3660252/500_Fonts_from_fonts500.com all at once]]
Additions:
[[http://tech.slashdot.org/comments.pl?sid=565231&cid=23559299 leave it to Jesus 666]]
Additions:
[[http://www.djangoproject.com/documentation/forms/ django forms]] [[http://www.djangoproject.com/documentation/newforms/ django newforms]] [[http://code.google.com/appengine/articles/djangoforms.html django form validation]] [[http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms/widgets.py django form tests (examples)]] [[http://www.djangoproject.com/documentation/form_wizard/ django forms wizard]]
Additions:
scripps 05.23: [[http://surfshot.s3.amazonaws.com/media/9/7/975364-large.jpg 1]] [[http://surfshot.s3.amazonaws.com/media/9/7/975363-large.jpg 2]] [[http://surfshot.s3.amazonaws.com/media/9/7/975370-large.jpg 3]]
Additions:
http://code.google.com/p/google-app-engine-samples/wiki/GoogleAppEngineSamples [[http://groups.google.com/group/google-appengine/browse_frm/thread/d3673d0ec7ead0e2 djangoforms]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/13d1f026d46bd35f model keys]]
Deletions:
Additions:
http://code.google.com/p/google-app-engine-samples/wiki/GoogleAppEngineSamples [[http://groups.google.com/group/google-appengine/browse_frm/thread/d3673d0ec7ead0e2 djangoforms]]
Deletions:
Additions:
http://code.google.com/p/google-app-engine-samples/wiki/GoogleAppEngineSamples
Additions:
[[http://archive.ics.uci.edu/ml/ lots of data]] (courtesy of my alma mater)
Additions:
[[http://highscalability.com/how-i-learned-stop-worrying-and-love-using-lot-disk-space-scale querying gapp]]
Additions:
http://img143.imageshack.us/img143/3660/fbooknb5.png
Additions:
sessions: [[http://groups.google.com/group/google-appengine/browse_frm/thread/1c459b2ca7a6e643/2311877beffe0403?lnk=gst&q=session#2311877beffe0403 datastore]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/f162c186c3e68f1a/1ea824e3bebd5801?lnk=gst&q=session#1ea824e3bebd5801 class]] [[http://code.google.com/appengine/docs/python/appcaching.html appcaching]]
Deletions:
Additions:
sessions: [[http://groups.google.com/group/google-appengine/browse_frm/thread/1c459b2ca7a6e643/2311877beffe0403?lnk=gst&q=session#2311877beffe0403 datastore]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/f162c186c3e68f1a/1ea824e3bebd5801?lnk=gst&q=session#1ea824e3bebd5801 class]]
Additions:
[[http://entertainment.slashdot.org/comments.pl?sid=556912&cid=23461200 mythbuntu]]
Additions:
[[http://www.rinkworks.com/words/collective.shtml words for groups of animals]]
Additions:
WordsIReallyLike
Additions:
[[http://kwap.appspot.com/ klenwell @ google app engine]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/c9e8a906a88a8102 links to good gapp tips]]
Deletions:
Additions:
[[http://kwap.appspot.com/ klenwell @ google app engine]]
Additions:
[[http://us2.php.net/manual/en/function.debug-backtrace.php#72534 php debug]]
Additions:
[[http://www.nytimes.com/2008/05/13/world/middleeast/13girls.html?_r=1&hp=&pagewanted=all Project Alia]]
Additions:
[[http://entertainment.slashdot.org/entertainment/08/05/13/0316251.shtml free as in beer beer]]
Additions:
[[http://www.msnbc.msn.com/id/23359042/from/ET/ no plastic surgery!]]
No Differences
Additions:
[[http://www.housingmaps.com/ housingmaps.com]]
Additions:
[[http://code.google.com/appengine/docs/gettingstarted/ google app engine]] [[http://blog.wachob.com/2008/04/google-appengin.html scaling with gae]] [[http://perspectives.mvdirona.com/2008/04/21/GoogleApplicationEngine.aspx a review]] [[http://code.google.com/appengine/docs/python/purepython.html python in gae]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/dc927ba00944027f gApp on ubuntu]] [[http://code.google.com/p/rietveld/source/browse gApp example code]]
Deletions:
Additions:
[[http://code.google.com/appengine/docs/gettingstarted/ google app engine]] [[http://blog.wachob.com/2008/04/google-appengin.html scaling with gae]] [[http://perspectives.mvdirona.com/2008/04/21/GoogleApplicationEngine.aspx a review]] [[http://code.google.com/appengine/docs/python/purepython.html python in gae]] [[http://groups.google.com/group/google-appengine/browse_frm/thread/dc927ba00944027f gApp on ubuntu]]
Deletions:
Additions:
on fonts: [[http://fontstruct.fontshop.com/ fontstruct]] [[http://www.sweeperscalendar.com/variorum/1129/ the prophecy]]
Additions:
stupid lambda tricks: ""<code>in_dict_list = lambda dic, k, v: v in [d[k] for d in dic]</code>""
Additions:
[[http://www.nytimes.com/2008/05/08/fashion/08PUNK.html?_r=1&oref=slogin steampunk]] ""=="" [[http://en.wikipedia.org/wiki/Tomorrowland#Tomorrowland_1998 tomorrowland 1998]]
Deletions:
Additions:
[[http://www.nytimes.com/2008/05/08/fashion/08PUNK.html?_r=1&oref=slogin steampunk]] == [[http://en.wikipedia.org/wiki/Tomorrowland#Tomorrowland_1998 tomorrowland 1998]]
Additions:
[[http://code.google.com/appengine/docs/gettingstarted/ google app engine]] [[http://blog.wachob.com/2008/04/google-appengin.html scaling with gae]] [[http://perspectives.mvdirona.com/2008/04/21/GoogleApplicationEngine.aspx a review]] [[http://code.google.com/appengine/docs/python/purepython.html python in gae]]
Deletions:
Additions:
[[http://code.google.com/appengine/docs/gettingstarted/ google app engine]] [[http://blog.wachob.com/2008/04/google-appengin.html scaling with gae]] [[http://perspectives.mvdirona.com/2008/04/21/GoogleApplicationEngine.aspx a review]]
Additions:
[[http://aspn.activestate.com/ASPN/docs/Komodo/4.3/komodo-js-api.html komodo js api]]
Additions:
[[http://en.wikipedia.org/wiki/AI_Winter AI Winter]] [[http://www.nytimes.com/2008/05/03/technology/03koller.html?th&emc=th is over]]
Additions:
http://www.gnu.org/software/diction/ http://www.link.cs.cmu.edu/link/ [[http://alanhorkan.livejournal.com/16062.html overview]] [[http://papyr.com/hypertextbooks/grammar/gramchek.htm tests]] [[http://en.wikipedia.org/wiki/Grammar_checker wikipedia]]
Deletions:
Additions:
http://www.gnu.org/software/diction/ http://www.link.cs.cmu.edu/link/ http://alanhorkan.livejournal.com/16062.html [[http://papyr.com/hypertextbooks/grammar/gramchek.htm tests]] [[http://en.wikipedia.org/wiki/Grammar_checker wikipedia]]
Additions:
[[http://pidgin.im/ pidgin]] (nice home page)
Additions:
[[http://www.herecomeseverybody.org/2008/04/looking-for-the-mouse.html the sitcom]] [[http://tech.slashdot.org/tech/08/04/27/1422258.shtml (./)]] | [[http://tech.slashdot.org/article.pl?sid=08/04/30/1515229 Berners-Lee on Web]]
Additions:
[[http://www.shoutcast.com/directory/index.phtml shoutcast streams]] see also [[http://lifehacker.com/384545/superior-alternatives-to-crappy-windows-software vlc]]
Deletions:
Additions:
[[http://www.shoutcast.com/directory/index.phtml shoutcast streams]]
Additions:
[[http://yro.slashdot.org/comments.pl?sid=537280&cid=23231314 /. life lessons: if arrested...]]
Additions:
[[http://politics.slashdot.org/comments.pl?sid=228403&cid=18513137 John McCain ad hominem]]
Additions:
[[http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references HTML entities]]
Additions:
[[http://en.wikipedia.org/wiki/Simon-Ehrlich_wager Simon-Ehrlich Wager]] [[http://krugman.blogs.nytimes.com/2008/04/22/limits-to-growth-and-related-stuff/ Krugman]]
Additions:
[[http://www.selenic.com/pipermail/mercurial/2007-April/012921.html removing a file from a python repo without deleting]] **use hg rm -A** (e.g. hg rm -A dir/*)
Additions:
[[http://www.nytimes.com/2008/04/24/books/24garn.html?_r=1&th&emc=th&oref=slogin kleinzahler]]
Deletions:
Additions:
[http://www.nytimes.com/2008/04/24/books/24garn.html?_r=1&th&emc=th&oref=slogin kleinzahler]]
Additions:
[[http://www.ocfamily.com/t-FeatureStory_BabyNames_0408.aspx oc baby names]]
Additions:
[[http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml komodo edit]] [[http://community.activestate.com/faq/komodo-file-locations saving preference file]]
Additions:
[[http://code.google.com/apis/igoogle/ igoogle API]]
Additions:
[[http://tech.slashdot.org/article.pl?sid=08/04/16/121225&from=rss Yahoo Analytics (IndexTools)]]
Additions:
[[http://www.pseudocoder.com/archives/2007/02/27/cakephp-cache-performance/ cakephp cache benchmark]]
Additions:
%%(bash)
# cron.d file
# to activate, link to /etc/cron.d: ln -s <path>/fname.cron /etc/cron.d/link_name
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# M H DM MO DW USER SCRIPT
# cron.d file
# to activate, link to /etc/cron.d: ln -s <path>/fname.cron /etc/cron.d/link_name
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# M H DM MO DW USER SCRIPT
Additions:
[[http://www.nytimes.com/2008/04/21/opinion/21krugman.html the commodities bubble]]
Additions:
[[http://tech.slashdot.org/comments.pl?sid=526820&cid=23115228 oss binary blobs]]
Additions:
# fork #2
Deletions:
No Differences
Additions:
emacs: [[http://www.google.com/search?q=customize+emacs+-scribd.com&hl=en&lr=&as_qdr=all&start=10&sa=N customize]] [[http://www.google.com/search?hl=en&lr=&as_qdr=all&q=+site:www.gnu.org+customize+emacs+-scribd.com manual]] [[http://www.gnu.org/software/emacs/tour/ tour]]
Additions:
%%(python)
...
# decapitate parent
os.chdir("/")
os.setsid()
os.umask(0)
# put another fork in it
try:
pid = os.fork()
if pid > 0:
print "pid: %d" % pid
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# A Mighty Daemon has been spawned. Hail Satan!
# Get pointer to "/dev/null"
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
...
%%
...
# decapitate parent
os.chdir("/")
os.setsid()
os.umask(0)
# put another fork in it
try:
pid = os.fork()
if pid > 0:
print "pid: %d" % pid
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# A Mighty Daemon has been spawned. Hail Satan!
# Get pointer to "/dev/null"
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
...
%%
Additions:
[[http://w-shadow.com/blog/2008/04/12/simple-text-summarizer-in-php/ simple text summarizer]] [[http://www.symfony-project.org/askeet/1_0/21 simple search engine]]
Deletions:
Additions:
[[http://w-shadow.com/blog/2008/04/12/simple-text-summarizer-in-php/ simple text summarizer]]
Additions:
ny times: [[http://www.nytimes.com/2008/04/13/business/13cash.html?th=&emc=th&pagewanted=all wall st. sleaze]] [[http://www.nytimes.com/2008/04/14/business/media/14link.html?th=&emc=th&pagewanted=all some guy who wrote a program to write 200,000 books]]
Deletions:
Additions:
[[http://www.nytimes.com/2008/04/13/business/13cash.html?th=&emc=th&pagewanted=all wall st. sleaze]]
Additions:
cakephp: [[http://book.cakephp.org/view/32/installation#advanced-installation-35 shared core setup]] [[http://bakery.cakephp.org/articles/view/maintaining-an-application-independant-code-library app-indy lib]] [[http://manual.cakephp.org/chapter/plugins plugins]]
Additions:
[[http://bakery.cakephp.org/ <a href="http://mushpup.org/">pw</a>: m{d/u}l11]]
Additions:
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP [[http://dev.mysql.com/doc/refman/4.1/en/timestamp.html mysql.com]]
Additions:
python encoding: [[http://mail.python.org/pipermail/python-list/2007-May/442985.html nutshell]] [[http://www.reportlab.com/i18n/python_unicode_tutorial.html unicode tutorial]]
Additions:
python on web: [[http://www.modpython.org/ modpython]] [[http://www.zope.org/ zope]] [[http://code.google.com/appengine/docs/gettingstarted/ google webapp]]
Additions:
[[http://code.google.com/appengine/docs/whatisgoogleappengine.html google app engine]]
Additions:
vim: [[http://www.linux.com/articles/54159 marks and jumps]]
Additions:
PHP PCRE Issue: [[http://us3.php.net/manual/en/ref.pcre.php#77790 cause]] [[http://www.phpinsider.com/smarty-forum/viewtopic.php?p=48604 cause]] [[http://bugs.php.net/bug.php?id=40846 bugs.php.net]] [[http://tracker.moodle.org/browse/MDL-11237?focusedCommentId=34538#action_34538 a solution]]
Deletions:
Additions:
PHP PCRE Issue: [[http://us3.php.net/manual/en/ref.pcre.php#77790 cause]] [[http://www.phpinsider.com/smarty-forum/viewtopic.php?p=48604 cause]] [[http://bugs.php.net/bug.php?id=40846 solution]]
Deletions:
Additions:
PHP PCRE Issue: [[http://us3.php.net/manual/en/ref.pcre.php#77790 cause]] [[http://www.phpinsider.com/smarty-forum/viewtopic.php?p=48604 cause]] [[http://bugs.php.net/bug.php?id=40624 bugs.php.net]]
Deletions:
Additions:
PHP PCRE Issue: [[http://www.phpinsider.com/smarty-forum/viewtopic.php?p=48604 cause]] [[http://bugs.php.net/bug.php?id=40624 bugs.php.net]]
Deletions:
Additions:
PCRE Issue: [[http://www.phpinsider.com/smarty-forum/viewtopic.php?p=48604 cause]]
Additions:
[[http://en.wikipedia.org/wiki/Moby_Project Moby Project]] [[http://www.nzdl.org/ELKB/download.html Roget's]]
Additions:
[[http://cb.vu/unixtoolbox.xhtml unix cheat sheet]]
Deletions:
<script type="text/javascript">
var Rows = [
'line 1',
'line 2',
'line 3',
'line 4'
];
function cx_prow(id)
{
var P = new Element('p', { 'id': id });
return P;
}
function cx_handle(id)
{
var El = new Element('span', { 'class': 'handle' }).update('•');
return El;
}
function cx_text(ln)
{
title = 'extended output can be put here: ' + ln;
var El = new Element('span', { 'class': 'line_text', 'title': title }).update(ln);
return El;
}
function cx_hide(id)
{
cur = 'this.style.cursor="pointer";';
clik = 'javascript:alert("hide clicked for ' + id + '"); return false;';
var El = new Element('span', {'id': id, 'onmouseover': cur, 'onclick': clik }).update('hide');
return El;
}
Rows.each( function(ln, i){
id = 'smedln_' + i;
Prow = cx_prow(id);
Prow.appendChild(cx_handle(id));
Prow.appendChild(cx_text(ln));
Prow.appendChild(cx_hide(id));
$('smed').appendChild(Prow);
}
);
$('smed').childElements().each( function(Obj){
id = Obj.id;
line = Obj.select('span.line_text')[0].innerHTML;
console.log(id, line);
}
);
</script>
%%
Additions:
[[http://www.dell.com/content/products/productdetails.aspx/vostronb_1400?c=us&cs=04&l=en&s=bsd&~tab=bundlestab vostro 1400]]
Additions:
[[http://www.interest.com/content/calculators/rentvsbuy.asp rent v. buy]] [[http://www.bloomberg.com/invest/calculators/mortgage.html bloomberg mortgage calculator]]
Deletions:
Additions:
[[http://www.interest.com/content/calculators/rentvsbuy.asp rent v. buy]]
Additions:
var Rows = [
'line 1',
'line 2',
'line 3',
'line 4'
];
title = 'extended output can be put here: ' + ln;
var El = new Element('span', { 'class': 'line_text', 'title': title }).update(ln);
cur = 'this.style.cursor="pointer";';
clik = 'javascript:alert("hide clicked for ' + id + '"); return false;';
var El = new Element('span', {'id': id, 'onmouseover': cur, 'onclick': clik }).update('hide');
'line 1',
'line 2',
'line 3',
'line 4'
];
title = 'extended output can be put here: ' + ln;
var El = new Element('span', { 'class': 'line_text', 'title': title }).update(ln);
cur = 'this.style.cursor="pointer";';
clik = 'javascript:alert("hide clicked for ' + id + '"); return false;';
var El = new Element('span', {'id': id, 'onmouseover': cur, 'onclick': clik }).update('hide');
Deletions:
var El = new Element('span', { 'class': 'line_text' }).update(ln);
var El = new Element('span', {'id': id, 'onclick': 'javascript:alert("hide clicked for ' + id + '"); return false;' }).update('hide');
Additions:
%%(javascript)
<script type="text/javascript">
var Rows = ['line 1', 'line 2', 'line 3', 'line 4'];
function cx_prow(id)
{
var P = new Element('p', { 'id': id });
return P;
}
function cx_handle(id)
{
var El = new Element('span', { 'class': 'handle' }).update('•');
return El;
}
function cx_text(ln)
{
var El = new Element('span', { 'class': 'line_text' }).update(ln);
return El;
}
function cx_hide(id)
{
var El = new Element('span', {'id': id, 'onclick': 'javascript:alert("hide clicked for ' + id + '"); return false;' }).update('hide');
return El;
}
Rows.each( function(ln, i){
id = 'smedln_' + i;
Prow = cx_prow(id);
Prow.appendChild(cx_handle(id));
Prow.appendChild(cx_text(ln));
Prow.appendChild(cx_hide(id));
$('smed').appendChild(Prow);
}
);
$('smed').childElements().each( function(Obj){
id = Obj.id;
line = Obj.select('span.line_text')[0].innerHTML;
console.log(id, line);
}
);
</script>
<script type="text/javascript">
var Rows = ['line 1', 'line 2', 'line 3', 'line 4'];
function cx_prow(id)
{
var P = new Element('p', { 'id': id });
return P;
}
function cx_handle(id)
{
var El = new Element('span', { 'class': 'handle' }).update('•');
return El;
}
function cx_text(ln)
{
var El = new Element('span', { 'class': 'line_text' }).update(ln);
return El;
}
function cx_hide(id)
{
var El = new Element('span', {'id': id, 'onclick': 'javascript:alert("hide clicked for ' + id + '"); return false;' }).update('hide');
return El;
}
Rows.each( function(ln, i){
id = 'smedln_' + i;
Prow = cx_prow(id);
Prow.appendChild(cx_handle(id));
Prow.appendChild(cx_text(ln));
Prow.appendChild(cx_hide(id));
$('smed').appendChild(Prow);
}
);
$('smed').childElements().each( function(Obj){
id = Obj.id;
line = Obj.select('span.line_text')[0].innerHTML;
console.log(id, line);
}
);
</script>
Deletions:
# imports
import sys, os
from datetime import *
class SimpleTest:
timer_last = 0
def __init__(self):
print 'initializing Simpletest'
def main(self):
print 'it is now: %s' % datetime.now()
def read_file(self, path):
try:
Fso = open(path, 'r')
content = Fso.read()
Fso.close()
content.strip()
return content
except Exception, e:
raise e
def eparse(self, content):
header, body = content.split('\n\n', 1)
print "\n\nheader:\n %s\n\nbody:\n %s" % (header, body)
return header, body
def timer(self):
now = datetime.now()
if ( self.timer_last == 0 ):
self.timer_last = now
return 0
else:
lapse = now - self.timer_last
self.timer_last = now
return lapse
if __name__ == '__main__':
Arch = SimpleTest()
Arch.timer()
fpath = 'C:\\PATHTO\\FILE.txt'
ec = Arch.read_file(fpath)
h, b = Arch.eparse(ec)
print "script time: %s" % Arch.timer()
Deletions:
# download: http://sourceforge.net/project/showfiles.php?group_id=22307
def test():
table = ''
dbname = ''
user = 'root'
pass = 'root'
host = 'localhost'
sql = 'SELECT * FROM %s' % table
try:
Dbo = MySQLdb.connect(host, user, pass, dbname).cursor()
Dbo.execute( sql )
ROWS = Dbo.fetchall()
except Exception, e:
print 'db issue: %s' % str(e)
for each_row as ROWS:
print each_row
test()
# Test Script
# to run: $ python C:\pathto\mysql.py
import datetime
import MySQLdb
class MysqlTest:
Dbo = None
Db1 = ['db_host', 'user', 'pw', 'db_name']
test_table = 'pages'
self.connect(self.Db1)
def connect(self, Host):
self.Dbo = MySQLdb.connect(Host[0], Host[1], Host[2], Host[3])
raise e
def testSelect(self):
sql = """SELECT * FROM %s LIMIT 10""" % self.test_table
Dbc = self.Dbo.cursor()
Dbc.execute(sql)
Rows = Dbc.fetchall()
Dbc.close()
return Rows
try:
Dbo = MysqlTest()
Rows = Dbo.testSelect()
for Row in Rows:
print Row
except Exception, e:
print 'there was an error: %s' % str(e)
Additions:
from datetime import *
class SimpleTest:
timer_last = 0
print 'initializing Simpletest'
def main(self):
print 'it is now: %s' % datetime.now()
def read_file(self, path):
Fso = open(path, 'r')
content = Fso.read()
Fso.close()
content.strip()
return content
def eparse(self, content):
header, body = content.split('\n\n', 1)
print "\n\nheader:\n %s\n\nbody:\n %s" % (header, body)
return header, body
def timer(self):
now = datetime.now()
if ( self.timer_last == 0 ):
self.timer_last = now
return 0
else:
lapse = now - self.timer_last
self.timer_last = now
return lapse
Arch = SimpleTest()
Arch.timer()
fpath = 'C:\\PATHTO\\FILE.txt'
ec = Arch.read_file(fpath)
h, b = Arch.eparse(ec)
print "script time: %s" % Arch.timer()
class SimpleTest:
timer_last = 0
print 'initializing Simpletest'
def main(self):
print 'it is now: %s' % datetime.now()
def read_file(self, path):
Fso = open(path, 'r')
content = Fso.read()
Fso.close()
content.strip()
return content
def eparse(self, content):
header, body = content.split('\n\n', 1)
print "\n\nheader:\n %s\n\nbody:\n %s" % (header, body)
return header, body
def timer(self):
now = datetime.now()
if ( self.timer_last == 0 ):
self.timer_last = now
return 0
else:
lapse = now - self.timer_last
self.timer_last = now
return lapse
Arch = SimpleTest()
Arch.timer()
fpath = 'C:\\PATHTO\\FILE.txt'
ec = Arch.read_file(fpath)
h, b = Arch.eparse(ec)
print "script time: %s" % Arch.timer()
Additions:
%%(python)
%%(python)
# Test Script
# to run: $ python C:\pathto\mysql.py
# imports
import sys, os
import datetime
import MySQLdb
class MysqlTest:
Dbo = None
Db1 = ['db_host', 'user', 'pw', 'db_name']
test_table = 'pages'
def __init__(self):
self.connect(self.Db1)
def connect(self, Host):
try:
self.Dbo = MySQLdb.connect(Host[0], Host[1], Host[2], Host[3])
except Exception, e:
raise e
def testSelect(self):
sql = """SELECT * FROM %s LIMIT 10""" % self.test_table
try:
Dbc = self.Dbo.cursor()
Dbc.execute(sql)
Rows = Dbc.fetchall()
Dbc.close()
return Rows
except Exception, e:
raise e
Dbo = MysqlTest()
Rows = Dbo.testSelect()
for Row in Rows:
print Row
print 'there was an error: %s' % str(e)
%%(python)
# Test Script
# to run: $ python C:\pathto\mysql.py
# imports
import sys, os
import datetime
import MySQLdb
class MysqlTest:
Dbo = None
Db1 = ['db_host', 'user', 'pw', 'db_name']
test_table = 'pages'
def __init__(self):
self.connect(self.Db1)
def connect(self, Host):
try:
self.Dbo = MySQLdb.connect(Host[0], Host[1], Host[2], Host[3])
except Exception, e:
raise e
def testSelect(self):
sql = """SELECT * FROM %s LIMIT 10""" % self.test_table
try:
Dbc = self.Dbo.cursor()
Dbc.execute(sql)
Rows = Dbc.fetchall()
Dbc.close()
return Rows
except Exception, e:
raise e
Dbo = MysqlTest()
Rows = Dbo.testSelect()
for Row in Rows:
print Row
print 'there was an error: %s' % str(e)
Additions:
[[SpecialBCAA BCAA]]
Additions:
%%
import sha, MySQLdb
# download: http://sourceforge.net/project/showfiles.php?group_id=22307
def test():
table = ''
dbname = ''
user = 'root'
pass = 'root'
host = 'localhost'
sql = 'SELECT * FROM %s' % table
try:
Dbo = MySQLdb.connect(host, user, pass, dbname).cursor()
Dbo.execute( sql )
ROWS = Dbo.fetchall()
except Exception, e:
print 'db issue: %s' % str(e)
for each_row as ROWS:
print each_row
if __name__ == '__main__':
test()
%%
import sha, MySQLdb
# download: http://sourceforge.net/project/showfiles.php?group_id=22307
def test():
table = ''
dbname = ''
user = 'root'
pass = 'root'
host = 'localhost'
sql = 'SELECT * FROM %s' % table
try:
Dbo = MySQLdb.connect(host, user, pass, dbname).cursor()
Dbo.execute( sql )
ROWS = Dbo.fetchall()
except Exception, e:
print 'db issue: %s' % str(e)
for each_row as ROWS:
print each_row
if __name__ == '__main__':
test()
%%
Additions:
[[http://garfieldminusgarfield.tumblr.com/ Garfield - Garfield = Existential Humor]]
Deletions:
Additions:
[[http://garfieldminusgarfield.tumblr.com/ Garfield - Garfield = Humor]]
Additions:
Cool Dingbats: [[http://www.bittbox.com/fonts/dingbats-roundup-16-incredibly-detailed-useful-and-free-dingbat-fonts/ bittbox.com]]
Deletions:
%%(bash)
# basic (source: http://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/)
$ find /path/to/files* -mtime +5 -ls
# delete
$ find /path/to/files* -mtime +5 -exec rm {} \;
# files only (http://www.unix.com/shell-programming-scripting/32816-need-remove-files-older-than-30-days-except-directories.html)
$ find /path/to/files -type f -mtime +90 -exec rm {} \;
# dirs only (http://lowfatlinux.com/linux-find.html)
$ find /path/to/files -type d -ok rmdir {} \;
# find files by size (http://lowfatlinux.com/linux-find.html)
$ find /path/to/files -size +100k -ls
# find files older than 8 hours (http://www.unix.com/shell-programming-scripting/32816-need-remove-files-older-than-30-days-except-directories.html)
$ touch -t `date --date='12 hours ago' +%Y%m%d%H%M` time_marker
$ find . -type f -newer time_marker -ls
# find files by size and age
$ find /path/to/files -type f -mtime +1 -size +5k -ls
# remove files older than 4 hours and larger than 5 kb
$ touch -t `date --date='4 hours ago' +%Y%m%d%H%M` time_marker
$ find /path/to/files -type f -newer time_marker -ls
%%
Scratchpad
%%
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>javascript canvas</title>
<!-- JS: timer -->
<script type="text/javascript">
var tx0 = new Date();
function jstx() { return ( ( new Date() ) - tx0 ) / 1000; }
function l() { if (eval('typeof(console)=="undefined"')) return; var arg=arguments, msg=''; for(i=0; i<arg.length; i++) { msg+=arg[i]+' '; } console.log('[log]', msg); }
function p(message) { document.write(message); }
</script>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="formState.js"></script>
<!-- JS: dev -->
<script type="text/javascript">
</script>
<!-- External Script -->
<!-- JS: dev -->
<script type="text/javascript">
var EditorApp = Class.create({
version : '0.1',
pre : 'ned_',
c : ' : ',
initialize: function(textarea_id)
{
this.id = this.pre + 'parent_' + textarea_id; // obj id
this.fid = this.id + '_undoable'; // form id
this.tid = textarea_id;
this.class = this.pre + 'block';
this.T = $(this.tid);
this.metabar = {};
this._update_dom();
this._add_observers();
},
_update_dom: function()
{
// get textarea parent and grandparent
this.Tp = this.T.getOffsetParent(this.T);
// create a parent dom element and form append textarea
this.E = new Element('div', { 'id': this.id, 'class': this.class });
this.F = new Element('form', { 'id': this.fid });
this.F.appendChild(this.T);
this.E.appendChild(this.F);
this.Tp.appendChild(this.E);
// append toolbar
this.addToolbar();
this.E.appendChild(this.toolbar);
// get dom obj
l(this.id, ' EditorApp created');
},
_add_observers: function()
{
// buffer
this.T.Buffer = new TextBuffer(20);
// add event listener
new Form.Element.Observer(
this.T.id,
2, // seconds
function(el, value){
el.Buffer.update(value);
}
)
this.T.observe('change', function(event)
{
l('observing changes on', this.T.id, 'for buffer');
El = Event.element(event);
});
},
addToolbar: function()
{
l('building toolbar');
BX = [];
// array: [0]id, [1]label, [2]target id, [3]callback
BX[0] = [this.pre + 'bold', '<b>', this.T.id, this.emboldenText];
BX[1] = [this.pre + 'ital', '<i>', this.T.id, this.testEvent];
BX[2] = [this.pre + 'undo', 'undo', this.T.id, this.undoEvent];
this.toolbar = new Element('div', { 'id': this.pre + 'toolbar' });
for ( var n=0; n<BX.length; n++ )
{
var new_bx = this.cxButton(BX[n][0], BX[n][1], BX[n][2], BX[n][3]);
this.toolbar.appendChild(new_bx);
}
},
cxButton: function(id, label, target, onclick_callback)
{
l('cxButton:',id,'|',label,'|',target);
Bx = new ToolButton(id, label, target, onclick_callback);
return Bx.E;
},
emboldenText: function(event)
{
el = Event.element(event); // element
t = $(el.target); // target
v = t.value; // target value
ins = ''; // insert
nv = v; // new value
ST = EditorApp.getSelectedText(t);
if ( ST[0] != false ) ins = '<strong>' + ST[0] + '</strong>';
nv = v.substring(0, ST[1]) + ins + v.substr(ST[2]);
t.value = nv;
l('event',event,': calling emboldenText on',t,'| insert: "',ins,'"');
EditorApp.selectRange($(t), ST[1] + ins.length, ST[1] + ins.length);
},
testEvent: function(event)
{
s = ' | ';
el = Event.element(event);
l('testEvent:','event=',event,s,'calling element=',el,s,'target=',el.target);
}
});
/*
returns an array holding:
[0]: selected text
[1]: start pos
[2]: end pos
*/
EditorApp.getSelectedText = function(el)
{
l("getting selected text from " + el.id + " : " + el.toString());
selected = [false, 0, 0];
// get start/end
var s1 = 0; var s2 = 0;
if ( typeof document.selection != 'undefined' )
{
var r = document.selection.createRange();
s1 = r.start;
s2 = r.end;
}
else if ( typeof el.selectionStart != 'undefined' )
{
s1 = el.selectionStart;
s2 = el.selectionEnd;
}
else
{
l('getSelectedText handle not found');
return selected;
}
while ( s2 > s1 && el.value.charAt(s2-1) == ' ' )
{
s2--;
}
l('selecting',s1,',',s2,'in',el.id);
if ( s2 - s1 < 1 ) return selected;
sel_text = el.value.substring(s1, s2);
l('selected text:', sel_text);
return [sel_text, s1, s2];
}
EditorApp.selectRange = function(el, p1, p2)
{
if(el.setSelectionRange)
{
el.focus();
el.setSelectionRange(p1,p2);
}
else if(el.createTextRange)
{
range=el.createTextRange();
range.collapse(true);
range.moveEnd('character',p2);
range.moveStart('character',p1);
range.select();
}
}
/*
Each button is an object and should have an action and a target. The target
is another object (or the button itself) upon which the action acts. The
action is a callback function which is called when button is clicked.
*/
var ToolButton = Class.create({
initialize: function(id, label, target_id, click_callback)
{
l('constructing ToolButton: ' + id);
// create button element (as a)
AttList = { 'id': id, 'onmouseover': 'javascript:this.style.cursor="pointer";' };
this.E = new Element('a', AttList).update(label);
// add attributes
this.E.id = id;
this.E.label = label;
this.E.target = target_id;
this.E.action = click_callback;
// add event listener
this.E.observe('click', function(event)
{
calling_el = Event.element(event);
click_callback(event);
$(calling_el.target).focus();
});
}
});
var TextBuffer = Class.create({
initialize: function(target_id, maxlen)
{
this.id = target_id;
this.maxlen = ( maxlen != undefined ) ? maxlen : 20;
this.E = $(target_id);
this.BUFFER = [];
this.ptr = -1;
},
// update buffer (alias of push)
update: function(textarea_value)
{
this.push(textarea_value);
},
// push buffer
push: function(str)
{
var buf_len = this.BUFFER.push(str);
var overflow = buf_len - this.maxlen;
while ( overflow > 0 )
{
overflow--;
this.BUFFER.shift();
buf_len--;
}
this.ptr = this.BUFFER.length - 1;
l("pushing '", str, "' on buffer and setting ptr to", this.ptr);
},
// undo buffer
undo: function()
{
this.ptr--;
if ( this.ptr < 0 ) this.ptr = 0;
var content = this.BUFFER[this.ptr];
l('undo: returning content "', content, "' at ptr", this.ptr);
return content;
},
// redo buffer
redo: function()
{
this.ptr++;
if ( this.ptr >= this.BUFFER.length ) this.ptr = this.BUFFER.length - 1;
var content = this.BUFFER[this.ptr];
l('redo: returning content "', content, "' at ptr", this.ptr);
return content;
}
});
/*
*/
var DomHandler = Class.create({
initialize: function()
{
l('constructing DomHandler ' + id);
}
});
</script>
<!-- External Script -->
<style type="text/css">
body { margin:0; padding:0; font-family:sans-serif; color:#ccf; }
h1 { margin:0 0 10px; padding:1em; border-bottom:1px solid #ccf; background: #f3f3ff; }
#footer {
clear:both; margin-top:12px; padding:4px; font: 11px verdana,sans-serif; border:1px solid #ccf; border-width:1px 0; background: #f3f3ff; text-align:center;
}
/* Editor */
.ned_block { width:300px; margin:0 auto; border:1px solid #ccc; }
.ned_block form, .ned_block textarea { margin:0; }
.ned_block textarea { width:300px; overflow-x:auto; margin:0; }
#ned_toolbar { text-align:center; margin:0; padding:3px; background:#f6f6f6; }
#ned_toolbar a { margin:0px 6px; }
#ned_toolbar a:hover { margin:0px 6px; color:#66d; }
</style>
</head>
<body>
<h1 id="page_title">prototyper</h1>
<div id="canvas">
<textarea id="proto" rows="10" cols="40">this is a textarea in the new prototype js html editor. Enjoy!</textarea>
</div>
<script type="text/javascript">var Editor = new EditorApp('proto');</script>
<!-- Footer -->
<script type="text/javascript">p('<div id="footer">js timer: ' + jstx() + ' s</div>'); l('script complete');</script>
</body>
</html>
%%
cron test
%%(bash)
#!/bin/bash
# Simple bash script to test cron
# COMMAND: $ ~/cron/test.sh
# CRON.D: * * * * 1-5 tatwell ~/cron/test.sh >> ~/cron/test_result.txt 2&>1
#Test Commands
TEST_DATE="date -R"
TEST_PHP="php -v"
TEST_PHP5="php5 -v"
TEST_LYNX="lynx -version"
TEST_WGET="wget -v"
TEST_FIND="find --version"
TEST_TOUCH="touch --version"
#Other Settings
HR="\n----------------------------\n"
echo -e "\n\n** Starting Cron Test **\n"
echo -e "DATE:\n"
$TEST_DATE
echo -e $HR
# Php Tests
echo -e "PHP:\n"
$TEST_PHP
echo -e $HR
echo -e "PHP5:\n"
$TEST_PHP5
echo -e $HR
echo -e "FIND:\n"
$TEST_FIND
echo -e $HR
echo -e "TOUCH:\n"
$TEST_TOUCH
echo -e $HR
echo -e "LYNX:\n"
$TEST_LYNX
echo -e $HR
echo -e "WGET:\n"
$TEST_WGET -V
echo -e "\n** Cron Test Complete **\n\n"
%%
Additions:
find files by size or data
Deletions:
Additions:
===find files by size or data===
# basic (source: http://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/)
$ find /path/to/files* -mtime +5 -ls
# delete
$ find /path/to/files* -mtime +5 -exec rm {} \;
# files only (http://www.unix.com/shell-programming-scripting/32816-need-remove-files-older-than-30-days-except-directories.html)
$ find /path/to/files -type f -mtime +90 -exec rm {} \;
# dirs only (http://lowfatlinux.com/linux-find.html)
$ find /path/to/files -type d -ok rmdir {} \;
# find files by size (http://lowfatlinux.com/linux-find.html)
$ find /path/to/files -size +100k -ls
# find files older than 8 hours (http://www.unix.com/shell-programming-scripting/32816-need-remove-files-older-than-30-days-except-directories.html)
$ touch -t `date --date='12 hours ago' +%Y%m%d%H%M` time_marker
$ find . -type f -newer time_marker -ls
# find files by size and age
$ find /path/to/files -type f -mtime +1 -size +5k -ls
# remove files older than 4 hours and larger than 5 kb
$ touch -t `date --date='4 hours ago' +%Y%m%d%H%M` time_marker
$ find /path/to/files -type f -newer time_marker -ls
# basic (source: http://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/)
$ find /path/to/files* -mtime +5 -ls
# delete
$ find /path/to/files* -mtime +5 -exec rm {} \;
# files only (http://www.unix.com/shell-programming-scripting/32816-need-remove-files-older-than-30-days-except-directories.html)
$ find /path/to/files -type f -mtime +90 -exec rm {} \;
# dirs only (http://lowfatlinux.com/linux-find.html)
$ find /path/to/files -type d -ok rmdir {} \;
# find files by size (http://lowfatlinux.com/linux-find.html)
$ find /path/to/files -size +100k -ls
# find files older than 8 hours (http://www.unix.com/shell-programming-scripting/32816-need-remove-files-older-than-30-days-except-directories.html)
$ touch -t `date --date='12 hours ago' +%Y%m%d%H%M` time_marker
$ find . -type f -newer time_marker -ls
# find files by size and age
$ find /path/to/files -type f -mtime +1 -size +5k -ls
# remove files older than 4 hours and larger than 5 kb
$ touch -t `date --date='4 hours ago' +%Y%m%d%H%M` time_marker
$ find /path/to/files -type f -newer time_marker -ls
Additions:
TEST_FIND="find --version"
TEST_TOUCH="touch --version"
echo -e "FIND:\n"
$TEST_FIND
echo -e "TOUCH:\n"
$TEST_TOUCH
TEST_TOUCH="touch --version"
echo -e "FIND:\n"
$TEST_FIND
echo -e "TOUCH:\n"
$TEST_TOUCH
Additions:
cron test
%%(bash)
#!/bin/bash
# Simple bash script to test cron
# COMMAND: $ ~/cron/test.sh
# CRON.D: * * * * 1-5 tatwell ~/cron/test.sh >> ~/cron/test_result.txt 2&>1
#Test Commands
TEST_DATE="date -R"
TEST_PHP="php -v"
TEST_PHP5="php5 -v"
TEST_LYNX="lynx -version"
TEST_WGET="wget -v"
#Other Settings
HR="\n----------------------------\n"
echo -e "\n\n** Starting Cron Test **\n"
echo -e "DATE:\n"
$TEST_DATE
echo -e $HR
# Php Tests
echo -e "PHP:\n"
$TEST_PHP
echo -e $HR
echo -e "PHP5:\n"
$TEST_PHP5
echo -e $HR
echo -e "LYNX:\n"
$TEST_LYNX
echo -e $HR
echo -e "WGET:\n"
$TEST_WGET -V
echo -e "\n** Cron Test Complete **\n\n"
%%(bash)
#!/bin/bash
# Simple bash script to test cron
# COMMAND: $ ~/cron/test.sh
# CRON.D: * * * * 1-5 tatwell ~/cron/test.sh >> ~/cron/test_result.txt 2&>1
#Test Commands
TEST_DATE="date -R"
TEST_PHP="php -v"
TEST_PHP5="php5 -v"
TEST_LYNX="lynx -version"
TEST_WGET="wget -v"
#Other Settings
HR="\n----------------------------\n"
echo -e "\n\n** Starting Cron Test **\n"
echo -e "DATE:\n"
$TEST_DATE
echo -e $HR
# Php Tests
echo -e "PHP:\n"
$TEST_PHP
echo -e $HR
echo -e "PHP5:\n"
$TEST_PHP5
echo -e $HR
echo -e "LYNX:\n"
$TEST_LYNX
echo -e $HR
echo -e "WGET:\n"
$TEST_WGET -V
echo -e "\n** Cron Test Complete **\n\n"
Additions:
Scratchpad
%%
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>javascript canvas</title>
<!-- JS: timer -->
<script type="text/javascript">
var tx0 = new Date();
function jstx() { return ( ( new Date() ) - tx0 ) / 1000; }
function l() { if (eval('typeof(console)=="undefined"')) return; var arg=arguments, msg=''; for(i=0; i<arg.length; i++) { msg+=arg[i]+' '; } console.log('[log]', msg); }
function p(message) { document.write(message); }
</script>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="formState.js"></script>
<!-- JS: dev -->
<script type="text/javascript">
</script>
<!-- External Script -->
<!-- JS: dev -->
<script type="text/javascript">
var EditorApp = Class.create({
version : '0.1',
pre : 'ned_',
c : ' : ',
initialize: function(textarea_id)
{
this.id = this.pre + 'parent_' + textarea_id; // obj id
this.fid = this.id + '_undoable'; // form id
this.tid = textarea_id;
this.class = this.pre + 'block';
this.T = $(this.tid);
this.metabar = {};
this._update_dom();
this._add_observers();
},
_update_dom: function()
{
// get textarea parent and grandparent
this.Tp = this.T.getOffsetParent(this.T);
// create a parent dom element and form append textarea
this.E = new Element('div', { 'id': this.id, 'class': this.class });
this.F = new Element('form', { 'id': this.fid });
this.F.appendChild(this.T);
this.E.appendChild(this.F);
this.Tp.appendChild(this.E);
// append toolbar
this.addToolbar();
this.E.appendChild(this.toolbar);
// get dom obj
l(this.id, ' EditorApp created');
},
_add_observers: function()
{
// buffer
this.T.Buffer = new TextBuffer(20);
// add event listener
new Form.Element.Observer(
this.T.id,
2, // seconds
function(el, value){
el.Buffer.update(value);
}
)
this.T.observe('change', function(event)
{
l('observing changes on', this.T.id, 'for buffer');
El = Event.element(event);
});
},
addToolbar: function()
{
l('building toolbar');
BX = [];
// array: [0]id, [1]label, [2]target id, [3]callback
BX[0] = [this.pre + 'bold', '<b>', this.T.id, this.emboldenText];
BX[1] = [this.pre + 'ital', '<i>', this.T.id, this.testEvent];
BX[2] = [this.pre + 'undo', 'undo', this.T.id, this.undoEvent];
this.toolbar = new Element('div', { 'id': this.pre + 'toolbar' });
for ( var n=0; n<BX.length; n++ )
{
var new_bx = this.cxButton(BX[n][0], BX[n][1], BX[n][2], BX[n][3]);
this.toolbar.appendChild(new_bx);
}
},
cxButton: function(id, label, target, onclick_callback)
{
l('cxButton:',id,'|',label,'|',target);
Bx = new ToolButton(id, label, target, onclick_callback);
return Bx.E;
},
emboldenText: function(event)
{
el = Event.element(event); // element
t = $(el.target); // target
v = t.value; // target value
ins = ''; // insert
nv = v; // new value
ST = EditorApp.getSelectedText(t);
if ( ST[0] != false ) ins = '<strong>' + ST[0] + '</strong>';
nv = v.substring(0, ST[1]) + ins + v.substr(ST[2]);
t.value = nv;
l('event',event,': calling emboldenText on',t,'| insert: "',ins,'"');
EditorApp.selectRange($(t), ST[1] + ins.length, ST[1] + ins.length);
},
testEvent: function(event)
{
s = ' | ';
el = Event.element(event);
l('testEvent:','event=',event,s,'calling element=',el,s,'target=',el.target);
}
});
/*
returns an array holding:
[0]: selected text
[1]: start pos
[2]: end pos
*/
EditorApp.getSelectedText = function(el)
{
l("getting selected text from " + el.id + " : " + el.toString());
selected = [false, 0, 0];
// get start/end
var s1 = 0; var s2 = 0;
if ( typeof document.selection != 'undefined' )
{
var r = document.selection.createRange();
s1 = r.start;
s2 = r.end;
}
else if ( typeof el.selectionStart != 'undefined' )
{
s1 = el.selectionStart;
s2 = el.selectionEnd;
}
else
{
l('getSelectedText handle not found');
return selected;
}
while ( s2 > s1 && el.value.charAt(s2-1) == ' ' )
{
s2--;
}
l('selecting',s1,',',s2,'in',el.id);
if ( s2 - s1 < 1 ) return selected;
sel_text = el.value.substring(s1, s2);
l('selected text:', sel_text);
return [sel_text, s1, s2];
}
EditorApp.selectRange = function(el, p1, p2)
{
if(el.setSelectionRange)
{
el.focus();
el.setSelectionRange(p1,p2);
}
else if(el.createTextRange)
{
range=el.createTextRange();
range.collapse(true);
range.moveEnd('character',p2);
range.moveStart('character',p1);
range.select();
}
}
/*
Each button is an object and should have an action and a target. The target
is another object (or the button itself) upon which the action acts. The
action is a callback function which is called when button is clicked.
*/
var ToolButton = Class.create({
initialize: function(id, label, target_id, click_callback)
{
l('constructing ToolButton: ' + id);
// create button element (as a)
AttList = { 'id': id, 'onmouseover': 'javascript:this.style.cursor="pointer";' };
this.E = new Element('a', AttList).update(label);
// add attributes
this.E.id = id;
this.E.label = label;
this.E.target = target_id;
this.E.action = click_callback;
// add event listener
this.E.observe('click', function(event)
{
calling_el = Event.element(event);
click_callback(event);
$(calling_el.target).focus();
});
}
});
var TextBuffer = Class.create({
initialize: function(target_id, maxlen)
{
this.id = target_id;
this.maxlen = ( maxlen != undefined ) ? maxlen : 20;
this.E = $(target_id);
this.BUFFER = [];
this.ptr = -1;
},
// update buffer (alias of push)
update: function(textarea_value)
{
this.push(textarea_value);
},
// push buffer
push: function(str)
{
var buf_len = this.BUFFER.push(str);
var overflow = buf_len - this.maxlen;
while ( overflow > 0 )
{
overflow--;
this.BUFFER.shift();
buf_len--;
}
this.ptr = this.BUFFER.length - 1;
l("pushing '", str, "' on buffer and setting ptr to", this.ptr);
},
// undo buffer
undo: function()
{
this.ptr--;
if ( this.ptr < 0 ) this.ptr = 0;
var content = this.BUFFER[this.ptr];
l('undo: returning content "', content, "' at ptr", this.ptr);
return content;
},
// redo buffer
redo: function()
{
this.ptr++;
if ( this.ptr >= this.BUFFER.length ) this.ptr = this.BUFFER.length - 1;
var content = this.BUFFER[this.ptr];
l('redo: returning content "', content, "' at ptr", this.ptr);
return content;
}
});
/*
*/
var DomHandler = Class.create({
initialize: function()
{
l('constructing DomHandler ' + id);
}
});
</script>
<!-- External Script -->
<style type="text/css">
body { margin:0; padding:0; font-family:sans-serif; color:#ccf; }
h1 { margin:0 0 10px; padding:1em; border-bottom:1px solid #ccf; background: #f3f3ff; }
#footer {
clear:both; margin-top:12px; padding:4px; font: 11px verdana,sans-serif; border:1px solid #ccf; border-width:1px 0; background: #f3f3ff; text-align:center;
}
/* Editor */
.ned_block { width:300px; margin:0 auto; border:1px solid #ccc; }
.ned_block form, .ned_block textarea { margin:0; }
.ned_block textarea { width:300px; overflow-x:auto; margin:0; }
#ned_toolbar { text-align:center; margin:0; padding:3px; background:#f6f6f6; }
#ned_toolbar a { margin:0px 6px; }
#ned_toolbar a:hover { margin:0px 6px; color:#66d; }
</style>
</head>
<body>
<h1 id="page_title">prototyper</h1>
<div id="canvas">
<textarea id="proto" rows="10" cols="40">this is a textarea in the new prototype js html editor. Enjoy!</textarea>
</div>
<script type="text/javascript">var Editor = new EditorApp('proto');</script>
<!-- Footer -->
<script type="text/javascript">p('<div id="footer">js timer: ' + jstx() + ' s</div>'); l('script complete');</script>
</body>
</html>
%%
%%
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>javascript canvas</title>
<!-- JS: timer -->
<script type="text/javascript">
var tx0 = new Date();
function jstx() { return ( ( new Date() ) - tx0 ) / 1000; }
function l() { if (eval('typeof(console)=="undefined"')) return; var arg=arguments, msg=''; for(i=0; i<arg.length; i++) { msg+=arg[i]+' '; } console.log('[log]', msg); }
function p(message) { document.write(message); }
</script>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="formState.js"></script>
<!-- JS: dev -->
<script type="text/javascript">
</script>
<!-- External Script -->
<!-- JS: dev -->
<script type="text/javascript">
var EditorApp = Class.create({
version : '0.1',
pre : 'ned_',
c : ' : ',
initialize: function(textarea_id)
{
this.id = this.pre + 'parent_' + textarea_id; // obj id
this.fid = this.id + '_undoable'; // form id
this.tid = textarea_id;
this.class = this.pre + 'block';
this.T = $(this.tid);
this.metabar = {};
this._update_dom();
this._add_observers();
},
_update_dom: function()
{
// get textarea parent and grandparent
this.Tp = this.T.getOffsetParent(this.T);
// create a parent dom element and form append textarea
this.E = new Element('div', { 'id': this.id, 'class': this.class });
this.F = new Element('form', { 'id': this.fid });
this.F.appendChild(this.T);
this.E.appendChild(this.F);
this.Tp.appendChild(this.E);
// append toolbar
this.addToolbar();
this.E.appendChild(this.toolbar);
// get dom obj
l(this.id, ' EditorApp created');
},
_add_observers: function()
{
// buffer
this.T.Buffer = new TextBuffer(20);
// add event listener
new Form.Element.Observer(
this.T.id,
2, // seconds
function(el, value){
el.Buffer.update(value);
}
)
this.T.observe('change', function(event)
{
l('observing changes on', this.T.id, 'for buffer');
El = Event.element(event);
});
},
addToolbar: function()
{
l('building toolbar');
BX = [];
// array: [0]id, [1]label, [2]target id, [3]callback
BX[0] = [this.pre + 'bold', '<b>', this.T.id, this.emboldenText];
BX[1] = [this.pre + 'ital', '<i>', this.T.id, this.testEvent];
BX[2] = [this.pre + 'undo', 'undo', this.T.id, this.undoEvent];
this.toolbar = new Element('div', { 'id': this.pre + 'toolbar' });
for ( var n=0; n<BX.length; n++ )
{
var new_bx = this.cxButton(BX[n][0], BX[n][1], BX[n][2], BX[n][3]);
this.toolbar.appendChild(new_bx);
}
},
cxButton: function(id, label, target, onclick_callback)
{
l('cxButton:',id,'|',label,'|',target);
Bx = new ToolButton(id, label, target, onclick_callback);
return Bx.E;
},
emboldenText: function(event)
{
el = Event.element(event); // element
t = $(el.target); // target
v = t.value; // target value
ins = ''; // insert
nv = v; // new value
ST = EditorApp.getSelectedText(t);
if ( ST[0] != false ) ins = '<strong>' + ST[0] + '</strong>';
nv = v.substring(0, ST[1]) + ins + v.substr(ST[2]);
t.value = nv;
l('event',event,': calling emboldenText on',t,'| insert: "',ins,'"');
EditorApp.selectRange($(t), ST[1] + ins.length, ST[1] + ins.length);
},
testEvent: function(event)
{
s = ' | ';
el = Event.element(event);
l('testEvent:','event=',event,s,'calling element=',el,s,'target=',el.target);
}
});
/*
returns an array holding:
[0]: selected text
[1]: start pos
[2]: end pos
*/
EditorApp.getSelectedText = function(el)
{
l("getting selected text from " + el.id + " : " + el.toString());
selected = [false, 0, 0];
// get start/end
var s1 = 0; var s2 = 0;
if ( typeof document.selection != 'undefined' )
{
var r = document.selection.createRange();
s1 = r.start;
s2 = r.end;
}
else if ( typeof el.selectionStart != 'undefined' )
{
s1 = el.selectionStart;
s2 = el.selectionEnd;
}
else
{
l('getSelectedText handle not found');
return selected;
}
while ( s2 > s1 && el.value.charAt(s2-1) == ' ' )
{
s2--;
}
l('selecting',s1,',',s2,'in',el.id);
if ( s2 - s1 < 1 ) return selected;
sel_text = el.value.substring(s1, s2);
l('selected text:', sel_text);
return [sel_text, s1, s2];
}
EditorApp.selectRange = function(el, p1, p2)
{
if(el.setSelectionRange)
{
el.focus();
el.setSelectionRange(p1,p2);
}
else if(el.createTextRange)
{
range=el.createTextRange();
range.collapse(true);
range.moveEnd('character',p2);
range.moveStart('character',p1);
range.select();
}
}
/*
Each button is an object and should have an action and a target. The target
is another object (or the button itself) upon which the action acts. The
action is a callback function which is called when button is clicked.
*/
var ToolButton = Class.create({
initialize: function(id, label, target_id, click_callback)
{
l('constructing ToolButton: ' + id);
// create button element (as a)
AttList = { 'id': id, 'onmouseover': 'javascript:this.style.cursor="pointer";' };
this.E = new Element('a', AttList).update(label);
// add attributes
this.E.id = id;
this.E.label = label;
this.E.target = target_id;
this.E.action = click_callback;
// add event listener
this.E.observe('click', function(event)
{
calling_el = Event.element(event);
click_callback(event);
$(calling_el.target).focus();
});
}
});
var TextBuffer = Class.create({
initialize: function(target_id, maxlen)
{
this.id = target_id;
this.maxlen = ( maxlen != undefined ) ? maxlen : 20;
this.E = $(target_id);
this.BUFFER = [];
this.ptr = -1;
},
// update buffer (alias of push)
update: function(textarea_value)
{
this.push(textarea_value);
},
// push buffer
push: function(str)
{
var buf_len = this.BUFFER.push(str);
var overflow = buf_len - this.maxlen;
while ( overflow > 0 )
{
overflow--;
this.BUFFER.shift();
buf_len--;
}
this.ptr = this.BUFFER.length - 1;
l("pushing '", str, "' on buffer and setting ptr to", this.ptr);
},
// undo buffer
undo: function()
{
this.ptr--;
if ( this.ptr < 0 ) this.ptr = 0;
var content = this.BUFFER[this.ptr];
l('undo: returning content "', content, "' at ptr", this.ptr);
return content;
},
// redo buffer
redo: function()
{
this.ptr++;
if ( this.ptr >= this.BUFFER.length ) this.ptr = this.BUFFER.length - 1;
var content = this.BUFFER[this.ptr];
l('redo: returning content "', content, "' at ptr", this.ptr);
return content;
}
});
/*
*/
var DomHandler = Class.create({
initialize: function()
{
l('constructing DomHandler ' + id);
}
});
</script>
<!-- External Script -->
<style type="text/css">
body { margin:0; padding:0; font-family:sans-serif; color:#ccf; }
h1 { margin:0 0 10px; padding:1em; border-bottom:1px solid #ccf; background: #f3f3ff; }
#footer {
clear:both; margin-top:12px; padding:4px; font: 11px verdana,sans-serif; border:1px solid #ccf; border-width:1px 0; background: #f3f3ff; text-align:center;
}
/* Editor */
.ned_block { width:300px; margin:0 auto; border:1px solid #ccc; }
.ned_block form, .ned_block textarea { margin:0; }
.ned_block textarea { width:300px; overflow-x:auto; margin:0; }
#ned_toolbar { text-align:center; margin:0; padding:3px; background:#f6f6f6; }
#ned_toolbar a { margin:0px 6px; }
#ned_toolbar a:hover { margin:0px 6px; color:#66d; }
</style>
</head>
<body>
<h1 id="page_title">prototyper</h1>
<div id="canvas">
<textarea id="proto" rows="10" cols="40">this is a textarea in the new prototype js html editor. Enjoy!</textarea>
</div>
<script type="text/javascript">var Editor = new EditorApp('proto');</script>
<!-- Footer -->
<script type="text/javascript">p('<div id="footer">js timer: ' + jstx() + ' s</div>'); l('script complete');</script>
</body>
</html>
%%
Additions:
Tivo for Radio: [[http://www.handcoding.com/archives/2005/03/20/ripping-npr-to-mp3-for-an-ipod/ excellent tutorial]] [[http://streamripper.sourceforge.net/ streamripper]] (windows or linux)
Additions:
OS Flash Dev: [[http://www.mtasc.org/ MTASC]] [[http://www.flashdevelop.org/community/viewtopic.php?t=305 flashdevelop.org]] [[http://fgpwiki.corewatch.net/index.php/How_do_I_get_Started game dev]]
Deletions:
Additions:
OS Flash Dev: [[http://www.mtasc.org/ MTASC]] [[http://fgpwiki.corewatch.net/index.php/How_do_I_get_Started game dev]]
Deletions:
Additions:
OS Flash Dev: [[http://www.mtasc.org/ MTASC]]
Deletions:
Additions:
OS Flash Dev: [[MTASC http://www.mtasc.org/]]
Additions:
""CakePhp"" config: [[http://www.virtualapplicationserver.com/CakePHP_MultipleInstallNotes.html multiple apps on single site]] [[http://bakery.cakephp.org/articles/view/hosting-admin-urls-on-a-subdomain admin subdomain]]
Additions:
SSL on Debian ""Apache2"": [[http://ilovett.com/blog/projects/installing-ssl-on-debian-apache2 ilovett.com]] [[http://www.debian-administration.org/articles/349 debian-administration.org]]
Deletions:
Additions:
SSL on Debian ""Apache2"": [[http://ilovett.com/blog/projects/installing-ssl-on-debian-apache2 ilovett.com]]
Deletions:
Additions:
SSL on Debian Apache2: [[http://ilovett.com/blog/projects/installing-ssl-on-debian-apache2 ilovett.com]]
Additions:
Fun with apache logs: [[http://russell.dyerhouse.com/cgi-bin/article.cgi?article_id=82 set-up]] [[http://www.builderau.com.au/program/unix/soa/Managing-and-parsing-your-Apache-logs/0,339024638,320280756,00.htm parsing]] [[http://crazytoon.com/2007/05/31/apache-how-do-you-set-up-log-rotation-and-archiving-for-apache-logs/ archiving logs]] [[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Deletions:
Additions:
[[http://crazytoon.com/2007/05/31/apache-how-do-you-set-up-log-rotation-and-archiving-for-apache-logs/ archiving logs]] [[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Deletions:
Fun with apache logs: [[http://russell.dyerhouse.com/cgi-bin/article.cgi?article_id=82 set-up]] [[http://www.builderau.com.au/program/unix/soa/Managing-and-parsing-your-Apache-logs/0,339024638,320280756,00.htm parsing]] [[http://crazytoon.com/2007/05/31/apache-how-do-you-set-up-log-rotation-and-archiving-for-apache-logs/ archiving logs]] [[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Linux on an old laptop: [[http://www.desktoplinux.com/articles/AT6185716632.html desktoplinux.com]] [[http://www.linuxforums.org/desktop/a_linux_distribution_for_an_old_laptop.html linuxforums.com]] [[http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/install-pre.html freebsd.org]]
[[CategoryCygwin7zip Using 7zip from command line on cygwin]]
Bulwer-Lytton Bad Fiction Contest: [[http://www.bulwer-lytton.com/#The%20rules rules]] [[http://www.bulwer-lytton.com/ home]]
musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE Justice with Uffie]] [[http://www.myspace.com/thetingtings Ting Tings]]
[[http://www.smashingmagazine.com/2007/11/08/40-excellent-freefonts-for-professional-design/ nice free fonts]]
vbs scripts: [[http://www.visualbasicscript.com/m_27365/tm.htm AD queries]] [[http://www.rlmueller.net/PingComputers.htm pinging computers]]
php server optimizaton: [[http://discuss.joelonsoftware.com/default.asp?joel.3.550939.7 joelonsoftware forums]] [[http://hudzilla.org/phpwiki/index.php?title=Performance hudzilla.org]]
Additions:
[[http://slashdot.org/article.pl?sid=08/01/06/1731247 Goodbye Cruel Word]]: Hello, [[http://www.lyx.org/ lyx]]!
Deletions:
Additions:
[[http://www.lyx.org/ lyx]]
Additions:
Fun with apache logs: [[http://russell.dyerhouse.com/cgi-bin/article.cgi?article_id=82 set-up]] [[http://www.builderau.com.au/program/unix/soa/Managing-and-parsing-your-Apache-logs/0,339024638,320280756,00.htm parsing]] [[http://crazytoon.com/2007/05/31/apache-how-do-you-set-up-log-rotation-and-archiving-for-apache-logs/ archiving logs]] [[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Deletions:
[[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Additions:
[[http://www.eos.ncsu.edu/remoteaccess/man/scp.html scp man]]
Additions:
ApacheModRewriteTestOk
Additions:
Fun with apache logs: [[http://russell.dyerhouse.com/cgi-bin/article.cgi?article_id=82 set-up]] [[http://www.builderau.com.au/program/unix/soa/Managing-and-parsing-your-Apache-logs/0,339024638,320280756,00.htm parsing]] [[http://crazytoon.com/2007/05/31/apache-how-do-you-set-up-log-rotation-and-archiving-for-apache-logs/ archiving logs]]
Deletions:
Additions:
Fun with apache logs: [[http://russell.dyerhouse.com/cgi-bin/article.cgi?article_id=82 set-up]] [[http://www.builderau.com.au/program/unix/soa/Managing-and-parsing-your-Apache-logs/0,339024638,320280756,00.htm parsing]]
Additions:
Linux on an old laptop: [[http://www.desktoplinux.com/articles/AT6185716632.html desktoplinux.com]] [[http://www.linuxforums.org/desktop/a_linux_distribution_for_an_old_laptop.html linuxforums.com]] [[http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/install-pre.html freebsd.org]]
Deletions:
Additions:
Linux on an old laptop: [[http://www.desktoplinux.com/articles/AT6185716632.html desktoplinux.com]] [[http://www.linuxforums.org/desktop/a_linux_distribution_for_an_old_laptop.html linuxforums.com]]
Additions:
[[CategoryCygwin7zip Using 7zip from command line on cygwin]]
Additions:
Bulwer-Lytton Bad Fiction Contest: [[http://www.bulwer-lytton.com/#The%20rules rules]] [[http://www.bulwer-lytton.com/ home]]
Additions:
[[CocktailNapkin2007 2007 Cocktail Napkin]]
Deletions:
[[http://it.slashdot.org/article.pl?sid=07/10/05/1234217&threshold=3 slashdot again on linux security]]
[[http://kwimgs.googlepages.com/ klenwell image site at pages.google]]
email trigger php: [[http://groups.google.com/group/comp.lang.php/browse_frm/thread/bfd6d0781d98a1c4/5d20f271cde37e56?lnk=st&q=Then+reload+service.+Please+note+somePHPfunctions.php&rnum=1#5d20f271cde37e56 gg]] [[http://www.google.com/search?hl=en&q=email+trigger+php+script&btnG=Google+Search google search]] [[http://www.mail-archive.com/php-general@lists.php.net/msg183184.html troubleshooting]]
[[http://www.freefavicon.com/freefavicons/objects/index.php favicons]]
free oss: [[http://www.theopencd.org/programs opencd.org]]
[[http://ask.slashdot.org/comments.pl?sid=236077&threshold=1&commentsort=0&mode=thread&pid=19268133#19268179 free pdf printers]] [[http://sourceforge.net/projects/pdfcreator/ pdfcreator]] (my pick)
[[http://www.phpunit.de/pocket_guide/index.en.php PHPUnit guide]]
[[https://help.ubuntu.com/community/CronHowto ubuntu cron]] [[http://ubuntuforums.org/archive/index.php/t-106270.html more info]] [[http://www.unixgeeks.org/security/newbie/unix/cron-1.html cron docs]]
[[http://developers.facebook.com/documentation.php facebook api documentation]] [[http://www.whenpenguinsattack.com/2006/10/05/how-to-use-the-facebook-api/ quick php tutorial]]
[[http://www.webhostingtalk.com/showthread.php?t=444824&highlight=document+root+linux+where Apache 2, SSL, and Virtual Hosts]]
[[http://it.slashdot.org/comments.pl?sid=276599&cid=20345963 linux forensics]] (slashdot.org)
[[http://flurdy.com/docs/postfix/ ubuntu mailserver]] (flurdy.com)
[[http://www.php.net/manual/en/function.setcookie.php#74401 cookie code]]
[[http://snook.ca/archives/html_and_css/six_keys_to_understanding_css_layouts/ 6 css layout keys]] [[http://www.alistapart.com/articles/sprites/ css sprites]]
[[http://developers.slashdot.org/comments.pl?sid=266713&cid=20187933 jungle disk]]
[[http://it.slashdot.org/comments.pl?sid=264749&cid=20165745 a comment on beautiful code]]
[[http://en.wikipedia.org/wiki/L-system L-system grammars]]
Google Books: [[http://books.google.com/books?id=cB4POeMPE9sC&pg=PA27&ots=9jiUY_-cc3&dq=von+Senden&sig=_3EJn7xXFYhBNHterYvsnnaBxfE Annie Dillard's Tinker Creek]] & [[http://books.google.com/books?id=xvoYAAAAIAAJ&q=von+Senden&dq=von+Senden&pgis=1 von Senden's Space and Sight]]
[[http://en.wikipedia.org/wiki/33_Thomas_Street brutalist]]
drupal dev: [[http://drupal.org/node/132845 to do tutorial]] [[http://api.drupal.org/api/HEAD/file/developer/topics/forms_api.html forms api]]
[[http://www.google-analytics.com/urchin.js google-analytics.com urchin script]]
[[http://www.cs.ualberta.ca/~chinook/play/ lose at checkers]] (www.cs.ualberta.ca)
drupal development: [[http://drupal.org/node/316 home]] [[http://drupal.org/node/79237 benchmarking]] [[http://buytaert.net/drupal-webserver-configurations-compared webserver configs]]
pretty code: [[http://ask.slashdot.org/article.pl?sid=07/07/14/2011208&threshold=3 slashdot]] [[http://www.oreilly.com/catalog/9780596510046/toc.html oreilly book]]
vps security: [[http://www.google.com/search?hl=en&safe=active&q=vps+recommended+firewall&btnG=Search google]] [[http://www.usefuljaja.com/2007/4/ubuntu-setup-page-1 ubuntu setup]] [[http://linux.about.com/od/ubusrv_doc/a/ubusg18t01.htm about.com]] [[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]] [[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
googles: [[http://www.google.com/search?hl=en&q=apache+password+protect&btnG=Google+Search apache .htaccess passwords]]
virtual host tutorials: [[http://www.onlamp.com/pub/a/apache/2003/07/24/vhosts.html?page=2 onlamp]] [[http://httpd.apache.org/docs/1.3/vhosts/name-based.html apache]] [[http://johnbokma.com/windows/apache-virtual-hosts-xp.html xp local]] [[http://rimuhosting.com/howto/ftp.jsp ftp]]
[[http://www.chiark.greenend.org.uk/~sgtatham/ Simon Tatham's Home Page]]
hosting issues - [[http://redmonk.com/sogrady/2006/05/22/who-turned-out-the-lights-or-the-straw-that-broke-1and1s-back/feed/ more hosting recs]]
[[http://www1.walthamforest.gov.uk/wmg/free.htm william morris wallpaper]]
[[http://www.afterdawn.com/guides/archive/how_to_play_flv_files.cfm how to play youtube videos offline]]
[[http://www.isbn.org/standards/home/isbn/us/isbn-fees.asp isbn fees]] [[http://www.lulu.com/ lulu]] [[http://www.sfwa.org/beware/printondemand.html print-on-demand caveat]] [[http://www.loc.gov/issn/issnbro.html#how issn]]
potential hosts: [[http://www.mediatemple.net/webhosting/dv/pricing.htm mediatemple.net]] [[http://www.jaguarpc.com/services/hosting/cpdemo.php jaguarpc.com]]
[[http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-branchtag.html#tsvn-dug-branch-1 branch/tag Tortoise SVN]]
[[http://www.mingw.org/ MinGW]] (learned about [[http://developers.slashdot.org/comments.pl?sid=237023&cid=19353345 here]])
ie-conditional stylesheets: [[http://www.quirksmode.org/css/condcom.html ie-conditional comments]]
%%<!--[if IE 6]><link rel="stylesheet" href="ie6.css" media="all" type="text/css" /><![endif]-->%%
[[http://tredosoft.com/Multiple_IE the ie multi-version thingamajig I've been looking for?]] (tredosoft.com)
underwriting: [[http://www.krza.org/underwriting.htm kzra.org]] [[http://www.upr.org/underwriting.html upr.org]]
[[http://advertisers.federatedmedia.net/plan.php?site=boingboing blog advertising]]
[[http://yro.slashdot.org/comments.pl?sid=234609&cid=19108551 "Sufficiently advanced satire is indistinguishable from reality."]] (I like this quote.)
[[http://www.digg.com/design/Over_300_Gorgeous_Icons_they_re_free_licensed_under_creative_commons tango lgpl icon set (see comments for other free icon sets)]] (digg.com)
[[http://www.italatin.com/latin.html latin translators]]
[[http://www.boutell.com/newfaq/creating/scriptpass.html posting data in js]] (boutell.com)
[[http://forums.somethingawful.com/showthread.php?threadid=2419323&perpage=40&pagenumber=1 NSFW = Now Safe For Work]] (somethingawful.com)
[[http://www.itasoftware.com/careers/jlisting.html?jid=6 a coding puzzle]] (itasoftware.com)
[[http://gpsgfaq.googlepages.com/google_page_creator.html google pages faq]]
[[http://www.myfinancialjourney.com/archive/frugal-cure-for-a-sore-throat#comment-1305 cure for the common sore throat?]]
[[http://800notes.com/ 800notes.com]] another one of a growing number of telemarketer logging sites
[[http://www.nytimes.com/2007/03/17/business/17online.html?th&emc=th how many visitors to make $50M?]] (nytimes.com)
[[http://www.digg.com/tech_news/Digg_s_Senior_System_Admin_on_How_to_Handle_Network_Growing_Pains digg senior sysadmin slideshow]]
[[http://www.everystockphoto.com/index.php everystockphoto.com]] [[http://morguefile.com/ morguefile.com]] [[http://www.flickr.com/search/advanced/ flickr photo search]]
[[http://www.nytimes.com/2007/03/11/business/11mortgage.html Crisis Looms]] (or is knocking at the door?) (nytimes.com)
[[http://www.nytimes.com/2007/03/11/books/review/Orr.t.html Annals of Poetry]] (nytimes.com)
[[http://weblogs.com/api.html weblogs.com api]]
[[http://www.codinghorror.com/blog/archives/000807.html reducing bandwidth]] (codinghorror.com)
[[http://www.worldmapper.org/thumbnails/mapindex1-12.html worldmapper]]
[[http://www.nytimes.com/2007/03/05/business/05lender.html hold for the pop]] (nytimes.com)
[[http://www.nytimes.com/2007/03/03/technology/03money.html?th&emc=th online salary reporting]] (New York Times) [[http://slashdot.org/article.pl?sid=07/03/06/0127205&threshold=3 the arts of negotiation]] (/.)
[[http://www.npr.org/templates/story/story.php?storyId=7630138 "Heart to Hang Onto" by Pete Townshend and Ronnie Lane]] (npr.org)
[[http://sourceforge.net/projects/snoopy/ Snoopy PHP Class]]
ubuntu programs: [[http://russellthedigitalninja.com/wordpress/?p=8 russellthedigitalninja.com]] [[http://www.digg.com/linux_unix/10_must_have_programs_for_a_new_Ubuntu_user digg]]
some rss feeds: [[http://rss.slashdot.org/Slashdot/slashdot slashdot]] [[http://www.nytimes.com/services/xml/rss/ NY Times]] [[http://news.yahoo.com/rss Yahoo!]] [[http://news.google.com/intl/en_us/news_feed_terms.html Google]] [[http://feeds.gawker.com/gawker/full Gawker]] [[http://www.digg.com/about-rss Digg]] [[http://en.wikipedia.org/wiki/Wikipedia:Syndication Wikipedia]]
[[http://www.socialtext.net/codev2/index.cgi?four_puzzles_from_cyberspace code v2 (by lawrence lessig) wiki]] (socialtext.net)
[[http://www.alternet.org/story/48278 Maybe We Deserve to Be Ripped Off By Bush's Billionaires]] (altnet.org)
[[http://www.linuxquestions.org/questions/showthread.php?s=9700928ee6fe99f6af8bce0257f2fb37&p=2579656#post2579656 computer on a stick]] [[http://www.puppyos.org/flash-puppy.htm puppy linux]]
[[http://alistapart.com/articles/footers/ footer at bottom of viewport]] (alistapart.com)
[[http://www.nextstudent.com/NextPath/nextPath-Online/Top-Web-Tools-for-College-Students.asp college student web tools]]
shared hosting prospects: [[http://www.servint.net/ servint ($ VPS+)]] [[http://www.webcinch.com/starter_plan.php webcinch.com]] [[http://steadfast.net/services/shared.php steadfast.net]] [[http://precisioneffect.com/web_hosting/ precisioneffect.com]] [[http://www.mediatemple.net/webhosting/gs/ mediatemple.net ($)]]
proxy sites (for when I absolutely, positively need to see it at work): [[http://www.avoidr.com/ avoidr.com]] [[http://www.theproxyfree.com/ theproxyfree.com]]
[[http://en.wikipedia.org/wiki/Logarithm logarithms]] (wikipedia)
slashdot submission of my [[http://slashdot.org/~klenwell/journal/162900 Proposal for User ID API]]
ucop customer service number: 1-800-888-8267
syllabification: [[http://en.wikipedia.org/wiki/English_phonology#Phonotactics English phonotactics]] (wikipedia) [[http://www.ingilish.com/englishsyllablestress.htm structural formula]] (ingilish.com)
[[http://pear.php.net/package/Text_TeXHyphen/docs/0.1.0/Text_TeXHyphen/Text_TeXHyphen_WordCache_SimpleHash.html#methodgetSyllables get syllables]] (pear.php.net) [[http://www.dcs.shef.ac.uk/research/ilash/Moby/ moby wordlists]]
[[http://www.maratz.com/blog/archives/2006/06/11/fancy-checkboxes-and-radio-buttons/ custom radio buttons]]
[[http://en.wikipedia.org/wiki/International_Phonetic_Alphabet IPA]] [[http://en.wikipedia.org/wiki/International_Phonetic_Alphabet_for_English#Consonants IPA English Charts]] [[http://upload.wikimedia.org/wikipedia/en/5/5a/IPA_vowel_chart_2005.png IPA vowel chart]] [[http://en.wikipedia.org/wiki/X-SAMPA X-SAMPA]] (wikipedia)
[[http://www.tobinsprout.net/ tobin sprout home page]]
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2572484#c27443690 internet argument!]] (fark.com)
[[http://www.poetrydaily.org/archdate.htm poetrydaily.org archive]]
[[http://sonnetmonkeymanuscripts.blogspot.com/ sonnet monkey manuscripts]] (5130824831237278418)
[[http://www.yisongyue.com/shaney/index.php mark v. shaney]] [[http://www.strout.net/python/shaney.py python code]]
split this expression: **a b | {a} {b|c} d** ([[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 1]] [[http://www.devnetwork.net/forums/viewtopic.php?t=51706&view=previous&sid=4698979ab287e4ad427517cddd4ec8e5 ex 2]] [[http://72.14.253.104/search?q=cache:H8tM1cTiB-oJ:www.thescripts.com/forum/post16376-6.html+preg_split+%22not+within%22&hl=en&gl=us&ct=clnk&cd=27 ex 3]] [[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 4]]) **[[http://groups.google.com/group/comp.lang.php/msg/07fa10aed96b2268 solution]]**
simple php spam filter ([[http://groups.google.com/group/comp.lang.php/msg/3a2c3b085f7d19ec source]]): %%(php) if ( substr_count($string, 'http://') > 1 ) $is_spam = 1; %%
[[http://www.faceresearch.org/tech/demos/average the ultimate Afro-Eurasian girl of your dreams]] ([[http://www.digg.com/general_sciences/I_created_a_woman_so_beautiful_she_made_me_melt digg]])
[[http://cutlersoftware.com/ubuntuinstall/ ubuntu installation guide]] ([[http://www.digg.com/linux_unix/How_to_install_ANYTHING_in_Ubuntu_3 digg]])
[[http://www.kilgarriff.co.uk/bnc-readme.html kilgarriff's BNC frequency wordlists]] ([[http://www.kilgarriff.co.uk/BNC_lists/poscodes.html POS codes]])
[[http://www.crummy.com/features/StockSpam/ crummy.com stock spam monitor]]
[[http://groups-beta.google.com/group/bloggerDev/browse_frm/thread/278f9b138c890416 blogger API post uid]] (google groups)
[[https://mv.dmv.ca.gov/nrl/welcome.do Notice of Transfer and Release of Liability]] (dmv.ca.gov)
[[http://groups-beta.google.com/group/comp.lang.php/browse_frm/thread/475095e024649b24/021a0aa935e84ee5#021a0aa935e84ee5 memory_get_usage() for php on windows]] (comp.lang.php)
[[http://en.wikipedia.org/wiki/Kiwifruit kiwifruit is from China and Italy is the biggest producer]] (wikipedia)
[[http://www.eliteskills.com/free_education/ Massive Resource List for All Autodidacts]]
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2534916#c26968345 interesting post on recent military recruits]] (fark)
[[http://xoopsdocs.net/modules/docs/en/xu-002/online/ch02.html xoops installation]]
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2534916#c26961154 a nice visual summary of the Iraq situation]] (fark)
"" ""/look further down the page for a chilling (though apt) Goehring quote
[[http://aten.adapthost.net/PCRepairSystem.zip pc repair kit]] (via [[http://www.digg.com/software/Carry_a_PC_Repair_System_on_a_USB_Drive digg]])
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2529537 owls!]] (fark)
[[http://ocw.mit.edu/OcwWeb/Global/all-courses.htm mit ocw master course list]]
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2526573 fark play-by-play of bcs championship game]]
[[http://tsfraser.googlepages.com/index.html a cool googlepages page]] [[SpecialHH hh]]
[[http://imageshack.us/]] (fark image hosting)
[[http://slashdot.org/comments.pl?sid=215492&cid=17498006 cleaning your credit report]] (slashdot)
[[http://www.nytimes.com/2007/01/07/technology/07net.html?_r=1&th&emc=th&oref=slogin Attack of the Zombie Computers Is Growing Threat]] (New York Times)
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2518022#c26752565 amusing comment]] (fark)
[[http://photobucket.com/ photobucket.com]] (remote hosting site of choice)
[[http://groups-beta.google.com/group/comp.lang.php/browse_frm/thread/449e128f6dca06d3/ab9fe22174c64f36#ab9fe22174c64f36 spatial searches in php/mysql]] (comp.lang.php)
[[http://softwarefor.org/faq.html software for starving students]] (not anymore, but still feel like one)
[[http://www.utorrent.com/ utorrent]] ([[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2514053#c26711021 rec]])
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2497320#c26497988 cool graph]]
Additions:
musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE Justice with Uffie]] [[http://www.myspace.com/thetingtings Ting Tings]]
Deletions:
Additions:
[[http://www.smashingmagazine.com/2007/11/08/40-excellent-freefonts-for-professional-design/ nice free fonts]]
Additions:
vbs scripts: [[http://www.visualbasicscript.com/m_27365/tm.htm AD queries]] [[http://www.rlmueller.net/PingComputers.htm pinging computers]]
Deletions:
Additions:
[[http://www.visualbasicscript.com/m_27365/tm.htm vbs script]] (see AD part)
Additions:
php server optimizaton: [[http://discuss.joelonsoftware.com/default.asp?joel.3.550939.7 joelonsoftware forums]] [[http://hudzilla.org/phpwiki/index.php?title=Performance hudzilla.org]]
Additions:
406 error? http://urbangiraffe.com/2005/08/20/mysterious-406-error/
Additions:
[[http://it.slashdot.org/article.pl?sid=07/10/05/1234217&threshold=3 slashdot again on linux security]]
Additions:
[[http://kwimgs.googlepages.com/ klenwell image site at pages.google]]
Additions:
email trigger php: [[http://groups.google.com/group/comp.lang.php/browse_frm/thread/bfd6d0781d98a1c4/5d20f271cde37e56?lnk=st&q=Then+reload+service.+Please+note+somePHPfunctions.php&rnum=1#5d20f271cde37e56 gg]] [[http://www.google.com/search?hl=en&q=email+trigger+php+script&btnG=Google+Search google search]] [[http://www.mail-archive.com/php-general@lists.php.net/msg183184.html troubleshooting]]
Additions:
[[http://www.freefavicon.com/freefavicons/objects/index.php favicons]]
Additions:
musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]] [[http://www.myspace.com/thetingtings $]]
Deletions:
Additions:
""<small>links and notes for later organization</small>""
""<small>""musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]""</small>""
""<small>""musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]""</small>""
Deletions:
musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]
Additions:
musical grab bag: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]
Deletions:
Additions:
""<small>links and notes for later organization</small>
""<small>""music: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]""</small>""
free oss: [[http://www.theopencd.org/programs opencd.org]]
""<small>""music: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]""</small>""
free oss: [[http://www.theopencd.org/programs opencd.org]]
Deletions:
music: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]
Additions:
music: [[http://www.youtube.com/watch?v=-JQnn1a3CXE *]]
Additions:
[[http://ask.slashdot.org/comments.pl?sid=236077&threshold=1&commentsort=0&mode=thread&pid=19268133#19268179 free pdf printers]] [[http://sourceforge.net/projects/pdfcreator/ pdfcreator]] (my pick)
Deletions:
Additions:
[[http://ask.slashdot.org/comments.pl?sid=236077&threshold=1&commentsort=0&mode=thread&pid=19268133#19268179 free pdf printers]]
Additions:
[[http://www.phpunit.de/pocket_guide/index.en.php PHPUnit guide]]
Additions:
[[https://help.ubuntu.com/community/CronHowto ubuntu cron]] [[http://ubuntuforums.org/archive/index.php/t-106270.html more info]] [[http://www.unixgeeks.org/security/newbie/unix/cron-1.html cron docs]]
Deletions:
Additions:
[[https://help.ubuntu.com/community/CronHowto ubuntu cron]] [[http://ubuntuforums.org/archive/index.php/t-106270.html more info]]
Additions:
[[http://developers.facebook.com/documentation.php facebook api documentation]] [[http://www.whenpenguinsattack.com/2006/10/05/how-to-use-the-facebook-api/ quick php tutorial]]
Additions:
[[http://www.webhostingtalk.com/showthread.php?t=444824&highlight=document+root+linux+where Apache 2, SSL, and Virtual Hosts]]
Additions:
[[http://it.slashdot.org/comments.pl?sid=276599&cid=20345963 linux forensics]] (slashdot.org)
Additions:
[[http://flurdy.com/docs/postfix/ ubuntu mailserver]] (flurdy.com)
Additions:
[[http://www.php.net/manual/en/function.setcookie.php#74401 cookie code]]
Additions:
[[http://snook.ca/archives/html_and_css/six_keys_to_understanding_css_layouts/ 6 css layout keys]] [[http://www.alistapart.com/articles/sprites/ css sprites]]
Additions:
[[http://developers.slashdot.org/comments.pl?sid=266713&cid=20187933 jungle disk]]
Additions:
[[http://it.slashdot.org/comments.pl?sid=264749&cid=20165745 a comment on beautiful code]]
Additions:
[[http://en.wikipedia.org/wiki/L-system L-system grammars]]
Additions:
Google Books: [[http://books.google.com/books?id=cB4POeMPE9sC&pg=PA27&ots=9jiUY_-cc3&dq=von+Senden&sig=_3EJn7xXFYhBNHterYvsnnaBxfE Annie Dillard's Tinker Creek]] & [[http://books.google.com/books?id=xvoYAAAAIAAJ&q=von+Senden&dq=von+Senden&pgis=1 von Senden's Space and Sight]]
Deletions:
Additions:
[[http://books.google.com/books?id=cB4POeMPE9sC&pg=PA27&ots=9jiUY_-cc3&dq=von+Senden&sig=_3EJn7xXFYhBNHterYvsnnaBxfE Annie Dillard's Tinker Creek]] [[http://books.google.com/books?id=xvoYAAAAIAAJ&q=von+Senden&dq=von+Senden&pgis=1 von Senden's Space and Sight]]
Deletions:
Additions:
[[http://books.google.com/books?id=cB4POeMPE9sC&pg=PA27&ots=9jiUY_-cc3&dq=von+Senden&sig=_3EJn7xXFYhBNHterYvsnnaBxfE Annie Dillard's //Tinker Creek//]] [[http://books.google.com/books?id=xvoYAAAAIAAJ&q=von+Senden&dq=von+Senden&pgis=1 von Senden's //Space and Sight//]]
Additions:
[[http://en.wikipedia.org/wiki/33_Thomas_Street brutalist]]
Additions:
drupal dev: [[http://drupal.org/node/132845 to do tutorial]] [[http://api.drupal.org/api/HEAD/file/developer/topics/forms_api.html forms api]]
Additions:
[[http://tsfraser.googlepages.com/index.html a cool googlepages page]] [[SpecialHH hh]]
Deletions:
Additions:
[[http://www.google-analytics.com/urchin.js google-analytics.com urchin script]]
Additions:
[[http://www.cs.ualberta.ca/~chinook/play/ lose at checkers]] (www.cs.ualberta.ca)
Additions:
potential hosts: [[http://www.mediatemple.net/webhosting/dv/pricing.htm mediatemple.net]] [[http://www.jaguarpc.com/services/hosting/cpdemo.php jaguarpc.com]]
Deletions:
Additions:
drupal development: [[http://drupal.org/node/316 home]] [[http://drupal.org/node/79237 benchmarking]] [[http://buytaert.net/drupal-webserver-configurations-compared webserver configs]]
Additions:
pretty code: [[http://ask.slashdot.org/article.pl?sid=07/07/14/2011208&threshold=3 slashdot]] [[http://www.oreilly.com/catalog/9780596510046/toc.html oreilly book]]
Additions:
vps security: [[http://www.google.com/search?hl=en&safe=active&q=vps+recommended+firewall&btnG=Search google]] [[http://www.usefuljaja.com/2007/4/ubuntu-setup-page-1 ubuntu setup]] [[http://linux.about.com/od/ubusrv_doc/a/ubusg18t01.htm about.com]] [[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]] [[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
Deletions:
Additions:
vps security: [[http://www.google.com/search?hl=en&safe=active&q=vps+recommended+firewall&btnG=Search google]] [[http://linux.about.com/od/ubusrv_doc/a/ubusg18t01.htm about.com]] [[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]] [[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
Deletions:
Additions:
vps security: [[http://www.google.com/search?hl=en&safe=active&q=vps+recommended+firewall&btnG=Search google]] [[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]] [[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
Deletions:
[[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]]
[[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
Additions:
vps security: [[http://www.google.com/search?hl=en&safe=active&q=vps+recommended+firewall&btnG=Search google]]
[[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]]
[[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
[[http://www.webhostingtalk.com/showthread.php?t=468168 secure vps]]
[[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
Deletions:
Additions:
vps security: [[http://www.google.com/search?hl=en&safe=active&q=vps+recommended+firewall&btnG=Search google]] [[http://forums.vpslink.com/showthread.php?t=1580 security settings]] [[http://www.webhostgear.com/61.html install apf]]
virtual host tutorials: [[http://www.onlamp.com/pub/a/apache/2003/07/24/vhosts.html?page=2 onlamp]] [[http://httpd.apache.org/docs/1.3/vhosts/name-based.html apache]] [[http://johnbokma.com/windows/apache-virtual-hosts-xp.html xp local]] [[http://rimuhosting.com/howto/ftp.jsp ftp]]
virtual host tutorials: [[http://www.onlamp.com/pub/a/apache/2003/07/24/vhosts.html?page=2 onlamp]] [[http://httpd.apache.org/docs/1.3/vhosts/name-based.html apache]] [[http://johnbokma.com/windows/apache-virtual-hosts-xp.html xp local]] [[http://rimuhosting.com/howto/ftp.jsp ftp]]
Deletions:
virtual host tutorials: [[http://www.onlamp.com/pub/a/apache/2003/07/24/vhosts.html?page=2 onlamp]] [[http://httpd.apache.org/docs/1.3/vhosts/name-based.html apache]] [[http://johnbokma.com/windows/apache-virtual-hosts-xp.html xp local]]
Deletions:
Additions:
SpamTrap
Additions:
googles: [[http://www.google.com/search?hl=en&q=apache+password+protect&btnG=Google+Search apache .htaccess passwords]]
Additions:
virtual host tutorials: [[http://www.onlamp.com/pub/a/apache/2003/07/24/vhosts.html?page=2 onlamp]] [[http://httpd.apache.org/docs/1.3/vhosts/name-based.html apache]] [[http://johnbokma.com/windows/apache-virtual-hosts-xp.html xp local]]
Additions:
ftp tutorials: [[http://rimuhosting.com/howto/ftp.jsp 1]]
Additions:
[[http://www.chiark.greenend.org.uk/~sgtatham/ Simon Tatham's Home Page]]
Additions:
hosting issues - [[http://redmonk.com/sogrady/2006/05/22/who-turned-out-the-lights-or-the-straw-that-broke-1and1s-back/feed/ more hosting recs]]
Additions:
[[http://www1.walthamforest.gov.uk/wmg/free.htm william morris wallpaper]]
Additions:
[[http://www.afterdawn.com/guides/archive/how_to_play_flv_files.cfm how to play youtube videos offline]]
Additions:
[[http://www.isbn.org/standards/home/isbn/us/isbn-fees.asp isbn fees]] [[http://www.lulu.com/ lulu]] [[http://www.sfwa.org/beware/printondemand.html print-on-demand caveat]] [[http://www.loc.gov/issn/issnbro.html#how issn]]
Deletions:
Additions:
[[http://www.isbn.org/standards/home/isbn/us/isbn-fees.asp isbn fees]] [[http://www.lulu.com/ lulu]] [[http://www.sfwa.org/beware/printondemand.html print-on-demand caveat]]
Deletions:
Additions:
[[http://www.isbn.org/standards/home/isbn/us/isbn-fees.asp isbn fees]] [[http://www.lulu.com/ lulu]]
Additions:
[[http://www.jaguarpc.com/services/hosting/cpdemo.php potential host: jaguarpc.com]]
Additions:
[[http://advertisers.federatedmedia.net/plan.php?site=boingboing blog advertising]]
Additions:
[[http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-branchtag.html#tsvn-dug-branch-1 branch/tag Tortoise SVN]]
Additions:
[[http://www.mingw.org/ MinGW]] (learned about [[http://developers.slashdot.org/comments.pl?sid=237023&cid=19353345 here]])
Additions:
ie-conditional stylesheets: [[http://www.quirksmode.org/css/condcom.html ie-conditional comments]]
%%<!--[if IE 6]><link rel="stylesheet" href="ie6.css" media="all" type="text/css" /><![endif]-->%%
%%<!--[if IE 6]><link rel="stylesheet" href="ie6.css" media="all" type="text/css" /><![endif]-->%%
Deletions:
Additions:
ie-conditional stylesheets: [[http://www.quirksmode.org/css/condcom.html ie-conditional comments]] e.g. <!--[if IE 6]><link rel="stylesheet" href="ie6.css" media="all" type="text/css" /><![endif]-->
Additions:
[[http://tredosoft.com/Multiple_IE the ie multi-version thingamajig I've been looking for?]] (tredosoft.com)
Additions:
underwriting: [[http://www.krza.org/underwriting.htm kzra.org]] [[http://www.upr.org/underwriting.html upr.org]]
Additions:
[[http://yro.slashdot.org/comments.pl?sid=234609&cid=19108551 "Sufficiently advanced satire is indistinguishable from reality."]] (I like this quote.)
Additions:
[[http://www.digg.com/design/Over_300_Gorgeous_Icons_they_re_free_licensed_under_creative_commons tango lgpl icon set (see comments for other free icon sets)]] (digg.com)
Additions:
[[http://www.italatin.com/latin.html latin translators]]
Additions:
[[http://www.boutell.com/newfaq/creating/scriptpass.html posting data in js]] (boutell.com)
Additions:
[[http://forums.somethingawful.com/showthread.php?threadid=2419323&perpage=40&pagenumber=1 NSFW = Now Safe For Work]] (somethingawful.com)
Additions:
[[http://www.itasoftware.com/careers/jlisting.html?jid=6 a coding puzzle]] (itasoftware.com)
Additions:
[[http://gpsgfaq.googlepages.com/google_page_creator.html google pages faq]]
Additions:
[[http://www.myfinancialjourney.com/archive/frugal-cure-for-a-sore-throat#comment-1305 cure for the common sore throat?]]
Additions:
[[http://800notes.com/ 800notes.com]] another one of a growing number of telemarketer logging sites
Additions:
[[http://www.nytimes.com/2007/03/17/business/17online.html?th&emc=th how many visitors to make $50M?]] (nytimes.com)
Deletions:
Additions:
[[http://www.nytimes.com/2007/03/17/business/17online.html?th&emc=th how many visitors to make $50M?] (nytimes.com)
Additions:
[[http://www.digg.com/tech_news/Digg_s_Senior_System_Admin_on_How_to_Handle_Network_Growing_Pains digg senior sysadmin slideshow]]
Additions:
[[http://www.everystockphoto.com/index.php everystockphoto.com]] [[http://morguefile.com/ morguefile.com]] [[http://www.flickr.com/search/advanced/ flickr photo search]]
Deletions:
Additions:
[[http://www.everystockphoto.com/index.php everystockphoto.com]] [[http://www.flickr.com/search/advanced/ flickr photo search]]
Deletions:
Additions:
[[http://www.everystockphoto.com/index.php everystockphoto.com]]
Additions:
[[http://www.nytimes.com/2007/03/11/business/11mortgage.html Crisis Looms]] (or is knocking at the door?) (nytimes.com)
Deletions:
Additions:
[[http://www.nytimes.com/2007/03/11/business/11mortgage.html Crisis Looms]] (or knocks?) (nytimes.com)
Additions:
[[http://www.nytimes.com/2007/03/11/books/review/Orr.t.html Annals of Poetry]] (nytimes.com)
Additions:
[[http://weblogs.com/api.html weblogs.com api]]
Additions:
[[http://www.codinghorror.com/blog/archives/000807.html reducing bandwidth]] (codinghorror.com)
Additions:
[[http://www.worldmapper.org/thumbnails/mapindex1-12.html worldmapper]]
Additions:
[[http://www.nytimes.com/2007/03/05/business/05lender.html hold for the pop]] (nytimes.com)
Additions:
[[http://www.nytimes.com/2007/03/03/technology/03money.html?th&emc=th online salary reporting]] (New York Times) [[http://slashdot.org/article.pl?sid=07/03/06/0127205&threshold=3 the arts of negotiation]] (/.)
Deletions:
Additions:
[[http://www.nytimes.com/2007/03/03/technology/03money.html?th&emc=th online salary reporting]] (New York Times) [[http://slashdot.org/article.pl?sid=07/03/06/0127205&threshold=3 avoiding the number]] (/.)
Deletions:
Additions:
[[http://www.nytimes.com/2007/03/03/technology/03money.html?th&emc=th online salary reporting]] (New York Times)
Additions:
[[http://www.npr.org/templates/story/story.php?storyId=7630138 "Heart to Hang Onto" by Pete Townshend and Ronnie Lane]] (npr.org)
Deletions:
Additions:
[[http://www.npr.org/templates/story/story.php?storyId=7630138 "Heart to Hang Onto" by Peter Townsend and Ronnie Lane]] (npr.org)
Deletions:
Additions:
[[http://www.npr.org/templates/story/story.php?storyId=7630138 "Heart to Hang Onto" by Peter Townsend and Ronnie Lane]]
Additions:
[[http://sourceforge.net/projects/snoopy/ Snoopy PHP Class]]
Additions:
ubuntu programs: [[http://russellthedigitalninja.com/wordpress/?p=8 russellthedigitalninja.com]] [[http://www.digg.com/linux_unix/10_must_have_programs_for_a_new_Ubuntu_user digg]]
Additions:
some rss feeds: [[http://rss.slashdot.org/Slashdot/slashdot slashdot]] [[http://www.nytimes.com/services/xml/rss/ NY Times]] [[http://news.yahoo.com/rss Yahoo!]] [[http://news.google.com/intl/en_us/news_feed_terms.html Google]] [[http://feeds.gawker.com/gawker/full Gawker]] [[http://www.digg.com/about-rss Digg]] [[http://en.wikipedia.org/wiki/Wikipedia:Syndication Wikipedia]]
Deletions:
Additions:
some rss feeds: [[http://rss.slashdot.org/Slashdot/slashdot slashdot]] [[http://www.nytimes.com/services/xml/rss/ NY Times]] [[http://news.yahoo.com/rss Yahoo!]] [[http://news.google.com/intl/en_us/news_feed_terms.html Google]] [[http://feeds.gawker.com/gawker/full Gawker]] [[http://en.wikipedia.org/wiki/Wikipedia:Syndication wikipedia]]
Additions:
[[http://www.socialtext.net/codev2/index.cgi?four_puzzles_from_cyberspace code v2 (by lawrence lessig) wiki]] (socialtext.net)
Additions:
[[http://www.alternet.org/story/48278 Maybe We Deserve to Be Ripped Off By Bush's Billionaires]] (altnet.org)
Additions:
[[http://www.linuxquestions.org/questions/showthread.php?s=9700928ee6fe99f6af8bce0257f2fb37&p=2579656#post2579656 computer on a stick]] [[http://www.puppyos.org/flash-puppy.htm puppy linux]]
Additions:
[[http://alistapart.com/articles/footers/ footer at bottom of viewport]] (alistapart.com)
Additions:
[[http://www.nextstudent.com/NextPath/nextPath-Online/Top-Web-Tools-for-College-Students.asp college student web tools]]
Additions:
shared hosting prospects: [[http://www.servint.net/ servint ($ VPS+)]] [[http://www.webcinch.com/starter_plan.php webcinch.com]] [[http://steadfast.net/services/shared.php steadfast.net]] [[http://precisioneffect.com/web_hosting/ precisioneffect.com]] [[http://www.mediatemple.net/webhosting/gs/ mediatemple.net ($)]]
Deletions:
Additions:
shared hosting prospects: [[http://www.servint.net/ servint (VPS+)]] [[http://www.webcinch.com/starter_plan.php webcinch.com]] [[http://steadfast.net/services/shared.php steadfast.net]]
Deletions:
Additions:
shared hosting prospects: [[http://www.servint.net/ servint]] [[http://www.webcinch.com/starter_plan.php webcinch]]
Deletions:
Additions:
hosting: [[http://www.servint.net/ servint]]
Additions:
proxy sites (for when I absolutely, positively need to see it at work): [[http://www.avoidr.com/ avoidr.com]] [[http://www.theproxyfree.com/ theproxyfree.com]]
Additions:
[[http://en.wikipedia.org/wiki/Logarithm logarithms]] (wikipedia)
slashdot submission of my [[http://slashdot.org/~klenwell/journal/162900 Proposal for User ID API]]
slashdot submission of my [[http://slashdot.org/~klenwell/journal/162900 Proposal for User ID API]]
Additions:
ucop customer service number: 1-800-888-8267
Additions:
[[http://en.wikipedia.org/wiki/International_Phonetic_Alphabet IPA]] [[http://en.wikipedia.org/wiki/International_Phonetic_Alphabet_for_English#Consonants IPA English Charts]] [[http://upload.wikimedia.org/wikipedia/en/5/5a/IPA_vowel_chart_2005.png IPA vowel chart]] [[http://en.wikipedia.org/wiki/X-SAMPA X-SAMPA]] (wikipedia)
Deletions:
Additions:
syllabification: [[http://en.wikipedia.org/wiki/English_phonology#Phonotactics English phonotactics]] (wikipedia) [[http://www.ingilish.com/englishsyllablestress.htm structural formula]] (ingilish.com)
Deletions:
Additions:
syllabification: [[http://en.wikipedia.org/wiki/English_phonology#Phonotactics English phonotactics]] (wikipedia)
Deletions:
Additions:
syllabifications: [[http://en.wikipedia.org/wiki/English_phonology#Phonotactics English phonotactics]] (wikipedia)
Additions:
[[http://pear.php.net/package/Text_TeXHyphen/docs/0.1.0/Text_TeXHyphen/Text_TeXHyphen_WordCache_SimpleHash.html#methodgetSyllables get syllables]] (pear.php.net) [[http://www.dcs.shef.ac.uk/research/ilash/Moby/ moby wordlists]]
Deletions:
Additions:
[[http://pear.php.net/package/Text_TeXHyphen/docs/0.1.0/Text_TeXHyphen/Text_TeXHyphen_WordCache_SimpleHash.html#methodgetSyllables get syllables]] (pear.php.net)
Additions:
[[http://www.maratz.com/blog/archives/2006/06/11/fancy-checkboxes-and-radio-buttons/ custom radio buttons]]
Additions:
[[http://en.wikipedia.org/wiki/International_Phonetic_Alphabet IPA]] [[http://upload.wikimedia.org/wikipedia/en/5/5a/IPA_vowel_chart_2005.png IPA vowel chart]] [[http://en.wikipedia.org/wiki/X-SAMPA X-SAMPA]] (wikipedia)
Deletions:
Additions:
[[http://en.wikipedia.org/wiki/International_Phonetic_Alphabet IPA]] [[http://upload.wikimedia.org/wikipedia/en/5/5a/IPA_vowel_chart_2005.png IPA vowel chart]] (wikipedia)
Additions:
[[http://www.tobinsprout.net/ tobin sprout home page]]
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2572484#c27443690 internet argument!]] (fark.com)
Additions:
[[http://www.poetrydaily.org/archdate.htm poetrydaily.org archive]]
Additions:
[[http://sonnetmonkeymanuscripts.blogspot.com/ sonnet monkey manuscripts]] (5130824831237278418)
Additions:
[[http://www.yisongyue.com/shaney/index.php mark v. shaney]] [[http://www.strout.net/python/shaney.py python code]]
Deletions:
Additions:
simple php spam filter ([[http://groups.google.com/group/comp.lang.php/msg/3a2c3b085f7d19ec source]]): %%(php) if ( substr_count($string, 'http://') > 1 ) $is_spam = 1; %%
Deletions:
Additions:
split this expression: **a b | {a} {b|c} d** ([[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 1]] [[http://www.devnetwork.net/forums/viewtopic.php?t=51706&view=previous&sid=4698979ab287e4ad427517cddd4ec8e5 ex 2]] [[http://72.14.253.104/search?q=cache:H8tM1cTiB-oJ:www.thescripts.com/forum/post16376-6.html+preg_split+%22not+within%22&hl=en&gl=us&ct=clnk&cd=27 ex 3]] [[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 4]]) **[[http://groups.google.com/group/comp.lang.php/msg/07fa10aed96b2268 solution]]**
Deletions:
[[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 4]]) **[[http://groups.google.com/group/comp.lang.php/msg/07fa10aed96b2268 solution]]**
Additions:
[[http://www.yisongyue.com/shaney/index.php mark v. shaney]]
split this expression: **a b | {a} {b|c} d** ([[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 1]] [[http://www.devnetwork.net/forums/viewtopic.php?t=51706&view=previous&sid=4698979ab287e4ad427517cddd4ec8e5 ex 2]] [[http://72.14.253.104/search?q=cache:H8tM1cTiB-oJ:www.thescripts.com/forum/post16376-6.html+preg_split+%22not+within%22&hl=en&gl=us&ct=clnk&cd=27 ex 3]]
[[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 4]]) **[[http://groups.google.com/group/comp.lang.php/msg/07fa10aed96b2268 solution]]**
split this expression: **a b | {a} {b|c} d** ([[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 1]] [[http://www.devnetwork.net/forums/viewtopic.php?t=51706&view=previous&sid=4698979ab287e4ad427517cddd4ec8e5 ex 2]] [[http://72.14.253.104/search?q=cache:H8tM1cTiB-oJ:www.thescripts.com/forum/post16376-6.html+preg_split+%22not+within%22&hl=en&gl=us&ct=clnk&cd=27 ex 3]]
[[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 4]]) **[[http://groups.google.com/group/comp.lang.php/msg/07fa10aed96b2268 solution]]**
Deletions:
Additions:
split this expression: **a b | {a} {b|c} d** ([[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 1]] [[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 2]] [[http://www.devnetwork.net/forums/viewtopic.php?t=51706&view=previous&sid=4698979ab287e4ad427517cddd4ec8e5 ex 3]] [[http://72.14.253.104/search?q=cache:H8tM1cTiB-oJ:www.thescripts.com/forum/post16376-6.html+preg_split+%22not+within%22&hl=en&gl=us&ct=clnk&cd=27 ex 4]])
Deletions:
Additions:
split this expression: **a b | {a} {b|c} d** ([[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 1]] [[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 2]] [[http://www.devnetwork.net/forums/viewtopic.php?t=51706&view=previous&sid=4698979ab287e4ad427517cddd4ec8e5 ex 3]])
Deletions:
Additions:
split this expression: **a b | {a} {b|c} d** ([[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default ex 1]] [[http://www.phpbuilder.com/board/showthread.php?s=c0850d95d2b286715f8ae2f91d23c06a&p=10739198#post10739198 ex 2]])
Deletions:
Additions:
split this expression: **a b | {a} {b|c} d** ([[http://codewalkers.com/forum/index.php?action=displaythread&forum=phpcoding&id=5781&realm=default sol 1?]])
Deletions:
Additions:
split this expression: **a b | {a} {b|c} d**
Deletions:
Additions:
split this expression: *a b | {a} {b|c} d**
Deletions:
Additions:
split this expression: **^SM_GET_PREP() ^BNC_GET_NOUN(1,1) | {prep_phrase} {`and`|`or`} ^SM_GET_PREP() ^BNC_GET_NOUN(1,1)**
Additions:
simple php spam filter: %%(php) if ( substr_count($string, 'http://') > 1 ) $is_spam = 1; %% ([[http://groups.google.com/group/comp.lang.php/msg/3a2c3b085f7d19ec source]])
Deletions:
Additions:
simple php spam filter: if ( substr_count($string, ""'http://'"") > 1 ) $is_spam = 1; ([[http://groups.google.com/group/comp.lang.php/msg/3a2c3b085f7d19ec source]])
Deletions:
Additions:
simple php spam filter: if ( substr_count($string, 'http://') > 1 ) $is_spam = 1; ([[http://groups.google.com/group/comp.lang.php/msg/3a2c3b085f7d19ec source]])
Additions:
[[http://www.faceresearch.org/tech/demos/average the ultimate Afro-Eurasian girl of your dreams]] ([[http://www.digg.com/general_sciences/I_created_a_woman_so_beautiful_she_made_me_melt digg]])
Deletions:
Additions:
[[the ultimate Afro-Eurasian girl of your dreams http://www.faceresearch.org/tech/demos/average]] ([[http://www.digg.com/general_sciences/I_created_a_woman_so_beautiful_she_made_me_melt digg]])
Additions:
[[http://cutlersoftware.com/ubuntuinstall/ ubuntu installation guide]] ([[http://www.digg.com/linux_unix/How_to_install_ANYTHING_in_Ubuntu_3 digg]])
Additions:
[[http://www.kilgarriff.co.uk/bnc-readme.html kilgarriff's BNC frequency wordlists]] ([[http://www.kilgarriff.co.uk/BNC_lists/poscodes.html POS codes]])
Deletions:
Additions:
[[http://www.kilgarriff.co.uk/bnc-readme.html kilgarriff's BNC frequency wordlists]]
Additions:
[[http://www.crummy.com/features/StockSpam/ crummy.com stock spam monitor]]
Additions:
[[http://groups-beta.google.com/group/bloggerDev/browse_frm/thread/278f9b138c890416 blogger API post uid]] (google groups)
Additions:
[[https://mv.dmv.ca.gov/nrl/welcome.do Notice of Transfer and Release of Liability]] (dmv.ca.gov)
Additions:
[[http://groups-beta.google.com/group/comp.lang.php/browse_frm/thread/475095e024649b24/021a0aa935e84ee5#021a0aa935e84ee5 memory_get_usage() for php on windows]] (comp.lang.php)
Additions:
[[http://en.wikipedia.org/wiki/Kiwifruit kiwifruit is from China and Italy is the biggest producer]] (wikipedia)
Additions:
[[http://www.eliteskills.com/free_education/ Massive Resource List for All Autodidacts]]
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2534916#c26968345 interesting post on recent military recruits]] (fark)
Additions:
[[http://xoopsdocs.net/modules/docs/en/xu-002/online/ch02.html xoops installation]]
Additions:
=====online cocktail napkin=====
""<small>links and notes for later organization</small>""
""<small>links and notes for later organization</small>""
Deletions:
""<small>for later organization</small>""
Additions:
[[http://aten.adapthost.net/PCRepairSystem.zip pc repair kit]] (via [[http://www.digg.com/software/Carry_a_PC_Repair_System_on_a_USB_Drive digg]])
Deletions:
Additions:
[[http://aten.adapthost.net/PCRepairSystem.zip pc repair kit]] (via [[digg http://www.digg.com/software/Carry_a_PC_Repair_System_on_a_USB_Drive]])
Additions:
"" ""/look further down the page for a chilling (though apt) Goehring quote
Deletions:
Additions:
/look further down the page for a chilling (though apt) Goehring quote
Deletions:
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2534916#c26961154 a nice visual summary of the Iraq situation]] (fark)
~ /look further down the page for a chilling (though apt) Goehring quote
~ /look further down the page for a chilling (though apt) Goehring quote
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2529537 owls!]] (fark)
Deletions:
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2529537 owls!]]
Additions:
[[http://ocw.mit.edu/OcwWeb/Global/all-courses.htm mit ocw master course list]]
Deletions:
Additions:
[[http://ocw.mit.edu/OcwWeb/Global/all-courses.htm MIT OCW Master Course List]]
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2526573 fark play-by-play of bcs championship game]]
Additions:
[[http://tsfraser.googlepages.com/index.html a cool googlepages page]]
Additions:
[[http://imageshack.us/]] (fark image hosting)
Additions:
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2518022#c26752565 amusing comment]] (fark)
Additions:
[[http://slashdot.org/comments.pl?sid=215492&cid=17498006 cleaning your credit report]] (slashdot)
Additions:
[[http://www.nytimes.com/2007/01/07/technology/07net.html?_r=1&th&emc=th&oref=slogin Attack of the Zombie Computers Is Growing Threat]] (New York Times)
Additions:
[[http://photobucket.com/ photobucket.com]] (remote hosting site of choice)
Deletions:
Additions:
[[http://photobucket.com/]]
Additions:
[[http://groups-beta.google.com/group/comp.lang.php/browse_frm/thread/449e128f6dca06d3/ab9fe22174c64f36#ab9fe22174c64f36 spatial searches in php/mysql]] (comp.lang.php)
Additions:
[[http://www.utorrent.com/ utorrent]] ([[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2514053#c26711021 rec]])
Deletions:
Additions:
[[http://softwarefor.org/faq.html software for starving students]] (not anymore, but still feel like one)
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2497320#c26497988 cool graph]]
----
[[CategorySpecial]]
[[http://forums.fark.com/cgi/fark/comments.pl?IDLink=2497320#c26497988 cool graph]]
----
[[CategorySpecial]]