rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
except: return 0 | def SimpleQueryTest(conn): try: # poor man's assertion not conn._db.closed or 1 / 0 conn.cursor().execute("select user();") return 1 except: return 0 | |
if not _users.has_key(connUser): | try: connectParams = _users[connUser] except KeyError: | def getConnection(connUser): """ Returns a database connection as defined by connUser. If this module already has an open connection for connUser, it returns it; otherwise, it creates a new connection, stores it, and returns it. """ if not _users.has_key(connUser): raise SkunkStandardError, 'user %s is not initialized... |
connectParams = _users[connUser] | def getConnection(connUser): """ Returns a database connection as defined by connUser. If this module already has an open connection for connUser, it returns it; otherwise, it creates a new connection, stores it, and returns it. """ if not _users.has_key(connUser): raise SkunkStandardError, 'user %s is not initialized... | |
db=_connections[connUser]=_real_connect(connUser, connectParams) | del _connections[connUser] db=_real_connect(connUser, connectParams) _connections[connUser]=db | def getConnection(connUser): """ Returns a database connection as defined by connUser. If this module already has an open connection for connUser, it returns it; otherwise, it creates a new connection, stores it, and returns it. """ if not _users.has_key(connUser): raise SkunkStandardError, 'user %s is not initialized... |
('path'), | ('path'), ('queryargs', {}), | def genCode(self, indent, codeout, tagreg, tag): DTCompilerUtil.tagDebug(indent, codeout, tag) args=DTUtil.tagCall(tag, [ ('path'), ('noescape', 'None')], kwcol = 'kw' ) kw=DTCompilerUtil.pyifyKWArgs(tag, args['kw']) args=DTCompilerUtil.pyifyArgs(tag, args) |
'%s ( path = %s, noescape = %s, kwargs = %s ) )' % (self.func, args['path'], args['noescape'], kw) ) | '%s ( path = %s, queryargs = %s, noescape = %s, kwargs = %s ) )' % \ (self.func, args['path'], args['queryargs'], args['noescape'], kw) ) | def genCode(self, indent, codeout, tagreg, tag): DTCompilerUtil.tagDebug(indent, codeout, tag) args=DTUtil.tagCall(tag, [ ('path'), ('noescape', 'None')], kwcol = 'kw' ) kw=DTCompilerUtil.pyifyKWArgs(tag, args['kw']) args=DTCompilerUtil.pyifyArgs(tag, args) |
def __init__(self, formname): | def __init__(self, formname, args=None): | def __init__(self, formname): self.formname=formname |
def __init__(self, formname, valid=0): | def __init__(self, formname, valid=0, args=None): | def __init__(self, formname, valid=0): self.formname=formname self.valid=valid |
self._modname = _getModName() | try: self._modname = _getModName() except: pass | def __init__(self, klass = None, superClasses = (), dict = {}): self._modname = _getModName() self._klass = klass self._superClasses = superClasses self._dict = dict |
return {'_klass': self._klass, '_modname': self._modname} | try: return {'_klass': self._klass, '_modname': self._modname} except: raise ValueError, ('Object of type %s cannot be pickled because' ' it is not associated with any module' ) % self._klass | def __getstate__(self): return {'_klass': self._klass, '_modname': self._modname} |
if not lineno and not offset and not line: | if not (lineno and offset and line): | def format ( self ): """ Format self nicely """ |
'Unfortunately, due to Python compiler limitations' \ ' context is not available\n', | 'Unfortunately, due to Python compiler limitations', ' context is not available\n', 'Program text is\n%s' % '\n'.join(["%04d: %s" % (i+1, srclines[i]) for i in range(len(srclines))]), | def format ( self ): """ Format self nicely """ |
self.name, v) | (self.name, v)) | def mergeNamespaces( self, namespace, argDict, auxVars ): sig = self.dt.meta().get(_SIG_META) if sig: #check the argument signature here if a <:compargs:> tag namespace.update(auxVars) for v in sig[_SIG_REQUIRED]: if not argDict.has_key(v) and not auxVars.has_key(v): raise SkunkStandardError, ( 'component %s: argument ... |
def __init__(self, usernameSlot, passwordSlot, authFile, loginPage): SessionAuthBase.__init__(self, usernameSlot, passwordSlot) | def __init__(self, usernameSlot, authFile, loginPage): SessionAuthBase.__init__(self, usernameSlot) | def __init__(self, usernameSlot, passwordSlot, authFile, loginPage): SessionAuthBase.__init__(self, usernameSlot, passwordSlot) AuthFileBase.__init__(self, authFile) RespAuthBase.__init__(self, loginPage) |
ERROR("sessionHandler cannot load: unable to import %s!!!!" % fqcn) | ERROR("auth cannot load: unable to import %s!!!!" % fqcn) | def _getClass(fqcn): # fully qualified class name: package.module.fooClass lastDot=fqcn.rfind('.') if lastDot==0: raise ValueError, "unable to import %s" %fqcn if lastDot>0: modName=fqcn[:lastDot] className=fqcn[lastDot+1:] try: module=__import__(modName, globals(), locals(), [className]) return vars(module)[className]... |
(path, info)=fs.split_extra(connection.uri) | (path, info)=fs.split_extra(_fixPath(Configuration.documentRoot, connection.uri)) | def rewrite(self, match, connection, sessionDict, key): fs=Configuration.documentRootFS (path, info)=fs.split_extra(connection.uri) if not path: raise PreemptiveResponse, self.notFoundHandler(connection, sessionDict) else: if self.add_info_to_args: connection.args[self.path_info_var_name]=info connection.requestHeaders... |
connection.requestHeaders['PATH_INFO']=info connection.uri= path | connection.requestHeaders['PATH-INFO']=info connection.uri= path[len(Configuration.documentRoot):] | def rewrite(self, match, connection, sessionDict, key): fs=Configuration.documentRootFS (path, info)=fs.split_extra(connection.uri) if not path: raise PreemptiveResponse, self.notFoundHandler(connection, sessionDict) else: if self.add_info_to_args: connection.args[self.path_info_var_name]=info connection.requestHeaders... |
self.unixPath=unixpath | self.unixPath=unixPath | def __init__(self, uri=None, host=None, unixPath=None, port=None, skunkPort=None, ip=None, ): self.uri=uri self.host=host self.unixPath=unixpath self.port=port self.skunkPort=skunkPort self.ip=ip |
def __call__(connection, sessionDict): | def __call__(self, connection, sessionDict): | def __call__(connection, sessionDict): for pat, target in zip((self.uri, self.host, self.unixPath, self.ip), (constants.LOCATION, constants.HOST, constants.UNIXPATH, constants.IP)): if pat is not None: t=sessionDict.get(target) if (not t) or not getcompiled(pat).search(t): return 0 for pat, target in zip((self.port, se... |
if (not t) or not getcompiled(pat).search(t): | if (not t) or not _getcompiled(pat).search(t): | def __call__(connection, sessionDict): for pat, target in zip((self.uri, self.host, self.unixPath, self.ip), (constants.LOCATION, constants.HOST, constants.UNIXPATH, constants.IP)): if pat is not None: t=sessionDict.get(target) if (not t) or not getcompiled(pat).search(t): return 0 for pat, target in zip((self.port, se... |
else: | continue | def _dorewriteloop(connection, sessionDict, rules): for p, r in rules: if callable(p): if p(connection, sessionDict): _dorewriteloop(connection, sessionDict, r) else: m = _getcompiled(p).search(connection.uri) if m is not None: if Configuration.rewriteEnableHooks: key=(p, r) sessionDict['rewriteRules'][key] = {} sessio... |
_dorewrite(m, connection, sessionDict, r, key) | _dorewrite(m, connection, sessionDict, r, (p, r)) | def _dorewriteloop(connection, sessionDict, rules): for p, r in rules: if callable(p): if p(connection, sessionDict): _dorewriteloop(connection, sessionDict, r) else: m = _getcompiled(p).search(connection.uri) if m is not None: if Configuration.rewriteEnableHooks: key=(p, r) sessionDict['rewriteRules'][key] = {} sessio... |
return DT.compileTemplate( data, name, tagRegistry ) | if Configuration.noTagDebug: otagdbg = DTCompilerUtil.tagDebug DTCompilerUtil.tagDebug = dt_no_tag_debug obj = DT.compileTemplate( data, name, tagRegistry ) DTCompilerUtil.tagDebug = otagdbg return obj else: return DT.compileTemplate( data, name, tagRegistry ) | def _dtCompileFunc( name, data ): return DT.compileTemplate( data, name, tagRegistry ) |
elif c == "\"": | elif s == 1 and c == "\"": s = 0 elif s == 2 and c == "'": | def parenthesis_balance(l, x, y): b = 0 s = 0 e = 0 for c in l: if e: e = 0 elif s: if c == "\\": e = 1 elif c == "\"": s = 0 elif c == "\"": s = 1 elif c == x: b += 1 elif c == y: b -= 1 return b |
elif c == "\"": | elif s == 1 and c == "\"": s = 0 elif s == 2 and c == "'": | def colon_find(l): mob = re.compile("\s*(\w+)").match(l) if mob and not mob.group(1) in ["for", "if", "while", "else", "elif"]: return None colon = None s = 0 e = 0 for i in range(len(l)): c = l[i] if e: e = 0 elif s: if c == "\\": e = 1 elif c == "\"": s = 0 elif c == "\"": s = 1 elif c == ":": colon = i return colon |
def string_cb(l, cb): outside = "" inside = "" pos = 0 start_pos = 0 is_in_string = False is_escaped = False for c in l: if is_escaped: is_escaped = False inside += c elif is_in_string: if c == "\\": is_escaped = True inside += c elif c == "\"": is_in_string = False inside += c ret = cb(True, start_pos, inside) if ret ... | def colon_find(l): mob = re.compile("\s*(\w+)").match(l) if mob and not mob.group(1) in ["for", "if", "while", "else", "elif"]: return None colon = None s = 0 e = 0 for i in range(len(l)): c = l[i] if e: e = 0 elif s: if c == "\\": e = 1 elif c == "\"": s = 0 elif c == "\"": s = 1 elif c == ":": colon = i return colon | |
self.the_doc = "" | def __init__(self, fin, fot, hot, name, egg, guard_prefix = "", dot = None): self.linecont = "" self.num = 0 self.depths = [Level()] self.preprocessor_targets = ["implementation"] self.fin = fin self.fot = fot self.real_hot = hot self.hot = StringIO.StringIO() self.typedefs = StringIO.StringIO() self.to = fot self.dot ... | |
%s | %s%s | def header(self): self.to.write(""" |
""".lstrip() % (self.blah, self.egg, self.name)) | """.lstrip() % (self.blah, self.numbering and '\n self.name)) | #undef max |
%s | %s%s | def footer(self): self.to.write(self.blah + "\n") self.hot.write("#endif\n") self.hot.write(self.blah + "\n") |
""".lstrip() % (self.blah, self.egg, self.guard, self.guard)) | """.lstrip() % (self.blah, self.numbering and '\n self.guard, self.guard)) | #ifndef %s |
if self.docstring == None and l.lstrip().startswith('"""'): self.docstring = "" l = l.lstrip()[3:] | def translate(self): for l in self.fin.readlines() + ["end:"]: self.num += 1 | |
self.docstring += l if self.docstring.rstrip().endswith('"""'): self.docstring = self.docstring.rstrip()[:-3] lines = self.docstring.splitlines() doc = lines[0] if len(lines) > 1: doc += "\n" + textwrap.dedent("\n".join(lines[1:])) self.the_doc = doc.strip() self.docstring = None | self.add_to_docstring(l) | def translate(self): for l in self.fin.readlines() + ["end:"]: self.num += 1 |
self.to.write("\n") | if self.numbering: self.to.write("\n") | def translate(self): for l in self.fin.readlines() + ["end:"]: self.num += 1 |
self.to.write(" | if self.numbering: self.to.write(" | def handle_line(self, l): |
self.dot.write("%s\n" % self.the_doc) self.the_doc = "" | self.dot.write("%s\n" % the_doc) | def handle_line(self, l): |
self.dot.write("%s\n" % self.the_doc) self.the_doc = "" | self.dot.write("%s\n" % the_doc) | self.dot.write('"""def %s\n' % self.depths[-1].name) |
self.to.write(" | if self.numbering: self.to.write(" | self.dot.write('"""def %s\n' % self.depths[-1].name) |
self.hot.write(" | if self.numbering: self.hot.write(" | def translate_def(self, l): mob = re.compile(r"\s*(.*?)\s*def\s*(\w+?)\s*\((.*)\)").match(l) if not mob: sys.stderr.write("%d: Error, no function!\n" % self.num) else: retval = mob.group(1) name = mob.group(2) params = mob.group(3) if retval == "": retval = "void" if retval in ["static", "inline static", "static inline... |
t.write(" | if self.numbering: t.write(" | def translate_import(self, t, names): q = ('"', '"') for name in names: name = name.strip() if name.startswith("global "): q = ("<", ">") name = name[7:].strip() if name: t.write("#line %d\n" % self.num) t.write("#include %s%s.h%s\n" % (q[0], name, q[1])) |
l1routs = ['asum', 'axpy', 'dot', 'scal'] l1refs = ['asum_fabs1_x1.c', 'axpy1_x1y1.c', 'dot1_x1y1.c', 'scal1_x1.c'] | psiz = [4, 8] l1routs = ['asum', 'axpy', 'dot', 'scal', 'iamax'] l1refs = ['asum_fabs1_x1.c', 'axpy1_x1y1.c', 'dot1_x1y1.c', 'scal1_x1.c', 'iamax_abs1_x1.c'] | def FindAtlas(FKOdir): file = os.path.join(FKOdir, 'time') file = os.path.join(file, 'Makefile') fi = open(file, 'r') for line in fi.readlines(): if (line.startswith('include')): j = line.find('Make.') assert(j != -1) ARCH = line[j+5:].strip() ATLdir = line[8:j-1].strip() break else: print "Can't find include line in ... |
sys.exit(0) | VS = "" KFLAG = "-P all 0 " + str(LS*2) | def FindAtlas(FKOdir): file = os.path.join(FKOdir, 'time') file = os.path.join(file, 'Makefile') fi = open(file, 'r') for line in fi.readlines(): if (line.startswith('include')): j = line.find('Make.') assert(j != -1) ARCH = line[j+5:].strip() ATLdir = line[8:j-1].strip() break else: print "Can't find include line in ... |
print 'l1atl = ', l1atl | CALLREF=0 CALLATL=0 CALLFKO=1 opt = "-X 1 -Y 1 -Fx 16 -Fy 16" | def FindAtlas(FKOdir): file = os.path.join(FKOdir, 'time') file = os.path.join(file, 'Makefile') fi = open(file, 'r') for line in fi.readlines(): if (line.startswith('include')): j = line.find('Make.') assert(j != -1) ARCH = line[j+5:].strip() ATLdir = line[8:j-1].strip() break else: print "Can't find include line in ... |
[time,mf] = l1cmnd.time(ATLdir, ARCH, pre, blas, N, l1refs[i]) print "REF %20.20s : time=%f, mflop=%f" % (pre+l1refs[i], time, mf) refT.append(time) refMF.append(mf) [time,mf] = l1cmnd.time(ATLdir, ARCH, pre, blas, N, l1atl[j], CCatl[j], CCFat[j]) print "ATL %20.20s : time=%f, mflop=%f" % (pre+l1atl[j], time, mf) atlT.... | if (CALLREF != 0): [time,mf] = l1cmnd.time(ATLdir, ARCH, pre, blas, N, l1refs[i]) print "REF %20.20s : time=%f, mflop=%f" % (pre+l1refs[i], time, mf) refT.append(time) refMF.append(mf) if (CALLATL != 0): [time,mf] = l1cmnd.time(ATLdir, ARCH, pre, blas, N, l1atl[j], CCatl[j], CCFat[j]) print "ATL %20.20s : time=%f, mfl... | def FindAtlas(FKOdir): file = os.path.join(FKOdir, 'time') file = os.path.join(file, 'Makefile') fi = open(file, 'r') for line in fi.readlines(): if (line.startswith('include')): j = line.find('Make.') assert(j != -1) ARCH = line[j+5:].strip() ATLdir = line[8:j-1].strip() break else: print "Can't find include line in ... |
print " default is ~/.i2pstasher" | print " default is ~/.stasher" | def usage(detailed=False, ret=0): print "Usage: %s <options> [<command> [<ars>...]]" % sys.argv[0] if not detailed: print "Type %s -h for help" % sys.argv[0] sys.exit(ret) print "This is stasher, distributed file storage network that runs" print "atop the anonymising I2P network (http://www.i2p.net)" print "Written b... |
print ans1[0], rans | def minitest_select(rans, wans, eans, timeout, f1=None, f4=None, c1=None, c4=None): """Mini-unit test for select (Python and I2P sockets). Calls f1() on socket S1, f4() on socket S4, uses select() timeout 'timeout'. rans, wans, and eans should be lists containing indexes 1...6 of the sockets defined below. The result... | |
print ans2[1], wans | def minitest_select(rans, wans, eans, timeout, f1=None, f4=None, c1=None, c4=None): """Mini-unit test for select (Python and I2P sockets). Calls f1() on socket S1, f4() on socket S4, uses select() timeout 'timeout'. rans, wans, and eans should be lists containing indexes 1...6 of the sockets defined below. The result... | |
print ans3[2], eans | def minitest_select(rans, wans, eans, timeout, f1=None, f4=None, c1=None, c4=None): """Mini-unit test for select (Python and I2P sockets). Calls f1() on socket S1, f4() on socket S4, uses select() timeout 'timeout'. rans, wans, and eans should be lists containing indexes 1...6 of the sockets defined below. The result... | |
print ans, [rans, wans, eans] | def minitest_select(rans, wans, eans, timeout, f1=None, f4=None, c1=None, c4=None): """Mini-unit test for select (Python and I2P sockets). Calls f1() on socket S1, f4() on socket S4, uses select() timeout 'timeout'. rans, wans, and eans should be lists containing indexes 1...6 of the sockets defined below. The result... | |
print S.recv(1) | S.recv(1) | def full1(S): """Connect regular Python socket to Google, and send.""" connect1(S) S.sendall('GET / HTTP/1.0\r\n\r\n') print S.recv(1) |
def connect(self, address, **kw): | def connect(self, address): | def connect(self, address, **kw): """ Attempts to connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. |
Attempts to connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. | Connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. | def connect(self, address, **kw): """ Attempts to connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. |
s.connect("duck.i2p") You can pass a keyword 'dontResolve', which if true, allows you to pass the base64 destination as the address, and override the hostname lookup. | s.connect('duck.i2p') Alternatively, you can use a full base64 Destination: | def connect(self, address, **kw): """ Attempts to connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. |
s.connect("238797sdfh2k34kjh....AAAA") | s.connect('238797sdfh2k34kjh....AAAA') | def connect(self, address, **kw): """ Attempts to connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. |
if not kw.get('dontResolve', 1): address = resolve(address, self.samaddr) | address = resolve(address, self.samaddr) | def connect(self, address, **kw): """ Attempts to connect to a remote dest, identified in local SAM bridge's hosts file as host 'address'. |
return (data[:bufsize], addr) | if bufsize == -1: return (data, addr) else: return (data[:bufsize], addr) | def recvfrom(self, bufsize, flags=0): """Like recv(), but returns a tuple (data, remoteaddr), where data is the string data received, and remoteaddr is the remote Destination.""" timeout = self.timeout (peek, waitall, dontwait) = \ (flags & MSG_PEEK, flags & MSG_WAITALL, flags & MSG_DONTWAIT) if dontwait: timeout = 0.0 |
self.log(3, "queries sent, awaiting reply") | self.log(3, "%s queries sent, awaiting reply" % numQueriesSent) | def sendSomeQueries(self, **kw): """ First step of findNode Select alpha nodes that we haven't yet queried, and send them queries """ # bail if too busy if self.numQueriesPending >= maxConcurrentQueries: return # shorthand localNode = self.localNode hashWanted = self.hashWanted # randomly choose some peers #somePeer... |
self.numPeersToStore = min(len(peers), numStorePeers) | i = 0 | def on_doneFindNode(self, lst): """ Receive a callback from findNode Send STORE command to each node that comes back """ localNode = self.localNode # normalise results normalisePeer = localNode._normalisePeer peers = [normalisePeer(p) for p in lst] # wrap in KPeer objects self.log(2, "STORE RPC findNode - got peers ... |
i = 0 | def on_doneFindNode(self, lst): """ Receive a callback from findNode Send STORE command to each node that comes back """ localNode = self.localNode # normalise results normalisePeer = localNode._normalisePeer peers = [normalisePeer(p) for p in lst] # wrap in KPeer objects self.log(2, "STORE RPC findNode - got peers ... | |
self.log(3, "got a timeout tick, what should we do??") self.nextTickTime = time.time() + 3 | self.log(3, "Timeout awaiting store reply from %d out of %d peers" % ( self.numPeersToStore - self.numPeersSucceeded, self.numPeersToStore)) if self.numPeersSucceeded == 0: self.log(3, "Store timeout - no peers replied, storing locally") self.localNode.storage.putKey(self.keyHashed, self.value, keyIsHashed=True) self... | def on_tick(self): self.log(3, "got a timeout tick, what should we do??") self.nextTickTime = time.time() + 3 |
if now >= rpc.nextTickTime: | if rpc.nextTickTime != None and now >= rpc.nextTickTime: | def _doHousekeeping(self): """ Performs periodical housekeeping on this node. Activities include: - checking pending records for timeouts """ now = time.time() # DEPRECATED - SWITCH TO RPC-based # check for expired pings for msgId, (dest, q, pingDeadline) in self.pendingPings.items(): if pingDeadline > now: # not ti... |
self.wfile.close() | def close(self): self.rfile.close() self.wfile.close() self.sock.close() | |
self.close() | def getref(self): """ Uplifts node's own ref """ self.connect() self.write("getref\n") self.flush() res = self.readline().strip() self.close() if res == "ok": ref = self.readline().strip() return ref else: return "failed" | |
def time(): return time.time() | def timer(): return time.time() | def time(): return time.time() # High resolution timer # Do NOT use time.clock() as it # drops sleep() time on Linux. |
if timeout != None: end = time() + timeout | if timeout != None: end = timer() + timeout | def connect(self, dest, timeout=None): """Create a stream connected to remote destination 'dest'. The id is random. If the timeout is exceeded, do NOT raise an error; rather, return a Stream object with .didconnect set to False.""" if not isinstance(dest, type('')): raise TypeError # Synchronize self.lock.acquire() t... |
if timeout != None and time() >= end: break | if timeout != None and timer() >= end: break | def connect(self, dest, timeout=None): """Create a stream connected to remote destination 'dest'. The id is random. If the timeout is exceeded, do NOT raise an error; rather, return a Stream object with .didconnect set to False.""" if not isinstance(dest, type('')): raise TypeError # Synchronize self.lock.acquire() t... |
if timeout != None: end = time() + timeout | if timeout != None: end = timer() + timeout | def accept(self, timeout=None): """Wait for incoming connection, and return a Stream object for it.""" if self.max_accept <= 0: raise i2p.Error('listen(n) must be called before accept ' + '(n>=1)') if timeout != None: end = time() + timeout while True: self.term.check() # Synchronized self.lock.acquire() try: # Get Str... |
if timeout != None and time() >= end: break | if timeout != None and timer() >= end: break | def accept(self, timeout=None): """Wait for incoming connection, and return a Stream object for it.""" if self.max_accept <= 0: raise i2p.Error('listen(n) must be called before accept ' + '(n>=1)') if timeout != None: end = time() + timeout while True: self.term.check() # Synchronized self.lock.acquire() try: # Get Str... |
if timeout != None: end = time() + timeout | if timeout != None: end = timer() + timeout | def recv(self, n, timeout=None, peek=False, waitall=False): """Reads up to n bytes in a manner identical to socket.recv. Blocks for up to timeout seconds if n > 0 and no data is available (timeout=None means wait forever). If still no data is available, raises BlockError or Timeout. For a closed stream, recv will rea... |
if timeout != None and time() >= end: break | if timeout != None and timer() >= end: break | def recv(self, n, timeout=None, peek=False, waitall=False): """Reads up to n bytes in a manner identical to socket.recv. Blocks for up to timeout seconds if n > 0 and no data is available (timeout=None means wait forever). If still no data is available, raises BlockError or Timeout. For a closed stream, recv will rea... |
if timeout != None: end = time() + timeout | if timeout != None: end = timer() + timeout | def recv(self, timeout=None, peek=False): """Get a single packet. Blocks for up to timeout seconds if n > 0 and no packet is available (timeout=None means wait forever). If still no packet is available, raises BlockError or Timeout. Returns the pair (data, address). If peek is True, the data is not removed.""" if t... |
if timeout != None and time() >= end: break | if timeout != None and timer() >= end: break | def recv(self, timeout=None, peek=False): """Get a single packet. Blocks for up to timeout seconds if n > 0 and no packet is available (timeout=None means wait forever). If still no packet is available, raises BlockError or Timeout. Returns the pair (data, address). If peek is True, the data is not removed.""" if t... |
if timeout != None: end = time() + timeout | if timeout != None: end = timer() + timeout | def recv(self, timeout=None, peek=False): """Identical to DatagramSocket.recv. The from address is an empty string.""" if timeout != None: end = time() + timeout while True: self.term.check() # Synchronized check and read until data available. self.lock.acquire() try: if len(self.buf) > 0: if peek: ans = self.buf.pop_... |
if timeout != None and time() >= end: break | if timeout != None and timer() >= end: break | def recv(self, timeout=None, peek=False): """Identical to DatagramSocket.recv. The from address is an empty string.""" if timeout != None: end = time() + timeout while True: self.term.check() # Synchronized check and read until data available. self.lock.acquire() try: if len(self.buf) > 0: if peek: ans = self.buf.pop_... |
if bufsize < 0: raise ValueError('bufsize must be >= 0') | if bufsize < 0: raise ValueError('bufsize must be >= 0 for streams') | def recvfrom(self, bufsize, flags=0): """Like recv(), but returns a tuple (data, remoteaddr), where data is the string data received, and remoteaddr is the remote Destination.""" timeout = self.timeout (peek, waitall, dontwait) = \ (flags & MSG_PEEK, flags & MSG_WAITALL, flags & MSG_DONTWAIT) if dontwait: timeout = 0.0 |
return self.sessobj.recv(timeout, peek)[:bufsize] | if bufsize < -1: raise ValueError('bufsize must be >= -1 for packets') (data, addr) = self.sessobj.recv(timeout, peek) return (data[:bufsize], addr) | def recvfrom(self, bufsize, flags=0): """Like recv(), but returns a tuple (data, remoteaddr), where data is the string data received, and remoteaddr is the remote Destination.""" timeout = self.timeout (peek, waitall, dontwait) = \ (flags & MSG_PEEK, flags & MSG_WAITALL, flags & MSG_DONTWAIT) if dontwait: timeout = 0.0 |
def dummyGetId(): return '' | def dummyGetId(): return '' | |
registeredPortletTyeps = [r.name for r in self.context.registeredUtilities() | registeredPortletTypes = [r.name for r in self.context.registeredUtilities() | def _extractPortlets(self): fragment = self._doc.createDocumentFragment() registeredPortletTyeps = [r.name for r in self.context.registeredUtilities() if r.provided == IPortletType] portletManagerRegistrations = [r for r in self.context.registeredUtilities() if r.provided.isOrExtends(IPortletManager)] for r in portle... |
specificInterface = providedBy(r.component).flattened()[0] | specificInterface = providedBy(r.component).flattened().next() | def _extractPortlets(self): fragment = self._doc.createDocumentFragment() registeredPortletTyeps = [r.name for r in self.context.registeredUtilities() if r.provided == IPortletType] portletManagerRegistrations = [r for r in self.context.registeredUtilities() if r.provided.isOrExtends(IPortletManager)] for r in portle... |
child.setAttribute('for', _getDottedName(child.for_)) | child.setAttribute('for', _getDottedName(portletType.for_)) | def _extractPortlets(self): fragment = self._doc.createDocumentFragment() registeredPortletTyeps = [r.name for r in self.context.registeredUtilities() if r.provided == IPortletType] portletManagerRegistrations = [r for r in self.context.registeredUtilities() if r.provided.isOrExtends(IPortletManager)] for r in portle... |
return '%s/join_form' % url() | return '%s/login_form' % url() | def login_form(self): url = getToolByName(self.context, 'portal_url') return '%s/join_form' % url() |
self.monthName = PMF(self._ts.month_msgid(self.month), default=self._ts.month_english(self.month)) | self.monthName = PLMF(self._ts.month_msgid(self.month), default=self._ts.month_english(self.month)) | def __init__(self, context, request, view, manager, data): base.Renderer.__init__(self, context, request, view, manager, data) |
weekdays.append(PMF(self._ts.day_msgid(day, format='s'), default=self._ts.weekday_english(day, format='a'))) | weekdays.append(PLMF(self._ts.day_msgid(day, format='s'), default=self._ts.weekday_english(day, format='a'))) | def getWeekdays(self): """Returns a list of Messages for the weekday names.""" weekdays = [] # list of ordered weekdays as numbers for day in self.calendar.getDayNumbers(): weekdays.append(PMF(self._ts.day_msgid(day, format='s'), default=self._ts.weekday_english(day, format='a'))) |
from os.path import exists, join | from os.path import exists, join, basename | def prepare(self): import os import urllib2 import shutil from os.path import exists, join from tempfile import mktemp id = self.sim.id portal = self.portal |
junkDir = simDir + '-' + mktemp() | junkDir = simDir + '-' + basename(mktemp()) | def prepare(self): import os import urllib2 import shutil from os.path import exists, join from tempfile import mktemp id = self.sim.id portal = self.portal |
walltime = dimensional("walltime", default=30.0*minute) | walltime = dimensional("walltime", default=0*minute) | def _appendNodeListArgs(self, args): nodegen = self.inventory.nodegen args.append("n" + ",".join([(nodegen) % node for node in self.nodelist])) |
'NTSTEP_BETWEEN_READ_ADJSRC': 'solver.ntstep-between-read_adjsrc', | 'NTSTEP_BETWEEN_READ_ADJSRC': 'solver.ntstep-between-read-adjsrc', | def _parse(self, pathname, root): # Technically, the parameters must be in a specific order, but # we don't enforce that here. from cig.addyndum.util import setPropertyWithPath f = open(pathname, "r") lineno = 0 for line in f: lineno = lineno + 1 if line[0] == '#': continue tokens = line.split() if not len(tokens): con... |
connection.ping() | try: connection.ping() except socket.error, e: if len(e.args)>1: err_txt = e.args[1] else: err_txt = e.args[0] self.logger.error('Pinger error: %s' % err_txt) | def pinger(self): sleep_secs = 5 while not self.full_stop.isSet(): for connection in self.pool.getConnections(): ping_period = connection.ping_period last_ping_time = connection.last_ping_time if (time.time() - last_ping_time) > (ping_period - sleep_secs): connection.ping() time.sleep(sleep_secs) |
bdate = tuple([int(x) for x in anketa['Birthday'].split('-')]+[1 for i in range(9)])[:9] vcard.setTagData('BDAY', time.strftime('%d %B %Y', bdate)+' г.') | vcard.setTagData('BDAY',anketa['Birthday']) | def anketa2vcard(self, anketa, avatara, ava_typ, album): attributes = { 'xmlns':"vcard-temp", #'prodid':"-//HandGen//NONSGML vGen v1.0//EN", #'version':"2.0" } e_mail = xmpp.Node('EMAIL') tel = xmpp.Node('TEL') adr = xmpp.Node('ADR') N = xmpp.Node('N') vcard = xmpp.Node('vCard', attrs=attributes) vcard.setTagData('FN',... |
self.log(logging.DEBUG, "Send %s packet (type=%s):\n%s" % (num_type[typ],hex(int(typ)), self.dump_packet(p))) | if typ!= MRIM_CS_PING: self.log(logging.DEBUG, "Send %s packet (type=%s):\n%s" % (num_type[typ],hex(int(typ)), self.dump_packet(p))) else: self.log(logging.DEBUG, "Ping") | def _send_packet(self, p): |
'login':self.__login, 'password':self.__password, | 'login':utils.str2win(self.__login), 'password':utils.str2win(self.__password), | def _got_hello_ack(self): |
'user_agent':self.__agent | 'user_agent':utils.str2win(self.__agent) | def _got_hello_ack(self): |
except urllib2.HTTPError: pass | except urllib2.HTTPError, e: http_err = "Can't connect to http://avt.foto.mail.ru (%s)" % e self.log(logging.ERROR, http_err) except urllib2.URLError, e: if hasattr(e.reason, 'args') and len(e.reason.args)==2: http_err = "Can't connect to http://avt.foto.mail.ru (%s)" % e.reason.args[1] else: http_err = "Can't connect ... | def _get_avatar(self, mail, ackf, acka): avatara = '' album = '' content_type = None try: user, domain = mail.split('@') url = 'http://avt.foto.mail.ru/%s/%s/_mrimavatar' % (domain.split('.')[0], user) album = 'http://avt.foto.mail.ru/%s/%s/' % (domain.split('.')[0], user) req = urllib2.Request(url) u = urllib2.urlopen... |
print >> outfile, e.q , "\t", e.a | if e.cat.name in cat_names_to_export: print >> outfile, e.q , "\t", e.a | def export_txt(filename, cat_names_to_export): outfile = file(filename,'w') for e in items: print >> outfile, e.q , "\t", e.a outfile.close() |
return False item.a = item.a.rstrip() | return False | def import_txt(filename, default_cat, reset_learning_data=False): global items imported_items = [] # Parse txt file. avg_easiness = average_easiness() f = None try: f = file(filename) except: try: f = file(filename.encode("latin")) except: print "Unable to open file." return False for line in f: try: line = unic... |
from mnemosyne_log import * | import mnemosyne_log | def initialise(): from mnemosyne_log import * global upload_thread, load_failed load_failed = False join = os.path.join exists = os.path.exists # Set default paths. basedir = os.path.join(os.path.expanduser("~"), ".mnemosyne") if not exists(basedir): os.mkdir(basedir) if not exists(join(basedir,"config")): in... |
archive_old_log() start_logging() | mnemosyne_log.archive_old_log() mnemosyne_log.start_logging() | def initialise(): from mnemosyne_log import * global upload_thread, load_failed load_failed = False join = os.path.join exists = os.path.exists # Set default paths. basedir = os.path.join(os.path.expanduser("~"), ".mnemosyne") if not exists(basedir): os.mkdir(basedir) if not exists(join(basedir,"config")): in... |
upload_thread = Uploader() | upload_thread = mnemosyne_log.Uploader() | def initialise(): from mnemosyne_log import * global upload_thread, load_failed load_failed = False join = os.path.join exists = os.path.exists # Set default paths. basedir = os.path.join(os.path.expanduser("~"), ".mnemosyne") if not exists(basedir): os.mkdir(basedir) if not exists(join(basedir,"config")): in... |
print >> outfile, e.q.encode("utf-8") + "\t" + e.a.encode("utf-8") | question = e.q.encode("utf-8") question = question.replace("\t", " ") question = question.replace("\n", "<br>") answer = e.a.encode("utf-8") answer = answer.replace("\t", " ") answer = answer.replace("\n", "<br>") print >> outfile, question + "\t" + answer | def export_txt(filename, cat_names_to_export, reset_learning_data=False): outfile = file(filename,'w') for e in items: if e.cat.name in cat_names_to_export: print >> outfile, e.q.encode("utf-8") + "\t" + e.a.encode("utf-8") outfile.close() |
start = new_string.lower().find("<latex>", end+1) | start = new_string.lower().find("<latex>") | def preprocess(old_string): # Escape literal < (unmatched tag) and new line from string. hanging = [] open = 0 pending = 0 for i in range(len(old_string)): if old_string[i] == '<': if open != 0: hanging.append(pending) pending = i continue open += 1 pending = i elif old_string[i] == '>': if open > 0: open -= 1 if o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.