Browse code
fixed some more problems
Showing 34 changed files
- pythonsnippets.py
- pythonsnippets1.py
- pythonsnippets_0020.py
- pythonsnippets_0021.py
- pythonsnippets_0022.py
- pythonsnippets_0023.py
- pythonsnippets_0024.py
- pythonsnippets_0025.py
- pythonsnippets_0026.py
- pythonsnippets_0027.py
- pythonsnippets_0028.py
- pythonsnippets_0029.py
- pythonsnippets_0030.py
- pythonsnippets_0031.py
- pythonsnippets_0032.py
- pythonsnippets_0033.py
- pythonsnippets_0034.py
- pythonsnippets_0035.py
- pythonsnippets_0036.py
- pythonsnippets_0037.py
- pythonsnippets_0038.py
- pythonsnippets_0039.py
- pythonsnippets_0040.py
- pythonsnippets_0041.py
- pythonsnippets_0042.py
- pythonsnippets_0043.py
- pythonsnippets_0044.py
- pythonsnippets_0045.py
- pythonsnippets_0046.py
- pythonsnippets_0047.py
- pythonsnippets_0048.py
- pythonsnippets_0049.py
- pythonsnippets_0050.py
- pythonsnippets_0051.py
1 | 1 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,1173 @@ |
1 |
+## pretty print dict |
|
2 |
+from emen2.subsystems import routing |
|
3 |
+for x in sorted(dct): |
|
4 |
+ print x.ljust(20), '=', dct[x] |
|
5 |
+## |
|
6 |
+ |
|
7 |
+days = ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'] |
|
8 |
+times = ['AM', 'PM', 'Night'] |
|
9 |
+from random import random |
|
10 |
+def get_dict(): |
|
11 |
+ result = {} |
|
12 |
+ for x in days: |
|
13 |
+ for y in times: |
|
14 |
+ result[(x,y)] = (random() < .5) |
|
15 |
+ return result |
|
16 |
+ |
|
17 |
+ |
|
18 |
+for x in range(20): |
|
19 |
+ a = db.newrecord('schedule', ctxid) |
|
20 |
+ a['schedule_times'] = get_dict() |
|
21 |
+ db.pclink(124, a.commit(), ctxid=ctxid) |
|
22 |
+ |
|
23 |
+## |
|
24 |
+ |
|
25 |
+def newfolder(name, parent): |
|
26 |
+ a = db.newrecord('folder', ctxid) |
|
27 |
+ a['folder_name'] = name |
|
28 |
+ db.pclink(parent, a.commit(), ctxid=ctxid) |
|
29 |
+## |
|
30 |
+print loads(db._Database__users.bdb[dumps('root')][:-1]+''' |
|
31 |
+S'email' |
|
32 |
+p17.''') |
|
33 |
+ |
|
34 |
+## |
|
35 |
+loads('''(iemen2.Database |
|
36 |
+User |
|
37 |
+p1 |
|
38 |
+(dp2 |
|
39 |
+S'username' |
|
40 |
+p3 |
|
41 |
+S'root' |
|
42 |
+p4 |
|
43 |
+sS'name' |
|
44 |
+p5 |
|
45 |
+(S'Database' |
|
46 |
+S'' |
|
47 |
+S'Administrator' |
|
48 |
+tp6 |
|
49 |
+sS'creator' |
|
50 |
+p7 |
|
51 |
+I0 |
|
52 |
+sS'privacy' |
|
53 |
+p8 |
|
54 |
+I0 |
|
55 |
+sS'creationtime' |
|
56 |
+p9 |
|
57 |
+S'2008/03/07 10:11:18' |
|
58 |
+p10 |
|
59 |
+sS'disabled' |
|
60 |
+p11 |
|
61 |
+I0 |
|
62 |
+sS'record' |
|
63 |
+p12 |
|
64 |
+NsS'groups' |
|
65 |
+p13 |
|
66 |
+(lp14 |
|
67 |
+I-1 |
|
68 |
+asS'password' |
|
69 |
+p15 |
|
70 |
+S'8843d7f92416211de9ebb963ff4ce28125932878' |
|
71 |
+p16 |
|
72 |
+sS'email' |
|
73 |
+p17 |
|
74 |
+Nsb.''') |
|
75 |
+## |
|
76 |
+class test(HTMLParser.HTMLParser): |
|
77 |
+ intable = False |
|
78 |
+ titling = False |
|
79 |
+ capturing = True |
|
80 |
+ cdata = [] |
|
81 |
+ out = u'' |
|
82 |
+ def handle_starttag(self, tag, attrs): |
|
83 |
+ print tag,attrs |
|
84 |
+ if dict(attrs).get('class', None) == 'm': self.capturing = False |
|
85 |
+ if tag.lower() == 'table': self.intable = True |
|
86 |
+ elif tag.lower() == 'title': self.titling = True |
|
87 |
+ elif tag.lower() == 'td' and dict(attrs).get('class', None) != 'm': |
|
88 |
+ self.capturing = True |
|
89 |
+ def handle_endtag(self, tag): |
|
90 |
+ if self.titling and tag.lower() == 'title': self.titling=False |
|
91 |
+ if self.capturing: |
|
92 |
+ out = u'\n'.join(self.cdata) |
|
93 |
+ self.cdata = [] |
|
94 |
+ self.out += '\n' + out |
|
95 |
+ #print out |
|
96 |
+ def handle_data(self, data): |
|
97 |
+ if self.capturing and self.intable and data.strip() != '': self.cdata.append(data.decode('utf-8')) |
|
98 |
+ if self.titling: self.cdata.append(u'HEADING: %s' % data.decode('utf-8')) |
|
99 |
+ |
|
100 |
+ |
|
101 |
+b=test() |
|
102 |
+for x in range(1,14): |
|
103 |
+ with file('3_%02d.html' % x, 'rU') as a: (b.reset(),setattr(b, 'capturing', True), b.feed(a.read())) |
|
104 |
+a = file('2_01.html') |
|
105 |
+b.feed(a.read()) |
|
106 |
+## |
|
107 |
+a = Database.User(dict(name=['Joe', '', 'Bloggs'], username='jblog', password='apassword', groups=[0])) |
|
108 |
+db.adduser(a) |
|
109 |
+db.approveuser(a.username,ctxid) |
|
110 |
+db.secrecordadduser ( ((a.username,),)*4, 125, ctxid=ctxid, recurse=3) |
|
111 |
+## |
|
112 |
+class Fwrapper: |
|
113 |
+ fileno = 3 |
|
114 |
+ def write(self, data): |
|
115 |
+ os.write(self.fileno, data) |
|
116 |
+ def read(self, data): |
|
117 |
+ pass |
|
118 |
+## |
|
119 |
+def mdir(name=None): |
|
120 |
+ if name != None: |
|
121 |
+ lis = dir(name); |
|
122 |
+ else: |
|
123 |
+ lis = dir() |
|
124 |
+ lis.sort(); |
|
125 |
+ lis = zip(lis[0::3],lis[1::3],lis[2::3]) |
|
126 |
+ in_ = lambda x: [a.ljust(25) for a in x] |
|
127 |
+ out = lambda lis: ['\t'.join(in_(x)) for x in lis] |
|
128 |
+ print '\n'.join(out(lis)) |
|
129 |
+## |
|
130 |
+from itertools import*;import sys;j=str.join;c=sys.stdin.read();print j('\n',map(lambda b:j(' ',[b,j('',islice(repeat('*'),len(filter(lambda x:x==b,c))))]),map(chr,range(97,122)))) |
|
131 |
+ |
|
132 |
+from itertools import*;import sys;j=str.join;c=sys.stdin.read();print j('\n',[j(' ',[b,j('',islice(repeat('*'),len([x for x in c if x==b])))])for b in map(chr,range(97,122))]) |
|
133 |
+ |
|
134 |
+from itertools import*;import sys;j=str.join;c=sys.stdin.read();print j('\n',[j(' ',[b,j('','*'*c.count(b))])for b in map(chr,range(65,123))]) |
|
135 |
+ |
|
136 |
+module Main where import Data.Char;main=getContents>>=(\b->putStrLn$(map chr[65..122]>>=(\c->c:' ':(take(length$filter(\x->x==c)b)$repeat '*')++"\n"))) |
|
137 |
+## |
|
138 |
+def mdir1(n): |
|
139 |
+ print '\n'.join((lambda l: ['\t'.join([a.ljust(25) for a in x]) for x in zip(l[0::3],l[1::3],l[2::3])])(sorted(dir(n) if n!=None else dir()))) |
|
140 |
+## |
|
141 |
+import ipc;reload(ipc) |
|
142 |
+import test_ipc;reload(test_ipc) |
|
143 |
+from ipc import *;from test_ipc import * |
|
144 |
+buf=Buf();a=Transport(buf);b=Transport(buf) |
|
145 |
+[x for x in a.send('hello')] |
|
146 |
+## |
|
147 |
+from twisted.spread import pb |
|
148 |
+from twisted.internet import reactor |
|
149 |
+from twisted.python import util |
|
150 |
+ |
|
151 |
+factory = pb.PBClientFactory() |
|
152 |
+reactor.connectTCP("localhost", 8789, factory) |
|
153 |
+d = factory.getRootObject() |
|
154 |
+a = [] |
|
155 |
+d.addCallback(lambda object: object.callRemote("nextQuote")) |
|
156 |
+d.addCallback(lambda echo: a.append(echo)) |
|
157 |
+d.addErrback(lambda reason: 'error: '+str(reason.value)) |
|
158 |
+d.addCallback(util.println) |
|
159 |
+reactor.run() |
|
160 |
+## |
|
161 |
+from twisted.internet import reactor |
|
162 |
+reactor.listenTCP(8789, factory) |
|
163 |
+reactor.run() |
|
164 |
+## |
|
165 |
+from twisted.spread import pb |
|
166 |
+class QuoteReader(pb.Root): |
|
167 |
+ def __init__(self, quoter): |
|
168 |
+ self.quoter = quoter |
|
169 |
+ def remote_nextQuote(self): |
|
170 |
+ return self.quoter.getQuote() |
|
171 |
+ |
|
172 |
+ |
|
173 |
+class Quoter(object): |
|
174 |
+ def getQuote(self): return 'Hello World!!\n' |
|
175 |
+ |
|
176 |
+ |
|
177 |
+factory = pb.PBServerFactory(QuoteReader(Quoter())) |
|
178 |
+## |
|
179 |
+from twisted.spread import pb |
|
180 |
+from twisted.internet import reactor |
|
181 |
+ |
|
182 |
+def main(): |
|
183 |
+ foo = Foo() |
|
184 |
+ factory = pb.PBClientFactory() |
|
185 |
+ reactor.connectTCP("localhost", 8800, factory) |
|
186 |
+ factory.getRootObject().addCallback(foo.step1) |
|
187 |
+ reactor.run() |
|
188 |
+ |
|
189 |
+ |
|
190 |
+class Foo: |
|
191 |
+ def __init__(self): |
|
192 |
+ self.oneRef = None |
|
193 |
+ def step1(self, obj): |
|
194 |
+ print "got one object:", obj |
|
195 |
+ self.oneRef = obj |
|
196 |
+ print "asking it to getTwo" |
|
197 |
+ self.oneRef.callRemote("getTwo").addCallback(self.step2) |
|
198 |
+ def step2(self, two): |
|
199 |
+ print "got two object:", two |
|
200 |
+ print "giving it back to one" |
|
201 |
+ print "one is", self.oneRef |
|
202 |
+ self.oneRef.callRemote("checkTwo", two) |
|
203 |
+ |
|
204 |
+ |
|
205 |
+main() |
|
206 |
+## |
|
207 |
+from twisted.spread import pb, jelly |
|
208 |
+from twisted.python import log |
|
209 |
+from twisted.internet import reactor |
|
210 |
+ |
|
211 |
+class MyException(pb.Error): pass |
|
212 |
+ |
|
213 |
+ |
|
214 |
+class MyOtherException(pb.Error): pass |
|
215 |
+ |
|
216 |
+ |
|
217 |
+class ScaryObject: |
|
218 |
+ # not safe for serialization |
|
219 |
+ pass |
|
220 |
+ |
|
221 |
+ |
|
222 |
+def worksLike(obj): |
|
223 |
+ # the callback/errback sequence in class One works just like an |
|
224 |
+ # asynchronous version of the following: |
|
225 |
+ try: |
|
226 |
+ response = obj.callMethod(name, arg) |
|
227 |
+ except pb.DeadReferenceError: |
|
228 |
+ print " stale reference: the client disconnected or crashed" |
|
229 |
+ except jelly.InsecureJelly: |
|
230 |
+ print " InsecureJelly: you tried to send something unsafe to them" |
|
231 |
+ except (MyException, MyOtherException): |
|
232 |
+ print " remote raised a MyException" # or MyOtherException |
|
233 |
+ except: |
|
234 |
+ print " something else happened" |
|
235 |
+ else: |
|
236 |
+ print " method successful, response:", response |
|
237 |
+ |
|
238 |
+ |
|
239 |
+class One: |
|
240 |
+ def worked(self, response): |
|
241 |
+ print " method successful, response:", response |
|
242 |
+ def check_InsecureJelly(self, failure): |
|
243 |
+ failure.trap(jelly.InsecureJelly) |
|
244 |
+ print " InsecureJelly: you tried to send something unsafe to them" |
|
245 |
+ return None |
|
246 |
+ def check_MyException(self, failure): |
|
247 |
+ which = failure.trap(MyException, MyOtherException) |
|
248 |
+ if which == MyException: |
|
249 |
+ print " remote raised a MyException" |
|
250 |
+ else: |
|
251 |
+ print " remote raised a MyOtherException" |
|
252 |
+ return None |
|
253 |
+ def catch_everythingElse(self, failure): |
|
254 |
+ print " something else happened" |
|
255 |
+ log.err(failure) |
|
256 |
+ return None |
|
257 |
+ def doCall(self, explanation, arg): |
|
258 |
+ print explanation |
|
259 |
+ try: |
|
260 |
+ deferred = self.remote.callRemote("fooMethod", arg) |
|
261 |
+ deferred.addCallback(self.worked) |
|
262 |
+ deferred.addErrback(self.check_InsecureJelly) |
|
263 |
+ deferred.addErrback(self.check_MyException) |
|
264 |
+ deferred.addErrback(self.catch_everythingElse) |
|
265 |
+ except pb.DeadReferenceError: |
|
266 |
+ print " stale reference: the client disconnected or crashed" |
|
267 |
+ def callOne(self): |
|
268 |
+ self.doCall("callOne: call with safe object", "safe string") |
|
269 |
+ def callTwo(self): |
|
270 |
+ self.doCall("callTwo: call with dangerous object", ScaryObject()) |
|
271 |
+ def callThree(self): |
|
272 |
+ self.doCall("callThree: call that raises remote exception", "panic!") |
|
273 |
+ def callShutdown(self): |
|
274 |
+ print "telling them to shut down" |
|
275 |
+ self.remote.callRemote("shutdown") |
|
276 |
+ def callFour(self): |
|
277 |
+ self.doCall("callFour: call on stale reference", "dummy") |
|
278 |
+ def got_obj(self, obj): |
|
279 |
+ self.remote = obj |
|
280 |
+ reactor.callLater(1, self.callOne) |
|
281 |
+ reactor.callLater(2, self.callTwo) |
|
282 |
+ reactor.callLater(3, self.callThree) |
|
283 |
+ reactor.callLater(4, self.callShutdown) |
|
284 |
+ reactor.callLater(5, self.callFour) |
|
285 |
+ reactor.callLater(6, reactor.stop) |
|
286 |
+ |
|
287 |
+ |
|
288 |
+factory = pb.PBClientFactory() |
|
289 |
+reactor.connectTCP("localhost", 8800, factory) |
|
290 |
+deferred = factory.getRootObject() |
|
291 |
+deferred.addCallback(One().got_obj) |
|
292 |
+reactor.run() |
|
293 |
+## |
|
294 |
+from twisted.spread import pb, jelly |
|
295 |
+from twisted.python import log |
|
296 |
+from twisted.internet import reactor |
|
297 |
+ |
|
298 |
+class LilyPond: |
|
299 |
+ def setStuff(self, color, numFrogs): |
|
300 |
+ self.color = color |
|
301 |
+ self.numFrogs = numFrogs |
|
302 |
+ def countFrogs(self): |
|
303 |
+ print "%d frogs" % self.numFrogs |
|
304 |
+ |
|
305 |
+ |
|
306 |
+class CopyPond(LilyPond, pb.Copyable): |
|
307 |
+ pass |
|
308 |
+ |
|
309 |
+ |
|
310 |
+class Sender: |
|
311 |
+ def __init__(self, pond): |
|
312 |
+ self.pond = pond |
|
313 |
+ def got_obj(self, remote): |
|
314 |
+ self.remote = remote |
|
315 |
+ d = remote.callRemote("takePond", self.pond) |
|
316 |
+ d.addCallback(self.ok).addErrback(self.notOk) |
|
317 |
+ def ok(self, response): |
|
318 |
+ print "pond arrived", response |
|
319 |
+ reactor.stop() |
|
320 |
+ def notOk(self, failure): |
|
321 |
+ print "error during takePond:" |
|
322 |
+ if failure.type == jelly.InsecureJelly: |
|
323 |
+ print " InsecureJelly" |
|
324 |
+ else: |
|
325 |
+ print failure |
|
326 |
+ reactor.stop() |
|
327 |
+ return None |
|
328 |
+ |
|
329 |
+def main(): |
|
330 |
+ from copy_sender import CopyPond # so it's not __main__.CopyPond |
|
331 |
+ pond = CopyPond() |
|
332 |
+ pond.setStuff("green", 7) |
|
333 |
+ pond.countFrogs() |
|
334 |
+ # class name: |
|
335 |
+ print ".".join([pond.__class__.__module__, pond.__class__.__name__]) |
|
336 |
+ sender = Sender(pond) |
|
337 |
+ factory = pb.PBClientFactory() |
|
338 |
+ reactor.connectTCP("localhost", 8800, factory) |
|
339 |
+ deferred = factory.getRootObject() |
|
340 |
+ deferred.addCallback(sender.got_obj) |
|
341 |
+ reactor.run() |
|
342 |
+ |
|
343 |
+if __name__ == '__main__': |
|
344 |
+ main() |
|
345 |
+## |
|
346 |
+import SocketServer |
|
347 |
+from cPickle import loads, dumps |
|
348 |
+ |
|
349 |
+class EchoHandler(SocketServer.BaseRequestHandler): |
|
350 |
+ dct = dict( |
|
351 |
+ demoObject = (1,2,3,4,5), |
|
352 |
+ demoObject1 = set([1,2,3,4,5]), |
|
353 |
+ demoObject2 = dict(q=(1,2,3,4,5)) |
|
354 |
+ ) |
|
355 |
+ def handle(self): |
|
356 |
+ while 1: |
|
357 |
+ data = self.request.recv(1024) |
|
358 |
+ if not data: break |
|
359 |
+ result = {} |
|
360 |
+ for key in data.split(): |
|
361 |
+ print key |
|
362 |
+ result[key] = self.dct.get(key, None) |
|
363 |
+ self.request.send(dumps(result)) |
|
364 |
+ |
|
365 |
+ |
|
366 |
+EchoServer = SocketServer.TCPServer(("", 8881), EchoHandler) |
|
367 |
+EchoServer.serve_forever() |
|
368 |
+## |
|
369 |
+wisted.spread import pb, jelly |
|
370 |
+from twisted.python import log |
|
371 |
+from twisted.internet import reactor |
|
372 |
+ |
|
373 |
+class LilyPond: |
|
374 |
+ def setStuff(self, color, numFrogs): |
|
375 |
+ self.color = color |
|
376 |
+ self.numFrogs = numFrogs |
|
377 |
+ def countFrogs(self): |
|
378 |
+ print "%d frogs" % self.numFrogs |
|
379 |
+ |
|
380 |
+ |
|
381 |
+class CopyPond(LilyPond, pb.Copyable): pass |
|
382 |
+ |
|
383 |
+class Sender: |
|
384 |
+ def __init__(self, pond): |
|
385 |
+ self.pond = pond |
|
386 |
+ def got_obj(self, remote): |
|
387 |
+ self.remote = remote |
|
388 |
+ d = remote.callRemote("takePond", self.pond) |
|
389 |
+ d.addCallback(self.ok).addErrback(self.notOk) |
|
390 |
+ def ok(self, response): |
|
391 |
+ print "pond arrived", response |
|
392 |
+ reactor.stop() |
|
393 |
+ def notOk(self, failure): |
|
394 |
+ print "error during takePond:" |
|
395 |
+ if failure.type == jelly.InsecureJelly: |
|
396 |
+ print " InsecureJelly" |
|
397 |
+ else: |
|
398 |
+ print failure |
|
399 |
+ reactor.stop() |
|
400 |
+ return None |
|
401 |
+ |
|
402 |
+def main(): |
|
403 |
+ from copy_sender import CopyPond # so it's not __main__.CopyPond |
|
404 |
+ pond = CopyPond() |
|
405 |
+ pond.setStuff("green", 7) |
|
406 |
+ pond.countFrogs() |
|
407 |
+ # class name: |
|
408 |
+ print ".".join([pond.__class__.__module__, pond.__class__.__name__]) |
|
409 |
+ sender = Sender(pond) |
|
410 |
+ factory = pb.PBClientFactory() |
|
411 |
+ reactor.connectTCP("localhost", 8800, factory) |
|
412 |
+ deferred = factory.getRootObject() |
|
413 |
+ deferred.addCallback(sender.got_obj) |
|
414 |
+ reactor.run() |
|
415 |
+ |
|
416 |
+if __name__ == '__main__': |
|
417 |
+ main() |
|
418 |
+#### |
|
419 |
+ |
|
420 |
+def cmp_dicts(dct, dct1): |
|
421 |
+ cp = set() |
|
422 |
+ for k in dct.keys(): |
|
423 |
+ if dct[k] != dct1.get(k,None): |
|
424 |
+ cp.add(k) |
|
425 |
+ return cp |
|
426 |
+ |
|
427 |
+#### |
|
428 |
+thelist = [1,2,3,4,5,6,7,8,9,8,7,7,6,5,3,2,1,0] |
|
429 |
+thelist.insert(0, len(thelist)) |
|
430 |
+datasize = thelist[0] |
|
431 |
+i=j=1; |
|
432 |
+while j <= (datasize-1): |
|
433 |
+ if thelist[j] == thelist[j+1]: |
|
434 |
+ j+=1 |
|
435 |
+ continue |
|
436 |
+ if i==j: |
|
437 |
+ i+=1 |
|
438 |
+ j+=1 |
|
439 |
+ continue |
|
440 |
+ thelist[i]=thelist[j] |
|
441 |
+ i+=1 |
|
442 |
+ j+=1 |
|
443 |
+ |
|
444 |
+#### |
|
445 |
+genetics.py -- python/ga |
|
446 |
+python -i genetics.py |
|
447 |
+#### |
|
448 |
+GOAL = 17 |
|
449 |
+POP = 30 |
|
450 |
+a = [encode(sensify_list(decode(get_n_genes()))) for x in range(POP)] |
|
451 |
+from functools import partial |
|
452 |
+cp = partial(compare_seqs, goal=GOAL) |
|
453 |
+a.sort(cp) |
|
454 |
+b = [evaluate(decode(x)) for x in a] |
|
455 |
+b |
|
456 |
+sorted(b) |
|
457 |
+ |
|
458 |
+a = [encode(sensify_list(decode(cross(*a[:2])))) for _ in range(POP)] |
|
459 |
+#### |
|
460 |
+import datetime |
|
461 |
+import emen2.subsystems.serializable_class |
|
462 |
+reload(emen2.subsystems.serializable_class) |
|
463 |
+from emen2.subsystems.serializable_class import * |
|
464 |
+a = schedule() |
|
465 |
+a.add_param('microscope', 129) |
|
466 |
+a.add_param('startdate', datetime.datetime(2008,1,1)) |
|
467 |
+a.add_param('microscope', db.getrecord(129,ctxid)) |
|
468 |
+#### |
|
469 |
+a = db.newrecord('folder') |
|
470 |
+a.commit() |
|
471 |
+a.commit() |
|
472 |
+a['folder_name'] = 'aasd' |
|
473 |
+a.commit() |
|
474 |
+#### |
|
475 |
+a = db.getrecord(range(200,300)) |
|
476 |
+[x['indexby'] for x in a] |
|
477 |
+for x in a: x['indexby'] = 'theteststring' |
|
478 |
+ |
|
479 |
+[x['indexby'] for x in a] |
|
480 |
+db.putrecord(a) |
|
481 |
+a = db.getrecord(range(200,300)) |
|
482 |
+[x['indexby'] for x in a] |
|
483 |
+### |
|
484 |
+range(463,962) |
|
485 |
+### |
|
486 |
+db._DBProxy__ctxid = 'b85246688f24c14712e0a7dfb93413f5defd50c4' |
|
487 |
+db.getrecord(0) |
|
488 |
+db.checkcontext() |
|
489 |
+dbtree.get_children() |
|
490 |
+dbtree.get_children([1]) |
|
491 |
+### |
|
492 |
+a = { |
|
493 |
+ 0: set([1, 14, 16, 17, 19, 20, 21, 22]), |
|
494 |
+ 1: set([2]), |
|
495 |
+ 2: set([]), |
|
496 |
+ 14: set([15]), |
|
497 |
+ 15: set([]), |
|
498 |
+ 16: set([18]), |
|
499 |
+ 17: set([]), |
|
500 |
+ 18: set([]), |
|
501 |
+ 19: set([]), |
|
502 |
+ 20: set([]), |
|
503 |
+ 21: set([]), |
|
504 |
+ 22: set([]) |
|
505 |
+} |
|
506 |
+def lookup(lis, table): |
|
507 |
+ cset = table[lis.pop(0)] |
|
508 |
+ ckey = None |
|
509 |
+ for x in lis[:-1]: |
|
510 |
+ if x in cset: |
|
511 |
+ ckey = x |
|
512 |
+ cset = table[x] |
|
513 |
+ print x, cset |
|
514 |
+ else: |
|
515 |
+ raise Exception() |
|
516 |
+ if lis[-1] in cset: |
|
517 |
+ key = lis[-1] |
|
518 |
+ return key, table[key] |
|
519 |
+ else: |
|
520 |
+ raise Exception() |
|
521 |
+ |
|
522 |
+import UserDict |
|
523 |
+import operator |
|
524 |
+class Tree(object, UserDict.DictMixin): |
|
525 |
+ def __init__(self, table, root): |
|
526 |
+ self.key = root |
|
527 |
+ self.filled = False |
|
528 |
+ self.children = {} |
|
529 |
+ if root in table: |
|
530 |
+ result = [] |
|
531 |
+ for child in table[root]: |
|
532 |
+ result.append((child, Tree(table, child))) |
|
533 |
+ self.filled = True |
|
534 |
+ self.children.update(result) |
|
535 |
+ |
|
536 |
+ def __getitem__(self, key): |
|
537 |
+ if hasattr(key, '__iter__'): |
|
538 |
+ return self.find([self.key] + list(key)) |
|
539 |
+ return self.children[key] |
|
540 |
+ def keys(self): |
|
541 |
+ return self.children.keys() |
|
542 |
+ def find(self, path): |
|
543 |
+ if len(path) == 1: |
|
544 |
+ return self |
|
545 |
+ else: |
|
546 |
+ value = self[path[1]] |
|
547 |
+ if value is not None: |
|
548 |
+ value = value.find(path[1:]) |
|
549 |
+ return value |
|
550 |
+ def __str__(self): |
|
551 |
+ return '\n'.join(self.mkstrtree(0)) |
|
552 |
+ def mkstrtree(self, level, space='--'): |
|
553 |
+ result = [space*level+str(level+1)+space+str(self.key)] |
|
554 |
+ for id, child in self.children.items(): |
|
555 |
+ result.extend(child.mkstrtree(level+1)) |
|
556 |
+ return result |
|
557 |
+ def mktree(self): |
|
558 |
+ result = {} |
|
559 |
+ def setitem(dict, key, value): dict[key] = value |
|
560 |
+ for key, value in self.children.items(): |
|
561 |
+ if value.filled: |
|
562 |
+ setitem(result, key, value.mktree()) |
|
563 |
+ else: |
|
564 |
+ setitem(result, key, None) |
|
565 |
+ return result |
|
566 |
+ def count(self): |
|
567 |
+ return len(self) + reduce(operator.add, |
|
568 |
+ [x.count() for x in self.children.values()], |
|
569 |
+ 0) |
|
570 |
+ |
|
571 |
+ |
|
572 |
+b = Tree(a, 135);print b |
|
573 |
+### |
|
574 |
+{ |
|
575 |
+ 0: { |
|
576 |
+ 1:{ |
|
577 |
+ 2: {} |
|
578 |
+ }, |
|
579 |
+ 14: { |
|
580 |
+ 15: {} |
|
581 |
+ }, |
|
582 |
+ 16:{ |
|
583 |
+ 18: {} |
|
584 |
+ }, |
|
585 |
+ 17:{} |
|
586 |
+ 19:{} |
|
587 |
+ 20:{} |
|
588 |
+ 21:{} |
|
589 |
+ 22:{} |
|
590 |
+ } |
|
591 |
+} |
|
592 |
+ |
|
593 |
+### |
|
594 |
+{0: set([1, 2, 3]), 1: set([2, 3, 4]), 2: set([3, 4, 5]), 3: set([4, 5, 6]), 4: set([5, 6, 7]), 5: set([8, 6, 7]), 6: set([8, 9, 7]), 7: set([8, 9]), 8: set([9]), 9: set([])} |
|
595 |
+### |
|
596 |
+import re |
|
597 |
+re.sub('&([^;]+);', r'&.\1.;', 'sdsfjsdlflsdfsdf&asdasd;dfsdfgsfdgfsd&dsfdsaf; &sfgfdgds;') |
|
598 |
+import htmlentitydefs |
|
599 |
+result = [] |
|
600 |
+for x in a: |
|
601 |
+ n = htmlentitydefs.codepoint2name.get(ord(x)) |
|
602 |
+ if n is not None: x = '&%s;' % n |
|
603 |
+ result.append(x) |
|
604 |
+#### |
|
605 |
+[htmlentitydefs.name2codepoint.get(y,y) for y in [x[1] or x[2] for x in re.findall('(&([^;]+);|([^&]))', a)]] |
|
606 |
+result = [] |
|
607 |
+for x in _: |
|
608 |
+ if isinstance(x, int): result.append(chr(x)) |
|
609 |
+ else: result.append(x) |
|
610 |
+ |
|
611 |
+ |
|
612 |
+''.join(result) |
|
613 |
+htmlentitydefs.codepoint2name[ord('&')] |
|
614 |
+### |
|
615 |
+class LazyLoad(object): |
|
616 |
+ def __init__(self, __func_, *args, **kwargs): |
|
617 |
+ self.__func = __func_ |
|
618 |
+ self.__args = list(args) |
|
619 |
+ self.__kwargs = kwargs |
|
620 |
+ def __get__(self, inst, cls): |
|
621 |
+ tb = cls.__dict__ |
|
622 |
+ nm = [x for x in tb.keys() if id(tb[x]) == id(self)][0] |
|
623 |
+ setattr(inst, nm, self.__func(*self.__args, **self.__kwargs)) |
|
624 |
+ return getattr(inst, nm) |
|
625 |
+ |
|
626 |
+def func(a,b,c): |
|
627 |
+ print a,b,c |
|
628 |
+ return a+b,c |
|
629 |
+ |
|
630 |
+class a(object): |
|
631 |
+ b = LazyLoad(func, 1,2,3) |
|
632 |
+ c = LazyLoad(func, 2,3,4) |
|
633 |
+ d = LazyLoad(func, 3,4,5) |
|
634 |
+ __e = LazyLoad(func, 4,5,6) |
|
635 |
+ def __str__(self): return str(self.__e) |
|
636 |
+#### |
|
637 |
+import HTMLParser |
|
638 |
+class TMP(HTMLParser.HTMLParser): |
|
639 |
+ INI = 0 |
|
640 |
+ DIV = 1 |
|
641 |
+ OTH = 2 |
|
642 |
+ AST = 3 |
|
643 |
+ def __init__(self): |
|
644 |
+ HTMLParser.HTMLParser.__init__(self) |
|
645 |
+ self.links = [];self.__tmp = [];self.dbuf = '';self.__state = self.INI;self.level = 0 |
|
646 |
+ def handle_starttag(self, tag, attrs): |
|
647 |
+ attrs = dict(attrs);self.level += 1 |
|
648 |
+ print '%stag: %r, attrs: %r, state: %r' % ('\t'*self.level, tag, attrs, self.__state), |
|
649 |
+ if tag == 'div' and self.__state != self.DIV and attrs.get('class') == 'smallbox': |
|
650 |
+ print 'useful div', |
|
651 |
+ self.__state = self.DIV |
|
652 |
+ elif tag == 'img' and self.__state == self.OTH: |
|
653 |
+ print 'useful image', |
|
654 |
+ self.__tmp.append(attrs['src']) |
|
655 |
+ elif tag == 'a' and self.__state == self.DIV: |
|
656 |
+ print 'useful link', |
|
657 |
+ self.__tmp.append(attrs['href']);self.__state = self.OTH |
|
658 |
+ print '..done' |
|
659 |
+ def handle_endtag(self, tag): |
|
660 |
+ print '%sclose tag: %r' % ('\t'*self.level, tag) |
|
661 |
+ self.level -= 1 |
|
662 |
+ if tag == 'div' and self.__state == self.DIV: |
|
663 |
+ if self.dbuf is not '': |
|
664 |
+ self.__tmp.append(self.dbuf) |
|
665 |
+ self.dbuf = '' |
|
666 |
+ self.links.append(self.__tmp);self.__tmp = [] |
|
667 |
+ self.__state == self.INI |
|
668 |
+ elif tag == 'a' and self.__state == self.OTH: |
|
669 |
+ self.__state = self.DIV |
|
670 |
+ if self.dbuf is not '': |
|
671 |
+ self.__tmp.append(self.dbuf) |
|
672 |
+ self.dbuf = '' |
|
673 |
+ def handle_data(self, data): |
|
674 |
+ if self.__state == self.OTH: |
|
675 |
+ self.dbuf += data + ' ' |
|
676 |
+ |
|
677 |
+#### |
|
678 |
+import HTMLParser |
|
679 |
+class TMP(HTMLParser.HTMLParser): |
|
680 |
+ INI = 0 |
|
681 |
+ DIV = 1 |
|
682 |
+ OTH = 2 |
|
683 |
+ def __init__(self): |
|
684 |
+ HTMLParser.HTMLParser.__init__(self) |
|
685 |
+ self.level = 0 |
|
686 |
+ def handle_starttag(self, tag, attrs): |
|
687 |
+ attrs = dict(attrs);self.level += 1 |
|
688 |
+ print '%s%r: %r' % ('\t'*self.level, tag, attrs) |
|
689 |
+ def handle_endtag(self, tag): |
|
690 |
+ print '%sclose tag: %r' % ('\t'*self.level, tag) |
|
691 |
+ self.level -= 1 |
|
692 |
+ def handle_data(self, data): |
|
693 |
+ print '%sdata: %r' %('\t'*(self.level+1), data) |
|
694 |
+ |
|
695 |
+ |
|
696 |
+import mechanize |
|
697 |
+def show_site(url): |
|
698 |
+ br = mechanize.Browser() |
|
699 |
+ r = br.open(url) |
|
700 |
+ print r.info() |
|
701 |
+ _a = TMP() |
|
702 |
+ _a.feed(r.read()) |
|
703 |
+ #return _a.links |
|
704 |
+ |
|
705 |
+ |
|
706 |
+a = filter(None, show_site(raw_input('url? '))) |
|
707 |
+#### |
|
708 |
+def inst(func): |
|
709 |
+ return func() |
|
710 |
+ |
|
711 |
+ |
|
712 |
+class IterDict(dict): |
|
713 |
+ keylist = [] |
|
714 |
+ @staticmethod |
|
715 |
+ def keylistiter_(): |
|
716 |
+ print IterDict.keylist |
|
717 |
+ index = 0 |
|
718 |
+ while 1: |
|
719 |
+ if index >= len(IterDict.keylist): index = 0 |
|
720 |
+ if not IterDict.keylist: break |
|
721 |
+ yield IterDict.keylist[index] |
|
722 |
+ index += 1 |
|
723 |
+ keylistiter = keylistiter_.__get__(1)() |
|
724 |
+ @classmethod |
|
725 |
+ def reset(cls): cls.keylistiter = cls.keylistiter_() |
|
726 |
+ def __setitem__(self, name, value): |
|
727 |
+ if name not in self.keylist: |
|
728 |
+ self.keylist.append(name) |
|
729 |
+ dict.__setitem__(self, name, value) |
|
730 |
+ def __delitem__(self, name): |
|
731 |
+ if name in self.keylist: |
|
732 |
+ del self.keylist[self.keylist.index(name)] |
|
733 |
+ dict.__delitem__(self, name) |
|
734 |
+ |
|
735 |
+ |
|
736 |
+import itertools |
|
737 |
+ |
|
738 |
+ |
|
739 |
+class CONT(object): pass |
|
740 |
+ |
|
741 |
+ |
|
742 |
+class PIDmanager(object): |
|
743 |
+ queue = IterDict() |
|
744 |
+ tasks = None |
|
745 |
+ @inst |
|
746 |
+ def pid_generator(): |
|
747 |
+ counter = 0 |
|
748 |
+ while 1: |
|
749 |
+ yield counter |
|
750 |
+ counter += 1 |
|
751 |
+ @classmethod |
|
752 |
+ def put_task(self, task): |
|
753 |
+ pid = self.pid_generator.next() |
|
754 |
+ self.queue[pid] = task |
|
755 |
+ print pid |
|
756 |
+ if self.tasks == None: |
|
757 |
+ self.queue.reset() |
|
758 |
+ self.tasks = self.queue.keylistiter |
|
759 |
+ self.tasks.next() |
|
760 |
+ @classmethod |
|
761 |
+ def run_task(self): |
|
762 |
+ if self.tasks != None: |
|
763 |
+ pid = self.tasks.next() |
|
764 |
+ task = self.queue[pid] |
|
765 |
+ if hasattr(task, '__iter__') and isinstance(task[0], CONT): |
|
766 |
+ _, func, args, kwargs, cleanup = task |
|
767 |
+ result = [] |
|
768 |
+ self.queue[pid] = func(*args, **kwargs) |
|
769 |
+ cleanup() |
|
770 |
+ return self.queue[pid] |
|
771 |
+ else: |
|
772 |
+ del self.queue[pid] |
|
773 |
+ return task |
|
774 |
+ @classmethod |
|
775 |
+ def run_all(self): |
|
776 |
+ try: |
|
777 |
+ while 1: self.run_task() |
|
778 |
+ except StopIteration: |
|
779 |
+ self.queue.reset() |
|
780 |
+ self.tasks == None |
|
781 |
+ |
|
782 |
+ |
|
783 |
+def print_many(gen, total=2000, count=0): |
|
784 |
+ print gen.next(), |
|
785 |
+ if count < total: |
|
786 |
+ return CONT(), print_many, (gen,), dict(total=total, count=count+1), cleanup |
|
787 |
+ |
|
788 |
+ |
|
789 |
+def cleanup(): print |
|
790 |
+ |
|
791 |
+ |
|
792 |
+PIDmanager.put_task( (CONT(), print_many, (itertools.cycle('a'),), dict(total=10), cleanup) ) |
|
793 |
+PIDmanager.put_task( (CONT(), print_many, (itertools.cycle('b'),), dict(total=10), cleanup) ) |
|
794 |
+PIDmanager.run_task() |
|
795 |
+###### |
|
796 |
+import functools |
|
797 |
+ |
|
798 |
+class Namespace(object): |
|
799 |
+ def __init__(self): |
|
800 |
+ self.__insts = {} |
|
801 |
+ def _bind_class(self, name, bases, dict): |
|
802 |
+ cls = type(name, bases, dict) |
|
803 |
+ cls.__ns = self |
|
804 |
+ def __init__(slf, *args, **kwargs): |
|
805 |
+ self.__insts[id(slf)] = slf |
|
806 |
+ cls.__init__(*args, **kwargs) |
|
807 |
+ print cls.__init__ |
|
808 |
+ cls.__init__ = __init__ |
|
809 |
+ return cls |
|
810 |
+ def __call__(self, func): |
|
811 |
+ result = func |
|
812 |
+ if not func.__name__.startswith('_'): |
|
813 |
+ setattr(self, func.__name__, func) |
|
814 |
+ result = None |
|
815 |
+ return result |
|
816 |
+ def __getattribute__(self, name): |
|
817 |
+ result = object.__getattribute__(self, name) |
|
818 |
+ if callable(result): |
|
819 |
+ result=functools.partial(result, self.__inst) |
|
820 |
+ return result |
|
821 |
+ |
|
822 |
+ |
|
823 |
+ |
|
824 |
+ |
|
825 |
+class NamespacedClass(object): |
|
826 |
+ a = Namespace() |
|
827 |
+ __metaclass__ = a._bind_class |
|
828 |
+ @a |
|
829 |
+ def b(self, test_arg): |
|
830 |
+ print self, test_arg |
|
831 |
+ |
|
832 |
+###### |
|
833 |
+a = db.newrecord('folder') |
|
834 |
+a.commit() |
|
835 |
+if type(_) != int: print '!!!!!!!!!!!!!!!!!!!!' |
|
836 |
+a.commit() |
|
837 |
+if _ is not 'No changes made': print '!!!!!!!!!!!!!!!!!!!!' |
|
838 |
+a['folder_name'] = 'aasd' |
|
839 |
+a.commit() |
|
840 |
+ |
|
841 |
+###### |
|
842 |
+import abc |
|
843 |
+class Pipe(object): |
|
844 |
+ __metaclass__ = abc.ABCMeta |
|
845 |
+ @property |
|
846 |
+ def file(self): return self.__file |
|
847 |
+ def __init__(self, file, *args, **kw): |
|
848 |
+ self.__file = file |
|
849 |
+ self.__delim = '\n' |
|
850 |
+ self.init(*args, **kw) |
|
851 |
+ def init(self, *args, **kw): pass |
|
852 |
+ # |
|
853 |
+ def __getattribute__(self, name): |
|
854 |
+ result = None |
|
855 |
+ try: |
|
856 |
+ result = object.__getattribute__(self, name) |
|
857 |
+ except Exception, e: |
|
858 |
+ try: |
|
859 |
+ result = self.__file.__getattribute__(name) |
|
860 |
+ except: |
|
861 |
+ raise e |
|
862 |
+ return result |
|
863 |
+ # |
|
864 |
+ def read(self, bytes=-1): |
|
865 |
+ buf = self.process_chunk(self.__file.read(bytes)) |
|
866 |
+ return buf |
|
867 |
+ # |
|
868 |
+ @abc.abstractmethod |
|
869 |
+ def process_chunk(self, chunk): return chunk |
|
870 |
+ |
|
871 |
+ |
|
872 |
+ |
|
873 |
+import re |
|
874 |
+class Grep(Pipe): |
|
875 |
+ def init(self, regex, delim='\n', *_, **__): |
|
876 |
+ self.__re = re.compile(regex) |
|
877 |
+ self.__delim = delim |
|
878 |
+ # |
|
879 |
+ def process_chunk(self, chunk): |
|
880 |
+ buf = chunk.split(self.__delim) |
|
881 |
+ out = [] |
|
882 |
+ while buf: |
|
883 |
+ line = buf.pop(0) |
|
884 |
+ if self.__re.search(line): |
|
885 |
+ out.append(line) |
|
886 |
+ return self.__delim.join(out) |
|
887 |
+###### |
|
888 |
+import functools |
|
889 |
+import collections |
|
890 |
+def instantiate(cls): return cls() |
|
891 |
+ |
|
892 |
+class Namespace(object): |
|
893 |
+ def registry(name, bases, dict_): |
|
894 |
+ cls = type(name, bases, dict_) |
|
895 |
+ cls.__dict = {} |
|
896 |
+ return cls |
|
897 |
+ __metaclass__ = registry |
|
898 |
+ def __init__(self, instance=None): |
|
899 |
+ self.__dict__ = self.__dict |
|
900 |
+ self.__inst = instance |
|
901 |
+ self._init() |
|
902 |
+ def _init(self): pass |
|
903 |
+ def __get__(self, instance, owner): |
|
904 |
+ result = type(self)(instance) |
|
905 |
+ return result |
|
906 |
+ def __check_inst(self): |
|
907 |
+ if self.__inst is None: |
|
908 |
+ raise AttributeError, 'this class is unbound, can\'t call methods' |
|
909 |
+ def __getattribute__(self, name): |
|
910 |
+ if not name.startswith('_'): |
|
911 |
+ self.__check_inst() |
|
912 |
+ result = object.__getattribute__(self, name) |
|
913 |
+ if callable(result) and not name.startswith('_'): |
|
914 |
+ result = functools.partial(result, self.__inst) |
|
915 |
+ return result |
|
916 |
+ |
|
917 |
+ |
|
918 |
+ |
|
919 |
+class DB(object): |
|
920 |
+ @instantiate |
|
921 |
+ class record(Namespace): |
|
922 |
+ @classmethod |
|
923 |
+ def _init(self): |
|
924 |
+ self.__value = 1 |
|
925 |
+ def get(self, db): |
|
926 |
+ return self.__value |
|
927 |
+ def set(self, db, value): |
|
928 |
+ self.__value = value |
|
929 |
+ def checkparam(self, db): |
|
930 |
+ print db.param.get() |
|
931 |
+ return db.param.get() == self.get() |
|
932 |
+ @instantiate |
|
933 |
+ class param(Namespace): |
|
934 |
+ @classmethod |
|
935 |
+ def _init(self): |
|
936 |
+ self.__value = 1 |
|
937 |
+ def get(self, db): |
|
938 |
+ db.othermethod(self.__value) |
|
939 |
+ return self.__value |
|
940 |
+ def set(self, db, value): |
|
941 |
+ db.othermethod(self.__value) |
|
942 |
+ self.__value = value |
|
943 |
+ db.othermethod(self.__value) |
|
944 |
+ def othermethod(self, value): print self, value |
|
945 |
+ def recordget(self): return self.record.get() |
|
946 |
+ def recordset(self, value): return self.record.set(value) |
|
947 |
+#### |
|
948 |
+import functools |
|
949 |
+ |
|
950 |
+def memoize(func): |
|
951 |
+ _cache = {} |
|
952 |
+ class NULL:pass |
|
953 |
+ NULL = NULL() |
|
954 |
+ @functools.wraps(func) |
|
955 |
+ def _inner(*args, **kwargs): |
|
956 |
+ _kwargs = tuple( |
|
957 |
+ (k, tuple(v) if hasattr(v, '__iter__') else v) for k,v in kwargs |
|
958 |
+ ) |
|
959 |
+ value = _cache.get((args, _kwargs), NULL) |
|
960 |
+ if value is NULL: |
|
961 |
+ value = func(*args, **kwargs) |
|
962 |
+ _cache[(args,_kwargs)] = value |
|
963 |
+ return value |
|
964 |
+ _inner.__enter__ = lambda *_: _inner |
|
965 |
+ _inner.__exit__ = lambda *_: _cache.clear() |
|
966 |
+ _inner.reset = _cache.clear |
|
967 |
+ _inner.cache = _cache |
|
968 |
+ _inner.orig = func |
|
969 |
+ return _inner |
|
970 |
+ |
|
971 |
+class return_if(object): |
|
972 |
+ def __init__(self, map): |
|
973 |
+ self._map = dict( |
|
974 |
+ (tuple(k) if hasattr(k, '__iter__') else (k,),v) for k,v in map.iteritems() |
|
975 |
+ ) |
|
976 |
+ self._func = lambda x:x |
|
977 |
+ def _inner(self, *args): |
|
978 |
+ if args in self._map: return self._map[args] |
|
979 |
+ else: return self._func(*args) |
|
980 |
+ def __call__(self, func): |
|
981 |
+ self._func = func |
|
982 |
+ return self._inner |
|
983 |
+ |
|
984 |
+ |
|
985 |
+@memoize |
|
986 |
+@return_if({1: 1}) |
|
987 |
+def fact(n): |
|
988 |
+ return n*fact(n-1) |
|
989 |
+ |
|
990 |
+ |
|
991 |
+@return_if({(1,1): 2, (2,2): 3, (3,3):4}) |
|
992 |
+def sum(a,b): |
|
993 |
+ return a+b |
|
994 |
+ |
|
995 |
+ |
|
996 |
+@memoize |
|
997 |
+@return_if({1: 1,2: 1}) |
|
998 |
+def fib(n): |
|
999 |
+ if n < 1: raise ValueError, "not n >= 1" |
|
1000 |
+ else: |
|
1001 |
+ return fib(n-1) + fib(n-2) |
|
1002 |
+#### |
|
1003 |
+ |
|
1004 |
+def b(): return a(2) |
|
1005 |
+ |
|
1006 |
+def c(): return b()*3 |
|
1007 |
+ |
|
1008 |
+def a(n): |
|
1009 |
+ if n==1: |
|
1010 |
+ return n |
|
1011 |
+ else: |
|
1012 |
+ return n*n-1 |
|
1013 |
+ |
|
1014 |
+ |
|
1015 |
+def d(a): |
|
1016 |
+ return |
|
1017 |
+ |
|
1018 |
+ |
|
1019 |
+def e(a): |
|
1020 |
+ return |
|
1021 |
+ |
|
1022 |
+#### |
|
1023 |
+ |
|
1024 |
+def f(h): |
|
1025 |
+ def g(n): |
|
1026 |
+ if n <= 1: return 1 |
|
1027 |
+ else: return n*h(n-1) |
|
1028 |
+ |
|
1029 |
+#def e(h): |
|
1030 |
+# def |
|
1031 |
+ |
|
1032 |
+def Y(f): |
|
1033 |
+ def g(h): |
|
1034 |
+ def i(x): |
|
1035 |
+ return f(h(h))(x) |
|
1036 |
+ return i |
|
1037 |
+ return g(g) |
|
1038 |
+ |
|
1039 |
+ |
|
1040 |
+@Y |
|
1041 |
+def fib(f): |
|
1042 |
+ def _inner(n): |
|
1043 |
+ if n in range(2): return 1 |
|
1044 |
+ else: return f(n-1) + f(n-2) |
|
1045 |
+ return _inner |
|
1046 |
+ |
|
1047 |
+ |
|
1048 |
+import functools |
|
1049 |
+ |
|
1050 |
+def bounce(func): |
|
1051 |
+ @functools.wraps(func) |
|
1052 |
+ def _inner(arg): |
|
1053 |
+ result = func(arg) |
|
1054 |
+ return result(fact) |
|
1055 |
+ return _inner |
|
1056 |
+ |
|
1057 |
+class return_if(object): |
|
1058 |
+ def __init__(self, map): |
|
1059 |
+ self._map = dict( |
|
1060 |
+ (tuple(k) if hasattr(k, '__iter__') else (k,),v) for k,v in map.iteritems() |
|
1061 |
+ ) |
|
1062 |
+ self._func = lambda x:x |
|
1063 |
+ def _inner(self, *args): |
|
1064 |
+ if args in self._map: return self._map[args] |
|
1065 |
+ else: return self._func(*args) |
|
1066 |
+ def __call__(self, func): |
|
1067 |
+ self._func = func |
|
1068 |
+ return self._inner |
|
1069 |
+@bounce |
|
1070 |
+@return_if({1: lambda _:1}) |
|
1071 |
+def fact(n): |
|
1072 |
+ return lambda x: n*x(n-1) |
|
1073 |
+ |
|
1074 |
+#### |
|
1075 |
+class Result(object): |
|
1076 |
+ def __repr__(self): return 'Result: %r' % self.v |
|
1077 |
+ def __init__(self, v): self.v = v |
|
1078 |
+ |
|
1079 |
+def wrapper(func): |
|
1080 |
+ def _inner(a): |
|
1081 |
+ results = [] |
|
1082 |
+ results.append(func(a)) |
|
1083 |
+ v = results[-1].next() |
|
1084 |
+ print v |
|
1085 |
+ while not isinstance(v, Result): |
|
1086 |
+ results.append(func(v)) |
|
1087 |
+ v = results[-1].next() |
|
1088 |
+ print v |
|
1089 |
+ results.pop() |
|
1090 |
+ if not results: result = v |
|
1091 |
+ else: |
|
1092 |
+ result = results.pop().send(v.v) |
|
1093 |
+ while results: |
|
1094 |
+ result = results.pop().send(result.v) |
|
1095 |
+ return result.v |
|
1096 |
+ return _inner |
|
1097 |
+ |
|
1098 |
+#### |
|
1099 |
+gen = fib(2) |
|
1100 |
+gen.next() |
|
1101 |
+gen1 = fib(_) |
|
1102 |
+gen1.next() |
|
1103 |
+gen.send(_.v) |
|
1104 |
+gen2 = fib(_) |
|
1105 |
+gen2.next() |
|
1106 |
+gen.send(_.v) |
|
1107 |
+_.v |
|
1108 |
+#### |
|
1109 |
+def wrapper(func): |
|
1110 |
+ def _inner(a): |
|
1111 |
+ results = [] |
|
1112 |
+ results.append(func(a)) |
|
1113 |
+ v = results[0].next() |
|
1114 |
+ idx = 0 |
|
1115 |
+ while True: |
|
1116 |
+ if not isinstance(v, Result): |
|
1117 |
+ results.append(func(v)) |
|
1118 |
+ idx = len(results) - 1 |
|
1119 |
+ v = results[idx].next() |
|
1120 |
+ else: |
|
1121 |
+ del results[idx] |
|
1122 |
+ if len(results) == 0: break |
|
1123 |
+ else: |
|
1124 |
+ idx -= 1 |
|
1125 |
+ v = results[idx].send(v.v) |
|
1126 |
+ return v.v |
|
1127 |
+ return _inner |
|
1128 |
+ |
|
1129 |
+@wrapper |
|
1130 |
+def fact(a): |
|
1131 |
+ if a == 1: |
|
1132 |
+ yield Result(1) |
|
1133 |
+ yield Result(a * (yield a-1)) |
|
1134 |
+ |
|
1135 |
+@wrapper |
|
1136 |
+def count(a): |
|
1137 |
+ if a == []: yield Result(0) |
|
1138 |
+ else: |
|
1139 |
+ yield Result(1 + (yield a[1:])) |
|
1140 |
+ |
|
1141 |
+@wrapper |
|
1142 |
+def fib(a): |
|
1143 |
+ if a in [1,2]: yield Result(1) |
|
1144 |
+ else: |
|
1145 |
+ z = (yield a-1) |
|
1146 |
+ b = (yield a-2) |
|
1147 |
+ yield Result( z + b ) |
|
1148 |
+ |
|
1149 |
+@wrapper |
|
1150 |
+def fib(a): |
|
1151 |
+ if a in [1,2]: yield Result(1) |
|
1152 |
+ else: |
|
1153 |
+ z = (yield a-1) |
|
1154 |
+ b = (yield a-2) |
|
1155 |
+ yield Result( z + b ) |
|
1156 |
+ |
|
1157 |
+ |
|
1158 |
+@wrapper |
|
1159 |
+def reverse(lis): |
|
1160 |
+ if lis == []: yield Result([]) |
|
1161 |
+ else: |
|
1162 |
+ yield Result( [(yield lis[1:]), lis[0]] ) |
|
1163 |
+## |
|
1164 |
+ |
|
1165 |
+def get_macaddr(): |
|
1166 |
+ 'Get Mac address in Python > 2.5' |
|
1167 |
+ import uuid |
|
1168 |
+ return ':'.join( |
|
1169 |
+ [ |
|
1170 |
+ a[x:x+2] for a in [ '%012x'%uuid.getnode() ] |
|
1171 |
+ for x in range(0,len(a),2) |
|
1172 |
+ ] |
|
1173 |
+ ) |
0 | 1174 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,157 @@ |
1 |
+import functools |
|
2 |
+ |
|
3 |
+def bounce(func): |
|
4 |
+ @functools.wraps(func) |
|
5 |
+ def _inner(arg): |
|
6 |
+ result = func(arg) |
|
7 |
+ return result(fact) |
|
8 |
+ return _inner |
|
9 |
+ |
|
10 |
+class return_if(object): |
|
11 |
+ def __init__(self, map): |
|
12 |
+ self._map = dict( |
|
13 |
+ (tuple(k) if hasattr(k, '__iter__') else (k,), v) for k,v in map.iteritems() |
|
14 |
+ ) |
|
15 |
+ self._func = lambda x:x |
|
16 |
+ def _inner(self, *args): |
|
17 |
+ if args in self._map: return self._map[args] |
|
18 |
+ else: return self._func(*args) |
|
19 |
+ def __call__(self, func): |
|
20 |
+ self._func = func |
|
21 |
+ return self._inner |
|
22 |
+ |
|
23 |
+@bounce |
|
24 |
+@return_if({1: lambda _:1}) |
|
25 |
+def fact(n): |
|
26 |
+ return lambda x: n*x(n-1) |
|
27 |
+ |
|
28 |
+ |
|
29 |
+def fact(m): |
|
30 |
+ @return_if({1: lambda :1}) |
|
31 |
+ def fact_inner(n): |
|
32 |
+ return lambda f: n*f(n-1) |
|
33 |
+ return fact_inner(m)(lambda n: fact_inner(n)) |
|
34 |
+ |
|
35 |
+assert fact(5) == 120 |
|
36 |
+print 'yes!' |
|
37 |
+#### |
|
38 |
+def for_(cond, cb, val): |
|
39 |
+ if cond(val): return while_(cond, cb, cb(val)) |
|
40 |
+ else: return val |
|
41 |
+ |
|
42 |
+def fact(n): |
|
43 |
+ return for_( (lambda x: x[1] > 1), |
|
44 |
+ ( lambda val: ( (val[0]*( val[1]-1 ) ), val[1]-1 ) ) |
|
45 |
+ )[0] |
|
46 |
+#### |
|
47 |
+import functools |
|
48 |
+class piecewise_function(object): |
|
49 |
+ def __init__(self, fallback): |
|
50 |
+ self._conds = [] |
|
51 |
+ self._fallback = fallback |
|
52 |
+# self.__call__ = functools.wrap(fallback)(self.__call__) |
|
53 |
+ def add_piece(self, cond): |
|
54 |
+ def _inner(f): |
|
55 |
+ self._conds.append((cond,f)) |
|
56 |
+ return self |
|
57 |
+ return _inner |
|
58 |
+ def __call__(self, *args, **kwargs): |
|
59 |
+ result = self._fallback |
|
60 |
+ for cond, func in self._conds: |
|
61 |
+ if cond(*args, **kwargs): result = func |
|
62 |
+ return result(*args, **kwargs) |
|
63 |
+ |
|
64 |
+#### |
|
65 |
+def caller(f): |
|
66 |
+ def _inner(*a, **kw): |
|
67 |
+ iter = f(*a, **kw) |
|
68 |
+ result = iter.next() |
|
69 |
+ print iter |
|
70 |
+ while hasattr(result, '__iter__') and callable(result[0]): |
|
71 |
+ result = iter.send(apply(result[0], *result[1:])) |
|
72 |
+ return result |
|
73 |
+ return _inner |
|
74 |
+ |
|
75 |
+ |
|
76 |
+@caller |
|
77 |
+def test(a): |
|
78 |
+ result = None |
|
79 |
+ if a == 1: |
|
80 |
+ yield 1 |
|
81 |
+ else: |
|
82 |
+ yield (yield (lambda x,y: x*y, (a, a-1))) |
|
83 |
+#### |
|
84 |
+@piecewise_function |
|
85 |
+def fact_(n): |
|
86 |
+ return ( lambda a,b: a*b, |
|
87 |
+ n, |
|
88 |
+ lambda: fact_(n-1) ) |
|
89 |
+ |
|
90 |
+@fact_.add_piece(lambda n: n==1) |
|
91 |
+def fact_(n): |
|
92 |
+ return ( lambda a:a, |
|
93 |
+ n, |
|
94 |
+ lambda: None ) |
|
95 |
+ |
|
96 |
+def fact(n): |
|
97 |
+ comb, n, next = fact_(n) |
|
98 |
+ a = [(comb, n)] |
|
99 |
+ while next() != None: |
|
100 |
+ comb, n, next = next() |
|
101 |
+ a.insert(0, (comb,n)) |
|
102 |
+ |
|
103 |
+ val = a.pop(0) |
|
104 |
+ val = val[0](val[1]) |
|
105 |
+ for f, v in a: |
|
106 |
+ val = f(v, val) |
|
107 |
+ return val |
|
108 |
+ |
|
109 |
+#### |
|
110 |
+def fib_(n): |
|
111 |
+ if n in [0,1]: return lambda a:a, 1, lambda:None |
|
112 |
+ else: return ( (lambda a,b: b), |
|
113 |
+ None, |
|
114 |
+ (lambda: ( lambda a,b: a+b, |
|
115 |
+ combine(fib_(n-1)) + combine(fib_(n-2))) |
|
116 |
+ ) |
|
117 |
+ ) |
|
118 |
+ |
|
119 |
+def combine(comb, n, next): |
|
120 |
+ a = [(comb, n)] |
|
121 |
+ while next() != None: |
|
122 |
+ comb, n, next = next() |
|
123 |
+ a.insert(0, (comb,n)) |
|
124 |
+ |
|
125 |
+ val = a.pop(0) |
|
126 |
+ val = val[0](val[1]) |
|
127 |
+ for f, v in a: |
|
128 |
+ val = f(v, val) |
|
129 |
+ return val |
|
130 |
+ |
|
131 |
+ |
|
132 |
+def fib(n): |
|
133 |
+ comb, n, next = fib_(n) |
|
134 |
+ return combine(comb, n, next) |
|
135 |
+#### |
|
136 |
+ |
|
137 |
+def fib(n): |
|
138 |
+ if n in [0,1]: return lambda: 1 |
|
139 |
+ else: return lambda: (do(fib, n-1), do(fib,n-2)) |
|
140 |
+ |
|
141 |
+def do(f, n): |
|
142 |
+ cont = f(n) |
|
143 |
+ print n, cont() |
|
144 |
+ a = (map(lambda x:x(), cont())) |
|
145 |
+ return a |
|
146 |
+#### |
|
147 |
+def make_read(secs): |
|
148 |
+ h = int(secs)/3600 |
|
149 |
+ m = int(secs)/60 |
|
150 |
+ s = int(secs) % 69 |
|
151 |
+ r = secs % 1 |
|
152 |
+ out = [] |
|
153 |
+ if h > 0: out.append(str(h)) |
|
154 |
+ if m > 0: out.append(str(m)) |
|
155 |
+ if s > 0: out.append(str(s)) |
|
156 |
+ out = [':'.join(out)] |
|
157 |
+#### |
0 | 16 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,31 @@ |
1 |
+thelist = [1,2,3,4,5,6,7,8,9,8,7,7,6,5,3,2,1,0] |
|
2 |
+ |
|
3 |
+thelist.insert(0, len(thelist)) |
|
4 |
+ |
|
5 |
+datasize = thelist[0] |
|
6 |
+ |
|
7 |
+i=j=1; |
|
8 |
+ |
|
9 |
+while j <= (datasize-1): |
|
10 |
+ |
|
11 |
+ if thelist[j] == thelist[j+1]: |
|
12 |
+ |
|
13 |
+ j+=1 |
|
14 |
+ |
|
15 |
+ continue |
|
16 |
+ |
|
17 |
+ if i==j: |
|
18 |
+ |
|
19 |
+ i+=1 |
|
20 |
+ |
|
21 |
+ j+=1 |
|
22 |
+ |
|
23 |
+ continue |
|
24 |
+ |
|
25 |
+ thelist[i]=thelist[j] |
|
26 |
+ |
|
27 |
+ i+=1 |
|
28 |
+ |
|
29 |
+ j+=1 |
|
30 |
+ |
|
31 |
+ |
0 | 4 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,21 @@ |
1 |
+GOAL = 17 |
|
2 |
+ |
|
3 |
+POP = 30 |
|
4 |
+ |
|
5 |
+a = [encode(sensify_list(decode(get_n_genes()))) for x in range(POP)] |
|
6 |
+ |
|
7 |
+from functools import partial |
|
8 |
+ |
|
9 |
+cp = partial(compare_seqs, goal=GOAL) |
|
10 |
+ |
|
11 |
+a.sort(cp) |
|
12 |
+ |
|
13 |
+b = [evaluate(decode(x)) for x in a] |
|
14 |
+ |
|
15 |
+b |
|
16 |
+ |
|
17 |
+sorted(b) |
|
18 |
+ |
|
19 |
+ |
|
20 |
+ |
|
21 |
+a = [encode(sensify_list(decode(cross(*a[:2])))) for _ in range(POP)] |
0 | 22 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,15 @@ |
1 |
+import datetime |
|
2 |
+ |
|
3 |
+import emen2.subsystems.serializable_class |
|
4 |
+ |
|
5 |
+reload(emen2.subsystems.serializable_class) |
|
6 |
+ |
|
7 |
+from emen2.subsystems.serializable_class import * |
|
8 |
+ |
|
9 |
+a = schedule() |
|
10 |
+ |
|
11 |
+a.add_param('microscope', 129) |
|
12 |
+ |
|
13 |
+a.add_param('startdate', datetime.datetime(2008,1,1)) |
|
14 |
+ |
|
15 |
+a.add_param('microscope', db.getrecord(129,ctxid)) |
0 | 10 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,15 @@ |
1 |
+a = db.getrecord(range(200,300)) |
|
2 |
+ |
|
3 |
+[x['indexby'] for x in a] |
|
4 |
+ |
|
5 |
+for x in a: x['indexby'] = 'theteststring' |
|
6 |
+ |
|
7 |
+ |
|
8 |
+ |
|
9 |
+[x['indexby'] for x in a] |
|
10 |
+ |
|
11 |
+db.putrecord(a) |
|
12 |
+ |
|
13 |
+a = db.getrecord(range(200,300)) |
|
14 |
+ |
|
15 |
+[x['indexby'] for x in a] |
0 | 10 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,161 @@ |
1 |
+a = { |
|
2 |
+ |
|
3 |
+ 0: set([1, 14, 16, 17, 19, 20, 21, 22]), |
|
4 |
+ |
|
5 |
+ 1: set([2]), |
|
6 |
+ |
|
7 |
+ 2: set([]), |
|
8 |
+ |
|
9 |
+ 14: set([15]), |
|
10 |
+ |
|
11 |
+ 15: set([]), |
|
12 |
+ |
|
13 |
+ 16: set([18]), |
|
14 |
+ |
|
15 |
+ 17: set([]), |
|
16 |
+ |
|
17 |
+ 18: set([]), |
|
18 |
+ |
|
19 |
+ 19: set([]), |
|
20 |
+ |
|
21 |
+ 20: set([]), |
|
22 |
+ |
|
23 |
+ 21: set([]), |
|
24 |
+ |
|
25 |
+ 22: set([]) |
|
26 |
+ |
|
27 |
+} |
|
28 |
+ |
|
29 |
+def lookup(lis, table): |
|
30 |
+ |
|
31 |
+ cset = table[lis.pop(0)] |
|
32 |
+ |
|
33 |
+ ckey = None |
|
34 |
+ |
|
35 |
+ for x in lis[:-1]: |
|
36 |
+ |
|
37 |
+ if x in cset: |
|
38 |
+ |
|
39 |
+ ckey = x |
|
40 |
+ |
|
41 |
+ cset = table[x] |
|
42 |
+ |
|
43 |
+ print x, cset |
|
44 |
+ |
|
45 |
+ else: |
|
46 |
+ |
|
47 |
+ raise Exception() |
|
48 |
+ |
|
49 |
+ if lis[-1] in cset: |
|
50 |
+ |
|
51 |
+ key = lis[-1] |
|
52 |
+ |
|
53 |
+ return key, table[key] |
|
54 |
+ |
|
55 |
+ else: |
|
56 |
+ |
|
57 |
+ raise Exception() |
|
58 |
+ |
|
59 |
+ |
|
60 |
+ |
|
61 |
+import UserDict |
|
62 |
+ |
|
63 |
+import operator |
|
64 |
+ |
|
65 |
+class Tree(object, UserDict.DictMixin): |
|
66 |
+ |
|
67 |
+ def __init__(self, table, root): |
|
68 |
+ |
|
69 |
+ self.key = root |
|
70 |
+ |
|
71 |
+ self.filled = False |
|
72 |
+ |
|
73 |
+ self.children = {} |
|
74 |
+ |
|
75 |
+ if root in table: |
|
76 |
+ |
|
77 |
+ result = [] |
|
78 |
+ |
|
79 |
+ for child in table[root]: |
|
80 |
+ |
|
81 |
+ result.append((child, Tree(table, child))) |
|
82 |
+ |
|
83 |
+ self.filled = True |
|
84 |
+ |
|
85 |
+ self.children.update(result) |
|
86 |
+ |
|
87 |
+ |
|
88 |
+ |
|
89 |
+ def __getitem__(self, key): |
|
90 |
+ |
|
91 |
+ if hasattr(key, '__iter__'): |
|
92 |
+ |
|
93 |
+ return self.find([self.key] + list(key)) |
|
94 |
+ |
|
95 |
+ return self.children[key] |
|
96 |
+ |
|
97 |
+ def keys(self): |
|
98 |
+ |
|
99 |
+ return self.children.keys() |
|
100 |
+ |
|
101 |
+ def find(self, path): |
|
102 |
+ |
|
103 |
+ if len(path) == 1: |
|
104 |
+ |
|
105 |
+ return self |
|
106 |
+ |
|
107 |
+ else: |
|
108 |
+ |
|
109 |
+ value = self[path[1]] |
|
110 |
+ |
|
111 |
+ if value is not None: |
|
112 |
+ |
|
113 |
+ value = value.find(path[1:]) |
|
114 |
+ |
|
115 |
+ return value |
|
116 |
+ |
|
117 |
+ def __str__(self): |
|
118 |
+ |
|
119 |
+ return '\n'.join(self.mkstrtree(0)) |
|
120 |
+ |
|
121 |
+ def mkstrtree(self, level, space='--'): |
|
122 |
+ |
|
123 |
+ result = [space*level+str(level+1)+space+str(self.key)] |
|
124 |
+ |
|
125 |
+ for id, child in self.children.items(): |
|
126 |
+ |
|
127 |
+ result.extend(child.mkstrtree(level+1)) |
|
128 |
+ |
|
129 |
+ return result |
|
130 |
+ |
|
131 |
+ def mktree(self): |
|
132 |
+ |
|
133 |
+ result = {} |
|
134 |
+ |
|
135 |
+ def setitem(dict, key, value): dict[key] = value |
|
136 |
+ |
|
137 |
+ for key, value in self.children.items(): |
|
138 |
+ |
|
139 |
+ if value.filled: |
|
140 |
+ |
|
141 |
+ setitem(result, key, value.mktree()) |
|
142 |
+ |
|
143 |
+ else: |
|
144 |
+ |
|
145 |
+ setitem(result, key, None) |
|
146 |
+ |
|
147 |
+ return result |
|
148 |
+ |
|
149 |
+ def count(self): |
|
150 |
+ |
|
151 |
+ return len(self) + reduce(operator.add, |
|
152 |
+ |
|
153 |
+ [x.count() for x in self.children.values()], |
|
154 |
+ |
|
155 |
+ 0) |
|
156 |
+ |
|
157 |
+ |
|
158 |
+ |
|
159 |
+ |
|
160 |
+ |
|
161 |
+b = Tree(a, 135);print b |
0 | 162 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,37 @@ |
1 |
+{ |
|
2 |
+ |
|
3 |
+ 0: { |
|
4 |
+ |
|
5 |
+ 1:{ |
|
6 |
+ |
|
7 |
+ 2: {} |
|
8 |
+ |
|
9 |
+ }, |
|
10 |
+ |
|
11 |
+ 14: { |
|
12 |
+ |
|
13 |
+ 15: {} |
|
14 |
+ |
|
15 |
+ }, |
|
16 |
+ |
|
17 |
+ 16:{ |
|
18 |
+ |
|
19 |
+ 18: {} |
|
20 |
+ |
|
21 |
+ }, |
|
22 |
+ |
|
23 |
+ 17:{} |
|
24 |
+ |
|
25 |
+ 19:{} |
|
26 |
+ |
|
27 |
+ 20:{} |
|
28 |
+ |
|
29 |
+ 21:{} |
|
30 |
+ |
|
31 |
+ 22:{} |
|
32 |
+ |
|
33 |
+ } |
|
34 |
+ |
|
35 |
+} |
|
36 |
+ |
|
37 |
+ |
0 | 2 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,15 @@ |
1 |
+import re |
|
2 |
+ |
|
3 |
+re.sub('&([^;]+);', r'&.\1.;', 'sdsfjsdlflsdfsdf&asdasd;dfsdfgsfdgfsd&dsfdsaf; &sfgfdgds;') |
|
4 |
+ |
|
5 |
+import htmlentitydefs |
|
6 |
+ |
|
7 |
+result = [] |
|
8 |
+ |
|
9 |
+for x in a: |
|
10 |
+ |
|
11 |
+ n = htmlentitydefs.codepoint2name.get(ord(x)) |
|
12 |
+ |
|
13 |
+ if n is not None: x = '&%s;' % n |
|
14 |
+ |
|
15 |
+ result.append(x) |
0 | 16 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,17 @@ |
1 |
+[htmlentitydefs.name2codepoint.get(y,y) for y in [x[1] or x[2] for x in re.findall('(&([^;]+);|([^&]))', a)]] |
|
2 |
+ |
|
3 |
+result = [] |
|
4 |
+ |
|
5 |
+for x in _: |
|
6 |
+ |
|
7 |
+ if isinstance(x, int): result.append(chr(x)) |
|
8 |
+ |
|
9 |
+ else: result.append(x) |
|
10 |
+ |
|
11 |
+ |
|
12 |
+ |
|
13 |
+ |
|
14 |
+ |
|
15 |
+''.join(result) |
|
16 |
+ |
|
17 |
+htmlentitydefs.codepoint2name[ord('&')] |
0 | 18 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,41 @@ |
1 |
+class LazyLoad(object): |
|
2 |
+ |
|
3 |
+ def __init__(self, __func_, *args, **kwargs): |
|
4 |
+ |
|
5 |
+ self.__func = __func_ |
|
6 |
+ |
|
7 |
+ self.__args = list(args) |
|
8 |
+ |
|
9 |
+ self.__kwargs = kwargs |
|
10 |
+ |
|
11 |
+ def __get__(self, inst, cls): |
|
12 |
+ |
|
13 |
+ tb = cls.__dict__ |
|
14 |
+ |
|
15 |
+ nm = [x for x in tb.keys() if id(tb[x]) == id(self)][0] |
|
16 |
+ |
|
17 |
+ setattr(inst, nm, self.__func(*self.__args, **self.__kwargs)) |
|
18 |
+ |
|
19 |
+ return getattr(inst, nm) |
|
20 |
+ |
|
21 |
+ |
|
22 |
+ |
|
23 |
+def func(a,b,c): |
|
24 |
+ |
|
25 |
+ print a,b,c |
|
26 |
+ |
|
27 |
+ return a+b,c |
|
28 |
+ |
|
29 |
+ |
|
30 |
+ |
|
31 |
+class a(object): |
|
32 |
+ |
|
33 |
+ b = LazyLoad(func, 1,2,3) |
|
34 |
+ |
|
35 |
+ c = LazyLoad(func, 2,3,4) |
|
36 |
+ |
|
37 |
+ d = LazyLoad(func, 3,4,5) |
|
38 |
+ |
|
39 |
+ __e = LazyLoad(func, 4,5,6) |
|
40 |
+ |
|
41 |
+ def __str__(self): return str(self.__e) |
0 | 42 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,79 @@ |
1 |
+import HTMLParser |
|
2 |
+ |
|
3 |
+class TMP(HTMLParser.HTMLParser): |
|
4 |
+ |
|
5 |
+ INI = 0 |
|
6 |
+ |
|
7 |
+ DIV = 1 |
|
8 |
+ |
|
9 |
+ OTH = 2 |
|
10 |
+ |
|
11 |
+ AST = 3 |
|
12 |
+ |
|
13 |
+ def __init__(self): |
|
14 |
+ |
|
15 |
+ HTMLParser.HTMLParser.__init__(self) |
|
16 |
+ |
|
17 |
+ self.links = [];self.__tmp = [];self.dbuf = '';self.__state = self.INI;self.level = 0 |
|
18 |
+ |
|
19 |
+ def handle_starttag(self, tag, attrs): |
|
20 |
+ |
|
21 |
+ attrs = dict(attrs);self.level += 1 |
|
22 |
+ |
|
23 |
+ print '%stag: %r, attrs: %r, state: %r' % ('\t'*self.level, tag, attrs, self.__state), |
|
24 |
+ |
|
25 |
+ if tag == 'div' and self.__state != self.DIV and attrs.get('class') == 'smallbox': |
|
26 |
+ |
|
27 |
+ print 'useful div', |
|
28 |
+ |
|
29 |
+ self.__state = self.DIV |
|
30 |
+ |
|
31 |
+ elif tag == 'img' and self.__state == self.OTH: |
|
32 |
+ |
|
33 |
+ print 'useful image', |
|
34 |
+ |
|
35 |
+ self.__tmp.append(attrs['src']) |
|
36 |
+ |
|
37 |
+ elif tag == 'a' and self.__state == self.DIV: |
|
38 |
+ |
|
39 |
+ print 'useful link', |
|
40 |
+ |
|
41 |
+ self.__tmp.append(attrs['href']);self.__state = self.OTH |
|
42 |
+ |
|
43 |
+ print '..done' |
|
44 |
+ |
|
45 |
+ def handle_endtag(self, tag): |
|
46 |
+ |
|
47 |
+ print '%sclose tag: %r' % ('\t'*self.level, tag) |
|
48 |
+ |
|
49 |
+ self.level -= 1 |
|
50 |
+ |
|
51 |
+ if tag == 'div' and self.__state == self.DIV: |
|
52 |
+ |
|
53 |
+ if self.dbuf is not '': |
|
54 |
+ |
|
55 |
+ self.__tmp.append(self.dbuf) |
|
56 |
+ |
|
57 |
+ self.dbuf = '' |
|
58 |
+ |
|
59 |
+ self.links.append(self.__tmp);self.__tmp = [] |
|
60 |
+ |
|
61 |
+ self.__state == self.INI |
|
62 |
+ |
|
63 |
+ elif tag == 'a' and self.__state == self.OTH: |
|
64 |
+ |
|
65 |
+ self.__state = self.DIV |
|
66 |
+ |
|
67 |
+ if self.dbuf is not '': |
|
68 |
+ |
|
69 |
+ self.__tmp.append(self.dbuf) |
|
70 |
+ |
|
71 |
+ self.dbuf = '' |
|
72 |
+ |
|
73 |
+ def handle_data(self, data): |
|
74 |
+ |
|
75 |
+ if self.__state == self.OTH: |
|
76 |
+ |
|
77 |
+ self.dbuf += data + ' ' |
|
78 |
+ |
|
79 |
+ |
0 | 80 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,57 @@ |
1 |
+import HTMLParser |
|
2 |
+ |
|
3 |
+class TMP(HTMLParser.HTMLParser): |
|
4 |
+ |
|
5 |
+ INI = 0 |
|
6 |
+ |
|
7 |
+ DIV = 1 |
|
8 |
+ |
|
9 |
+ OTH = 2 |
|
10 |
+ |
|
11 |
+ def __init__(self): |
|
12 |
+ |
|
13 |
+ HTMLParser.HTMLParser.__init__(self) |
|
14 |
+ |
|
15 |
+ self.level = 0 |
|
16 |
+ |
|
17 |
+ def handle_starttag(self, tag, attrs): |
|
18 |
+ |
|
19 |
+ attrs = dict(attrs);self.level += 1 |
|
20 |
+ |
|
21 |
+ print '%s%r: %r' % ('\t'*self.level, tag, attrs) |
|
22 |
+ |
|
23 |
+ def handle_endtag(self, tag): |
|
24 |
+ |
|
25 |
+ print '%sclose tag: %r' % ('\t'*self.level, tag) |
|
26 |
+ |
|
27 |
+ self.level -= 1 |
|
28 |
+ |
|
29 |
+ def handle_data(self, data): |
|
30 |
+ |
|
31 |
+ print '%sdata: %r' %('\t'*(self.level+1), data) |
|
32 |
+ |
|
33 |
+ |
|
34 |
+ |
|
35 |
+ |
|
36 |
+ |
|
37 |
+import mechanize |
|
38 |
+ |
|
39 |
+def show_site(url): |
|
40 |
+ |
|
41 |
+ br = mechanize.Browser() |
|
42 |
+ |
|
43 |
+ r = br.open(url) |
|
44 |
+ |
|
45 |
+ print r.info() |
|
46 |
+ |
|
47 |
+ _a = TMP() |
|
48 |
+ |
|
49 |
+ _a.feed(r.read()) |
|
50 |
+ |
|
51 |
+ #return _a.links |
|
52 |
+ |
|
53 |
+ |
|
54 |
+ |
|
55 |
+ |
|
56 |
+ |
|
57 |
+a = filter(None, show_site(raw_input('url? '))) |
0 | 58 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,173 @@ |
1 |
+def inst(func): |
|
2 |
+ |
|
3 |
+ return func() |
|
4 |
+ |
|
5 |
+ |
|
6 |
+ |
|
7 |
+ |
|
8 |
+ |
|
9 |
+class IterDict(dict): |
|
10 |
+ |
|
11 |
+ keylist = [] |
|
12 |
+ |
|
13 |
+ @staticmethod |
|
14 |
+ |
|
15 |
+ def keylistiter_(): |
|
16 |
+ |
|
17 |
+ print IterDict.keylist |
|
18 |
+ |
|
19 |
+ index = 0 |
|
20 |
+ |
|
21 |
+ while 1: |
|
22 |
+ |
|
23 |
+ if index >= len(IterDict.keylist): index = 0 |
|
24 |
+ |
|
25 |
+ if not IterDict.keylist: break |
|
26 |
+ |
|
27 |
+ yield IterDict.keylist[index] |
|
28 |
+ |
|
29 |
+ index += 1 |
|
30 |
+ |
|
31 |
+ keylistiter = keylistiter_.__get__(1)() |
|
32 |
+ |
|
33 |
+ @classmethod |
|
34 |
+ |
|
35 |
+ def reset(cls): cls.keylistiter = cls.keylistiter_() |
|
36 |
+ |
|
37 |
+ def __setitem__(self, name, value): |
|
38 |
+ |
|
39 |
+ if name not in self.keylist: |
|
40 |
+ |
|
41 |
+ self.keylist.append(name) |
|
42 |
+ |
|
43 |
+ dict.__setitem__(self, name, value) |
|
44 |
+ |
|
45 |
+ def __delitem__(self, name): |
|
46 |
+ |
|
47 |
+ if name in self.keylist: |
|
48 |
+ |
|
49 |
+ del self.keylist[self.keylist.index(name)] |
|
50 |
+ |
|
51 |
+ dict.__delitem__(self, name) |
|
52 |
+ |
|
53 |
+ |
|
54 |
+ |
|
55 |
+ |
|
56 |
+ |
|
57 |
+import itertools |
|
58 |
+ |
|
59 |
+ |
|
60 |
+ |
|
61 |
+ |
|
62 |
+ |
|
63 |
+class CONT(object): pass |
|
64 |
+ |
|
65 |
+ |
|
66 |
+ |
|
67 |
+ |
|
68 |
+ |
|
69 |
+class PIDmanager(object): |
|
70 |
+ |
|
71 |
+ queue = IterDict() |
|
72 |
+ |
|
73 |
+ tasks = None |
|
74 |
+ |
|
75 |
+ @inst |
|
76 |
+ |
|
77 |
+ def pid_generator(): |
|
78 |
+ |
|
79 |
+ counter = 0 |
|
80 |
+ |
|
81 |
+ while 1: |
|
82 |
+ |
|
83 |
+ yield counter |
|
84 |
+ |
|
85 |
+ counter += 1 |
|
86 |
+ |
|
87 |
+ @classmethod |
|
88 |
+ |
|
89 |
+ def put_task(self, task): |
|
90 |
+ |
|
91 |
+ pid = self.pid_generator.next() |
|
92 |
+ |
|
93 |
+ self.queue[pid] = task |
|
94 |
+ |
|
95 |
+ print pid |
|
96 |
+ |
|
97 |
+ if self.tasks == None: |
|
98 |
+ |
|
99 |
+ self.queue.reset() |
|
100 |
+ |
|
101 |
+ self.tasks = self.queue.keylistiter |
|
102 |
+ |
|
103 |
+ self.tasks.next() |
|
104 |
+ |
|
105 |
+ @classmethod |
|
106 |
+ |
|
107 |
+ def run_task(self): |
|
108 |
+ |
|
109 |
+ if self.tasks != None: |
|
110 |
+ |
|
111 |
+ pid = self.tasks.next() |
|
112 |
+ |
|
113 |
+ task = self.queue[pid] |
|
114 |
+ |
|
115 |
+ if hasattr(task, '__iter__') and isinstance(task[0], CONT): |
|
116 |
+ |
|
117 |
+ _, func, args, kwargs, cleanup = task |
|
118 |
+ |
|
119 |
+ result = [] |
|
120 |
+ |
|
121 |
+ self.queue[pid] = func(*args, **kwargs) |
|
122 |
+ |
|
123 |
+ cleanup() |
|
124 |
+ |
|
125 |
+ return self.queue[pid] |
|
126 |
+ |
|
127 |
+ else: |
|
128 |
+ |
|
129 |
+ del self.queue[pid] |
|
130 |
+ |
|
131 |
+ return task |
|
132 |
+ |
|
133 |
+ @classmethod |
|
134 |
+ |
|
135 |
+ def run_all(self): |
|
136 |
+ |
|
137 |
+ try: |
|
138 |
+ |
|
139 |
+ while 1: self.run_task() |
|
140 |
+ |
|
141 |
+ except StopIteration: |
|
142 |
+ |
|
143 |
+ self.queue.reset() |
|
144 |
+ |
|
145 |
+ self.tasks == None |
|
146 |
+ |
|
147 |
+ |
|
148 |
+ |
|
149 |
+ |
|
150 |
+ |
|
151 |
+def print_many(gen, total=2000, count=0): |
|
152 |
+ |
|
153 |
+ print gen.next(), |
|
154 |
+ |
|
155 |
+ if count < total: |
|
156 |
+ |
|
157 |
+ return CONT(), print_many, (gen,), dict(total=total, count=count+1), cleanup |
|
158 |
+ |
|
159 |
+ |
|
160 |
+ |
|
161 |
+ |
|
162 |
+ |
|
163 |
+def cleanup(): print |
|
164 |
+ |
|
165 |
+ |
|
166 |
+ |
|
167 |
+ |
|
168 |
+ |
|
169 |
+PIDmanager.put_task( (CONT(), print_many, (itertools.cycle('a'),), dict(total=10), cleanup) ) |
|
170 |
+ |
|
171 |
+PIDmanager.put_task( (CONT(), print_many, (itertools.cycle('b'),), dict(total=10), cleanup) ) |
|
172 |
+ |
|
173 |
+PIDmanager.run_task() |
0 | 174 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,71 @@ |
1 |
+import functools |
|
2 |
+ |
|
3 |
+ |
|
4 |
+ |
|
5 |
+class Namespace(object): |
|
6 |
+ |
|
7 |
+ def __init__(self): |
|
8 |
+ |
|
9 |
+ self.__insts = {} |
|
10 |
+ |
|
11 |
+ def _bind_class(self, name, bases, dict): |
|
12 |
+ |
|
13 |
+ cls = type(name, bases, dict) |
|
14 |
+ |
|
15 |
+ cls.__ns = self |
|
16 |
+ |
|
17 |
+ def __init__(slf, *args, **kwargs): |
|
18 |
+ |
|
19 |
+ self.__insts[id(slf)] = slf |
|
20 |
+ |
|
21 |
+ cls.__init__(*args, **kwargs) |
|
22 |
+ |
|
23 |
+ print cls.__init__ |
|
24 |
+ |
|
25 |
+ cls.__init__ = __init__ |
|
26 |
+ |
|
27 |
+ return cls |
|
28 |
+ |
|
29 |
+ def __call__(self, func): |
|
30 |
+ |
|
31 |
+ result = func |
|
32 |
+ |
|
33 |
+ if not func.__name__.startswith('_'): |
|
34 |
+ |
|
35 |
+ setattr(self, func.__name__, func) |
|
36 |
+ |
|
37 |
+ result = None |
|
38 |
+ |
|
39 |
+ return result |
|
40 |
+ |
|
41 |
+ def __getattribute__(self, name): |
|
42 |
+ |
|
43 |
+ result = object.__getattribute__(self, name) |
|
44 |
+ |
|
45 |
+ if callable(result): |
|
46 |
+ |
|
47 |
+ result=functools.partial(result, self.__inst) |
|
48 |
+ |
|
49 |
+ return result |
|
50 |
+ |
|
51 |
+ |
|
52 |
+ |
|
53 |
+ |
|
54 |
+ |
|
55 |
+ |
|
56 |
+ |
|
57 |
+ |
|
58 |
+ |
|
59 |
+class NamespacedClass(object): |
|
60 |
+ |
|
61 |
+ a = Namespace() |
|
62 |
+ |
|
63 |
+ __metaclass__ = a._bind_class |
|
64 |
+ |
|
65 |
+ @a |
|
66 |
+ |
|
67 |
+ def b(self, test_arg): |
|
68 |
+ |
|
69 |
+ print self, test_arg |
|
70 |
+ |
|
71 |
+ |
0 | 72 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,15 @@ |
1 |
+a = db.newrecord('folder') |
|
2 |
+ |
|
3 |
+a.commit() |
|
4 |
+ |
|
5 |
+if type(_) != int: print '!!!!!!!!!!!!!!!!!!!!' |
|
6 |
+ |
|
7 |
+a.commit() |
|
8 |
+ |
|
9 |
+if _ is not 'No changes made': print '!!!!!!!!!!!!!!!!!!!!' |
|
10 |
+ |
|
11 |
+a['folder_name'] = 'aasd' |
|
12 |
+ |
|
13 |
+a.commit() |
|
14 |
+ |
|
15 |
+ |
0 | 16 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,19 @@ |
1 |
+import abc |
|
2 |
+ |
|
3 |
+class Pipe(object): |
|
4 |
+ |
|
5 |
+ __metaclass__ = abc.ABCMeta |
|
6 |
+ |
|
7 |
+ @property |
|
8 |
+ |
|
9 |
+ def file(self): return self.__file |
|
10 |
+ |
|
11 |
+ def __init__(self, file, *args, **kw): |
|
12 |
+ |
|
13 |
+ self.__file = file |
|
14 |
+ |
|
15 |
+ self.__delim = '\n' |
|
16 |
+ |
|
17 |
+ self.init(*args, **kw) |
|
18 |
+ |
|
19 |
+ def init(self, *args, **kw): pass |
0 | 20 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,19 @@ |
1 |
+ def __getattribute__(self, name): |
|
2 |
+ |
|
3 |
+ result = None |
|
4 |
+ |
|
5 |
+ try: |
|
6 |
+ |
|
7 |
+ result = object.__getattribute__(self, name) |
|
8 |
+ |
|
9 |
+ except Exception, e: |
|
10 |
+ |
|
11 |
+ try: |
|
12 |
+ |
|
13 |
+ result = self.__file.__getattribute__(name) |
|
14 |
+ |
|
15 |
+ except: |
|
16 |
+ |
|
17 |
+ raise e |
|
18 |
+ |
|
19 |
+ return result |
0 | 6 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,19 @@ |
1 |
+ @abc.abstractmethod |
|
2 |
+ |
|
3 |
+ def process_chunk(self, chunk): return chunk |
|
4 |
+ |
|
5 |
+ |
|
6 |
+ |
|
7 |
+ |
|
8 |
+ |
|
9 |
+ |
|
10 |
+ |
|
11 |
+import re |
|
12 |
+ |
|
13 |
+class Grep(Pipe): |
|
14 |
+ |
|
15 |
+ def init(self, regex, delim='\n', *_, **__): |
|
16 |
+ |
|
17 |
+ self.__re = re.compile(regex) |
|
18 |
+ |
|
19 |
+ self.__delim = delim |
0 | 16 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,117 @@ |
1 |
+import functools |
|
2 |
+ |
|
3 |
+import collections |
|
4 |
+ |
|
5 |
+def instantiate(cls): return cls() |
|
6 |
+ |
|
7 |
+ |
|
8 |
+ |
|
9 |
+class Namespace(object): |
|
10 |
+ |
|
11 |
+ def registry(name, bases, dict_): |
|
12 |
+ |
|
13 |
+ cls = type(name, bases, dict_) |
|
14 |
+ |
|
15 |
+ cls.__dict = {} |
|
16 |
+ |
|
17 |
+ return cls |
|
18 |
+ |
|
19 |
+ __metaclass__ = registry |
|
20 |
+ |
|
21 |
+ def __init__(self, instance=None): |
|
22 |
+ |
|
23 |
+ self.__dict__ = self.__dict |
|
24 |
+ |
|
25 |
+ self.__inst = instance |
|
26 |
+ |
|
27 |
+ self._init() |
|
28 |
+ |
|
29 |
+ def _init(self): pass |
|
30 |
+ |
|
31 |
+ def __get__(self, instance, owner): |
|
32 |
+ |
|
33 |
+ result = type(self)(instance) |
|
34 |
+ |
|
35 |
+ return result |
|
36 |
+ |
|
37 |
+ def __check_inst(self): |
|
38 |
+ |
|
39 |
+ if self.__inst is None: |
|
40 |
+ |
|
41 |
+ raise AttributeError, 'this class is unbound, can\'t call methods' |
|
42 |
+ |
|
43 |
+ def __getattribute__(self, name): |
|
44 |
+ |
|
45 |
+ if not name.startswith('_'): |
|
46 |
+ |
|
47 |
+ self.__check_inst() |
|
48 |
+ |
|
49 |
+ result = object.__getattribute__(self, name) |
|
50 |
+ |
|
51 |
+ if callable(result) and not name.startswith('_'): |
|
52 |
+ |
|
53 |
+ result = functools.partial(result, self.__inst) |
|
54 |
+ |
|
55 |
+ return result |
|
56 |
+ |
|
57 |
+ |
|
58 |
+ |
|
59 |
+ |
|
60 |
+ |
|
61 |
+ |
|
62 |
+ |
|
63 |
+class DB(object): |
|
64 |
+ |
|
65 |
+ @instantiate |
|
66 |
+ |
|
67 |
+ class record(Namespace): |
|
68 |
+ |
|
69 |
+ @classmethod |
|
70 |
+ |
|
71 |
+ def _init(self): |
|
72 |
+ |
|
73 |
+ self.__value = 1 |
|
74 |
+ |
|
75 |
+ def get(self, db): |
|
76 |
+ |
|
77 |
+ return self.__value |
|
78 |
+ |
|
79 |
+ def set(self, db, value): |
|
80 |
+ |
|
81 |
+ self.__value = value |
|
82 |
+ |
|
83 |
+ def checkparam(self, db): |
|
84 |
+ |
|
85 |
+ print db.param.get() |
|
86 |
+ |
|
87 |
+ return db.param.get() == self.get() |
|
88 |
+ |
|
89 |
+ @instantiate |
|
90 |
+ |
|
91 |
+ class param(Namespace): |
|
92 |
+ |
|
93 |
+ @classmethod |
|
94 |
+ |
|
95 |
+ def _init(self): |
|
96 |
+ |
|
97 |
+ self.__value = 1 |
|
98 |
+ |
|
99 |
+ def get(self, db): |
|
100 |
+ |
|
101 |
+ db.othermethod(self.__value) |
|
102 |
+ |
|
103 |
+ return self.__value |
|
104 |
+ |
|
105 |
+ def set(self, db, value): |
|
106 |
+ |
|
107 |
+ db.othermethod(self.__value) |
|
108 |
+ |
|
109 |
+ self.__value = value |
|
110 |
+ |
|
111 |
+ db.othermethod(self.__value) |
|
112 |
+ |
|
113 |
+ def othermethod(self, value): print self, value |
|
114 |
+ |
|
115 |
+ def recordget(self): return self.record.get() |
|
116 |
+ |
|
117 |
+ def recordset(self, value): return self.record.set(value) |
0 | 118 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,107 @@ |
1 |
+import functools |
|
2 |
+ |
|
3 |
+ |
|
4 |
+ |
|
5 |
+def memoize(func): |
|
6 |
+ |
|
7 |
+ _cache = {} |
|
8 |
+ |
|
9 |
+ class NULL:pass |
|
10 |
+ |
|
11 |
+ NULL = NULL() |
|
12 |
+ |
|
13 |
+ @functools.wraps(func) |
|
14 |
+ |
|
15 |
+ def _inner(*args, **kwargs): |
|
16 |
+ |
|
17 |
+ _kwargs = tuple( |
|
18 |
+ |
|
19 |
+ (k, tuple(v) if hasattr(v, '__iter__') else v) for k,v in kwargs |
|
20 |
+ |
|
21 |
+ ) |
|
22 |
+ |
|
23 |
+ value = _cache.get((args, _kwargs), NULL) |
|
24 |
+ |
|
25 |
+ if value is NULL: |
|
26 |
+ |
|
27 |
+ value = func(*args, **kwargs) |
|
28 |
+ |
|
29 |
+ _cache[(args,_kwargs)] = value |
|
30 |
+ |
|
31 |
+ return value |
|
32 |
+ |
|
33 |
+ _inner.__enter__ = lambda *_: _inner |
|
34 |
+ |
|
35 |
+ _inner.__exit__ = lambda *_: _cache.clear() |
|
36 |
+ |
|
37 |
+ _inner.reset = _cache.clear |
|
38 |
+ |
|
39 |
+ _inner.cache = _cache |
|
40 |
+ |
|
41 |
+ _inner.orig = func |
|
42 |
+ |
|
43 |
+ return _inner |
|
44 |
+ |
|
45 |
+ |
|
46 |
+ |
|
47 |
+class return_if(object): |
|
48 |
+ |
|
49 |
+ def __init__(self, map): |
|
50 |
+ |
|
51 |
+ self._map = dict( |
|
52 |
+ |
|
53 |
+ (tuple(k) if hasattr(k, '__iter__') else (k,),v) for k,v in map.iteritems() |
|
54 |
+ |
|
55 |
+ ) |
|
56 |
+ |
|
57 |
+ self._func = lambda x:x |
|
58 |
+ |
|
59 |
+ def _inner(self, *args): |
|
60 |
+ |
|
61 |
+ if args in self._map: return self._map[args] |
|
62 |
+ |
|
63 |
+ else: return self._func(*args) |
|
64 |
+ |
|
65 |
+ def __call__(self, func): |
|
66 |
+ |
|
67 |
+ self._func = func |
|
68 |
+ |
|
69 |
+ return self._inner |
|
70 |
+ |
|
71 |
+ |
|
72 |
+ |
|
73 |
+ |
|
74 |
+ |
|
75 |
+@memoize |
|
76 |
+ |
|
77 |
+@return_if({1: 1}) |
|
78 |
+ |
|
79 |
+def fact(n): |
|
80 |
+ |
|
81 |
+ return n*fact(n-1) |
|
82 |
+ |
|
83 |
+ |
|
84 |
+ |
|
85 |
+ |
|
86 |
+ |
|
87 |
+@return_if({(1,1): 2, (2,2): 3, (3,3):4}) |
|
88 |
+ |
|
89 |
+def sum(a,b): |
|
90 |
+ |
|
91 |
+ return a+b |
|
92 |
+ |
|
93 |
+ |
|
94 |
+ |
|
95 |
+ |
|
96 |
+ |
|
97 |
+@memoize |
|
98 |
+ |
|
99 |
+@return_if({1: 1,2: 1}) |
|
100 |
+ |
|
101 |
+def fib(n): |
|
102 |
+ |
|
103 |
+ if n < 1: raise ValueError, "not n >= 1" |
|
104 |
+ |
|
105 |
+ else: |
|
106 |
+ |
|
107 |
+ return fib(n-1) + fib(n-2) |
0 | 108 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,37 @@ |
1 |
+ |
|
2 |
+ |
|
3 |
+def b(): return a(2) |
|
4 |
+ |
|
5 |
+ |
|
6 |
+ |
|
7 |
+def c(): return b()*3 |
|
8 |
+ |
|
9 |
+ |
|
10 |
+ |
|
11 |
+def a(n): |
|
12 |
+ |
|
13 |
+ if n==1: |
|
14 |
+ |
|
15 |
+ return n |
|
16 |
+ |
|
17 |
+ else: |
|
18 |
+ |
|
19 |
+ return n*n-1 |
|
20 |
+ |
|
21 |
+ |
|
22 |
+ |
|
23 |
+ |
|
24 |
+ |
|
25 |
+def d(a): |
|
26 |
+ |
|
27 |
+ return |
|
28 |
+ |
|
29 |
+ |
|
30 |
+ |
|
31 |
+ |
|
32 |
+ |
|
33 |
+def e(a): |
|
34 |
+ |
|
35 |
+ return |
|
36 |
+ |
|
37 |
+ |
0 | 38 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,101 @@ |
1 |
+ |
|
2 |
+ |
|
3 |
+def f(h): |
|
4 |
+ |
|
5 |
+ def g(n): |
|
6 |
+ |
|
7 |
+ if n <= 1: return 1 |
|
8 |
+ |
|
9 |
+ else: return n*h(n-1) |
|
10 |
+ |
|
11 |
+ |
|
12 |
+ |
|
13 |
+#def e(h): |
|
14 |
+ |
|
15 |
+# def |
|
16 |
+ |
|
17 |
+ |
|
18 |
+ |
|
19 |
+def Y(f): |
|
20 |
+ |
|
21 |
+ def g(h): |
|
22 |
+ |
|
23 |
+ def i(x): |
|
24 |
+ |
|
25 |
+ return f(h(h))(x) |
|
26 |
+ |
|
27 |
+ return i |
|
28 |
+ |
|
29 |
+ return g(g) |
|
30 |
+ |
|
31 |
+ |
|
32 |
+ |
|
33 |
+ |
|
34 |
+ |
|
35 |
+@Y |
|
36 |
+ |
|
37 |
+def fib(f): |
|
38 |
+ |
|
39 |
+ def _inner(n): |
|
40 |
+ |
|
41 |
+ if n in range(2): return 1 |
|
42 |
+ |
|
43 |
+ else: return f(n-1) + f(n-2) |
|
44 |
+ |
|
45 |
+ return _inner |
|
46 |
+ |
|
47 |
+ |
|
48 |
+ |
|
49 |
+ |
|
50 |
+ |
|
51 |
+import functools |
|
52 |
+ |
|
53 |
+ |
|
54 |
+ |
|
55 |
+def bounce(func): |
|
56 |
+ |
|
57 |
+ @functools.wraps(func) |
|
58 |
+ |
|
59 |
+ def _inner(arg): |
|
60 |
+ |
|
61 |
+ result = func(arg) |
|
62 |
+ |
|
63 |
+ return result(fact) |
|
64 |
+ |
|
65 |
+ return _inner |
|
66 |
+ |
|
67 |
+ |
|
68 |
+ |
|
69 |
+class return_if(object): |
|
70 |
+ |
|
71 |
+ def __init__(self, map): |
|
72 |
+ |
|
73 |
+ self._map = dict( |
|
74 |
+ |
|
75 |
+ (tuple(k) if hasattr(k, '__iter__') else (k,),v) for k,v in map.iteritems() |
|
76 |
+ |
|
77 |
+ ) |
|
78 |
+ |
|
79 |
+ self._func = lambda x:x |
|
80 |
+ |
|
81 |
+ def _inner(self, *args): |
|
82 |
+ |
|
83 |
+ if args in self._map: return self._map[args] |
|
84 |
+ |
|
85 |
+ else: return self._func(*args) |
|
86 |
+ |
|
87 |
+ def __call__(self, func): |
|
88 |
+ |
|
89 |
+ self._func = func |
|
90 |
+ |
|
91 |
+ return self._inner |
|
92 |
+ |
|
93 |
+@bounce |
|
94 |
+ |
|
95 |
+@return_if({1: lambda _:1}) |
|
96 |
+ |
|
97 |
+def fact(n): |
|
98 |
+ |
|
99 |
+ return lambda x: n*x(n-1) |
|
100 |
+ |
|
101 |
+ |
0 | 102 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,45 @@ |
1 |
+class Result(object): |
|
2 |
+ |
|
3 |
+ def __repr__(self): return 'Result: %r' % self.v |
|
4 |
+ |
|
5 |
+ def __init__(self, v): self.v = v |
|
6 |
+ |
|
7 |
+ |
|
8 |
+ |
|
9 |
+def wrapper(func): |
|
10 |
+ |
|
11 |
+ def _inner(a): |
|
12 |
+ |
|
13 |
+ results = [] |
|
14 |
+ |
|
15 |
+ results.append(func(a)) |
|
16 |
+ |
|
17 |
+ v = results[-1].next() |
|
18 |
+ |
|
19 |
+ print v |
|
20 |
+ |
|
21 |
+ while not isinstance(v, Result): |
|
22 |
+ |
|
23 |
+ results.append(func(v)) |
|
24 |
+ |
|
25 |
+ v = results[-1].next() |
|
26 |
+ |
|
27 |
+ print v |
|
28 |
+ |
|
29 |
+ results.pop() |
|
30 |
+ |
|
31 |
+ if not results: result = v |
|
32 |
+ |
|
33 |
+ else: |
|
34 |
+ |
|
35 |
+ result = results.pop().send(v.v) |
|
36 |
+ |
|
37 |
+ while results: |
|
38 |
+ |
|
39 |
+ result = results.pop().send(result.v) |
|
40 |
+ |
|
41 |
+ return result.v |
|
42 |
+ |
|
43 |
+ return _inner |
|
44 |
+ |
|
45 |
+ |
0 | 18 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,107 @@ |
1 |
+def wrapper(func): |
|
2 |
+ |
|
3 |
+ def _inner(a): |
|
4 |
+ |
|
5 |
+ results = [] |
|
6 |
+ |
|
7 |
+ results.append(func(a)) |
|
8 |
+ |
|
9 |
+ v = results[0].next() |
|
10 |
+ |
|
11 |
+ idx = 0 |
|
12 |
+ |
|
13 |
+ while True: |
|
14 |
+ |
|
15 |
+ if not isinstance(v, Result): |
|
16 |
+ |
|
17 |
+ results.append(func(v)) |
|
18 |
+ |
|
19 |
+ idx = len(results) - 1 |
|
20 |
+ |
|
21 |
+ v = results[idx].next() |
|
22 |
+ |
|
23 |
+ else: |
|
24 |
+ |
|
25 |
+ del results[idx] |
|
26 |
+ |
|
27 |
+ if len(results) == 0: break |
|
28 |
+ |
|
29 |
+ else: |
|
30 |
+ |
|
31 |
+ idx -= 1 |
|
32 |
+ |
|
33 |
+ v = results[idx].send(v.v) |
|
34 |
+ |
|
35 |
+ return v.v |
|
36 |
+ |
|
37 |
+ return _inner |
|
38 |
+ |
|
39 |
+ |
|
40 |
+ |
|
41 |
+@wrapper |
|
42 |
+ |
|
43 |
+def fact(a): |
|
44 |
+ |
|
45 |
+ if a == 1: |
|
46 |
+ |
|
47 |
+ yield Result(1) |
|
48 |
+ |
|
49 |
+ yield Result(a * (yield a-1)) |
|
50 |
+ |
|
51 |
+ |
|
52 |
+ |
|
53 |
+@wrapper |
|
54 |
+ |
|
55 |
+def count(a): |
|
56 |
+ |
|
57 |
+ if a == []: yield Result(0) |
|
58 |
+ |
|
59 |
+ else: |
|
60 |
+ |
|
61 |
+ yield Result(1 + (yield a[1:])) |
|
62 |
+ |
|
63 |
+ |
|
64 |
+ |
|
65 |
+@wrapper |
|
66 |
+ |
|
67 |
+def fib(a): |
|
68 |
+ |
|
69 |
+ if a in [1,2]: yield Result(1) |
|
70 |
+ |
|
71 |
+ else: |
|
72 |
+ |
|
73 |
+ z = (yield a-1) |
|
74 |
+ |
|
75 |
+ b = (yield a-2) |
|
76 |
+ |
|
77 |
+ yield Result( z + b ) |
|
78 |
+ |
|
79 |
+ |
|
80 |
+ |
|
81 |
+@wrapper |
|
82 |
+ |
|
83 |
+def fib(a): |
|
84 |
+ |
|
85 |
+ if a in [1,2]: yield Result(1) |
|
86 |
+ |
|
87 |
+ else: |
|
88 |
+ |
|
89 |
+ z = (yield a-1) |
|
90 |
+ |
|
91 |
+ b = (yield a-2) |
|
92 |
+ |
|
93 |
+ yield Result( z + b ) |
|
94 |
+ |
|
95 |
+ |
|
96 |
+ |
|
97 |
+ |
|
98 |
+ |
|
99 |
+@wrapper |
|
100 |
+ |
|
101 |
+def reverse(lis): |
|
102 |
+ |
|
103 |
+ if lis == []: yield Result([]) |
|
104 |
+ |
|
105 |
+ else: |
|
106 |
+ |
|
107 |
+ yield Result( [(yield lis[1:]), lis[0]] ) |