rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
>>> ms_u.getGroupwiseDistance_Goldstein([1,2,3,4],[1,2,3,4]) == 1330.5 | >>> ms_u.getGroupwiseDistance_Goldstein([1,2,3,4],[1,2,3,4]) == 47.517857142857146 | def getGroupwiseDistance_Goldstein(self,x,y): """ Returns the goldstein distance between two populations |
for j in ydict: dist += 1.0*(i-j)**2*xdict[i]/(2*len(x))*ydict[j]/(2*len(y))/self.getNumberofLoci() | if i!=None: for j in ydict: if j!=None: dist += float(i-j)**2*xdict[i]/NElementsX*ydict[j]/NElementsY | def getGroupwiseDistance_Goldstein(self,x,y): """ Returns the goldstein distance between two populations |
return sum(distList) | return sum(distList)/self.getNumberofLoci() | def getGroupwiseDistance_Goldstein(self,x,y): """ Returns the goldstein distance between two populations |
if x[locus]!=None and y[locus]!=None: | if x[locus][0]!=None and y[locus][0]!=None: | def getMSDistanceVectorByAlleles(self,x,y,distance_singleLocus): distance=numpy.zeros(len(x)) for locus in range(0,len(x)): if x[locus]!=None and y[locus]!=None: distance[locus]=distance_singleLocus(x[locus],y[locus]) else: distance[locus]=numpy.nan return distance |
communityKey=self.getParent(node) | communityKey=self.getSetIndex(node) | def getCommStruct(self,separateElements=True): communityMap={} if self.mappingOn: nodes=self.ktree else: nodes=range(0,len(self.ktree)) for node in nodes: communityKey=self.getParent(node) if separateElements or communityKey!=node: if communityKey not in communityMap: communityMap[communityKey]=[node] else: communityM... |
print " ".join([str(x) for x in xs]) | print " ".join(map(str, xs)) | def _debug(*xs): if __debug__: print " ".join([str(x) for x in xs]) |
print " ".join([str(x) for x in xs]), | print " ".join(map(str, xs)), | def _debug_noln(*xs): if __debug__: print " ".join([str(x) for x in xs]), sys.stdout.flush() |
pygame.display.flip() | _try_to_flip() | def _handle_events(): for event in pygame.event.get(): if event.type == pygame.locals.QUIT: _explicit_exit_func() if event.type == pygame.locals.KEYDOWN: # Execute the keybinding function, defaulting to a noop method _keybinds.get(event.key, _noop)() pygame.display.flip() _clock.tick(_FPS) |
def _try_to_flip(): if _video_is_on: pygame.display.flip() | def _handle_events(): for event in pygame.event.get(): if event.type == pygame.locals.QUIT: _explicit_exit_func() if event.type == pygame.locals.KEYDOWN: # Execute the keybinding function, defaulting to a noop method _keybinds.get(event.key, _noop)() pygame.display.flip() _clock.tick(_FPS) | |
def _screen(): return pygame.display.get_surface() @atexit.register def _end(): '''\ If the user explicitly asks to quit the animation or image, this function does nothing and immediately exits. Otherwise, this function retains the image on the screen until the user explicitly exits. ''' if _explicit_exit: return whil... | _video_is_on = True | def show(): '''Set up the basic pypixel environment, like the main window.''' global _clock pygame.init() title(None) pygame.display.set_mode(SIZE, _WINDOW_OPTS) pygame.mouse.set_visible(False) _clock = pygame.time.Clock() |
pygame.init() | def show(): '''Set up the basic pypixel environment, like the main window.''' global _clock title(None) pygame.init() pygame.display.set_mode(SIZE, _WINDOW_OPTS) pygame.mouse.set_visible(False) _clock = pygame.time.Clock() | |
self.assertRaises(Exception, test_view('product_cost_history')) | test_view('product_cost_history') | def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('product_cost_history')) |
tokens = _token_spliter.split(line) | tokens = _token_splitter.split(line) | def __call__(self, frame, event, arg): if event == 'line': lineno = frame.f_lineno if '__file__' in frame.f_globals: filename = frame.f_globals['__file__'] if (filename.endswith('.pyc') or filename.endswith('.pyo')): filename = filename[:-1] name = frame.f_globals['__name__'] line = linecache.getline(filename, lineno) ... |
for modname, mod in self._saved.iteritems(): if mod is not None: sys.modules[modname] = mod else: try: del sys.modules[modname] except KeyError: pass | try: for modname, mod in self._saved.iteritems(): if mod is not None: sys.modules[modname] = mod else: try: del sys.modules[modname] except KeyError: pass finally: imp.release_lock() | def restore(self): """Restores the modules that the saver knows about into sys.modules. """ for modname, mod in self._saved.iteritems(): if mod is not None: sys.modules[modname] = mod else: try: del sys.modules[modname] except KeyError: pass |
for name, mod in modules_to_patch: orig_mod = sys.modules.get(name) if orig_mod is None: orig_mod = __import__(name) for attr_name in mod.__patched__: patched_attr = getattr(mod, attr_name, None) if patched_attr is not None: setattr(orig_mod, attr_name, patched_attr) if patched_thread: _patch_main_thread(sys.modules[... | imp.acquire_lock() try: for name, mod in modules_to_patch: orig_mod = sys.modules.get(name) if orig_mod is None: orig_mod = __import__(name) for attr_name in mod.__patched__: patched_attr = getattr(mod, attr_name, None) if patched_attr is not None: setattr(orig_mod, attr_name, patched_attr) if patched_thread: _patch_... | def monkey_patch(**on): """Globally patches certain system modules to be greenthread-friendly. The keyword arguments afford some control over which modules are patched. If no keyword arguments are supplied, all possible modules are patched. If keywords are set to True, only the specified modules are patched. E.g., ``... |
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) | year, month, day, hh, mm, ss, wd, _y, _z = time.gmtime(timestamp) | def format_date_time(timestamp): """Formats a unix timestamp into an HTTP standard string.""" year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( _weekdayname[wd], day, _monthname[month], year, hh, mm, ss ) |
'Content-Length' not in [h for h, v in headers_set[1]]: | 'Content-Length' not in [h for h, _v in headers_set[1]]: | def start_response(status, response_headers, exc_info=None): status_code[0] = status.split()[0] if exc_info: try: if headers_sent: # Re-raise original exception if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: # Avoid dangling circular ref exc_info = None |
def import_main(g, name): | def import_main(name): | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
modobj = __import__(name, g, fromlist=['test_main']) | modobj = __import__(name, globals(), locals(), ['test_main']) | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
g[method_name] = modobj.test_main | globals()[method_name] = modobj.test_main | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
import_main(globals(), 'test_select') import_main(globals(), 'test_SimpleHTTPServer') import_main(globals(), 'test_asynchat') import_main(globals(), 'test_asyncore') import_main(globals(), 'test_ftplib') import_main(globals(), 'test_httplib') | import_main('test_select') import_main('test_SimpleHTTPServer') import_main('test_asynchat') import_main('test_asyncore') import_main('test_ftplib') import_main('test_httplib') | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
import_main(globals(), 'test_httpservers') | import_main('test_httpservers') | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
import_main(globals(), 'test_socket') import_main(globals(), 'test_socket_ssl') import_main(globals(), 'test_socketserver') | import_main('test_socket') import_main('test_socket_ssl') import_main('test_socketserver') | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
import_main(globals(), 'test_ssl') import_main(globals(), 'test_thread') import_main(globals(), 'test_threading_local') | import_main('test_ssl') import_main('test_thread') import_main('test_threading_local') | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
import_main(globals(), 'test_timeout') import_main(globals(), 'test_urllib') | import_main('test_timeout') import_main('test_urllib') | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
import_main(globals(), 'test_urllib2') import_main(globals(), 'test_urllib2_localnet') | import_main('test_urllib2') import_main('test_urllib2_localnet') | def import_main(g, name): try: modobj = __import__(name, g, fromlist=['test_main']) except ImportError: print "Not importing %s, it doesn't exist in this installation/version of Python" % name return else: method_name = name + "_test_main" try: g[method_name] = modobj.test_main modobj.test_main.__name__ = name + '.test... |
>>> evt = event.Event() | >>> from eventlet.event import Event >>> evt = Event() | ... def received(self, (message, evt) ): |
import fcntl | try: import fcntl except ImportError: raise NotImplementedError("set_nonblocking() on a file object " "with no setblocking() method " "(Windows pipes don't support non-blocking I/O)") | def set_nonblocking(fd): try: setblocking = fd.setblocking except AttributeError: # This version of Python predates socket.setblocking() import fcntl fileno = fd.fileno() flags = fcntl.fcntl(fileno, fcntl.F_GETFL) fcntl.fcntl(fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK) else: # socket supports setblocking() setblockin... |
"WebSocket-Location: ws://%s%s\r\n\r\n" % ( | "WebSocket-Location: %s\r\n\r\n" % ( | def __call__(self, environ, start_response): if not (environ.get('HTTP_CONNECTION') == 'Upgrade' and environ.get('HTTP_UPGRADE') == 'WebSocket'): # need to check a few more things here for true compliance start_response('400 Bad Request', [('Connection','close')]) return [] # See if they sent the new-format headers if... |
environ.get('HTTP_HOST'), environ.get('PATH_INFO'))) | location)) | def __call__(self, environ, start_response): if not (environ.get('HTTP_CONNECTION') == 'Upgrade' and environ.get('HTTP_UPGRADE') == 'WebSocket'): # need to check a few more things here for true compliance start_response('400 Bad Request', [('Connection','close')]) return [] # See if they sent the new-format headers if... |
"Sec-WebSocket-Location: ws://%s%s\r\n" | "Sec-WebSocket-Location: %s\r\n" | def __call__(self, environ, start_response): if not (environ.get('HTTP_CONNECTION') == 'Upgrade' and environ.get('HTTP_UPGRADE') == 'WebSocket'): # need to check a few more things here for true compliance start_response('400 Bad Request', [('Connection','close')]) return [] # See if they sent the new-format headers if... |
environ.get('HTTP_HOST'), environ.get('PATH_INFO'), | location, | def __call__(self, environ, start_response): if not (environ.get('HTTP_CONNECTION') == 'Upgrade' and environ.get('HTTP_UPGRADE') == 'WebSocket'): # need to check a few more things here for true compliance start_response('400 Bad Request', [('Connection','close')]) return [] # See if they sent the new-format headers if... |
Pool is a base class that is meant to be subclassed. When subclassing, define the :meth:`create` method to implement the desired resource. | Pool is a base class that implements resource limitation and construction. It is meant to be subclassed. When subclassing, define only the :meth:`create` method to implement the desired resource:: | def item_impl(self): """ Get an object out of the pool, for use with with statement. >>> from eventlet import pools >>> pool = pools.TokenPool(max_size=4) >>> with pool.item() as obj: ... print "got token" ... got token >>> pool.free() 4 """ obj = self.get() try: yield obj finally: self.put(obj) |
When using the pool, if you do a get, you should **always** do a :meth:`put`. | class MyPool(pools.Pool): def create(self): return MyObject() If using 2.5 or greater, the :meth:`item` method acts as a context manager; that's the best way to use it:: with mypool.item() as thing: thing.dostuff() If stuck on 2.4, the :meth:`get` and :meth:`put` methods are the preferred nomenclature. Use a ``fina... | def item_impl(self): """ Get an object out of the pool, for use with with statement. >>> from eventlet import pools >>> pool = pools.TokenPool(max_size=4) >>> with pool.item() as obj: ... print "got token" ... got token >>> pool.free() 4 """ obj = self.get() try: yield obj finally: self.put(obj) |
The pattern is:: | thing = self.pool.get() try: thing.dostuff() finally: self.pool.put(thing) | def item_impl(self): """ Get an object out of the pool, for use with with statement. >>> from eventlet import pools >>> pool = pools.TokenPool(max_size=4) >>> with pool.item() as obj: ... print "got token" ... got token >>> pool.free() 4 """ obj = self.get() try: yield obj finally: self.put(obj) |
thing = self.pool.get() try: thing.method() finally: self.pool.put(thing) The maximum size of the pool can be modified at runtime via the :attr:`max_size` attribute. Adjusting this number does not affect existing items checked out of the pool, nor on any waiters who are waiting for an item to free up. Some indetermi... | The maximum size of the pool can be modified at runtime via the :meth:`resize` method. Specifying a non-zero *min-size* argument pre-populates the pool with *min_size* items. *max-size* sets a hard limit to the size of the pool -- it cannot contain any more items than *max_size*, and if there are already *max_size* i... | def item_impl(self): """ Get an object out of the pool, for use with with statement. >>> from eventlet import pools >>> pool = pools.TokenPool(max_size=4) >>> with pool.item() as obj: ... print "got token" ... got token >>> pool.free() 4 """ obj = self.get() try: yield obj finally: self.put(obj) |
""" Pre-populates the pool with *min_size* items. Sets a hard limit to the size of the pool -- it cannot contain any more items than *max_size*, and if there are already *max_size* items 'checked out' of the pool, the pool will cause any getter to cooperatively yield until an item is put in. *order_as_stack* governs ... | """*order_as_stack* governs the ordering of the items in the free pool. | def __init__(self, min_size=0, max_size=4, order_as_stack=False): """ Pre-populates the pool with *min_size* items. Sets a hard limit to the size of the pool -- it cannot contain any more items than *max_size*, and if there are already *max_size* items 'checked out' of the pool, the pool will cause any getter to coope... |
"""Return an item from the pool, when one is available | """Return an item from the pool, when one is available. This may cause the calling greenthread to block. | def get(self): """Return an item from the pool, when one is available """ if self.free_items: return self.free_items.popleft() if self.current_size < self.max_size: created = self.create() self.current_size += 1 return created return self.channel.get() |
"""Put an item back into the pool, when done | """Put an item back into the pool, when done. This may cause the putting greenthread to block. | def put(self, item): """Put an item back into the pool, when done """ if self.current_size > self.max_size: self.current_size -= 1 return |
"""Resize the pool | """Resize the pool to *new_size*. Adjusting this number does not affect existing items checked out of the pool, nor on any greenthreads who are waiting for an item to free up. Some indeterminate number of :meth:`get`/:meth:`put` cycles will be necessary before the new maximum size truly matches the actual operation o... | def resize(self, new_size): """Resize the pool """ self.max_size = new_size |
"""Return the number of free items in the pool. | """Return the number of free items in the pool. This corresponds to the number of :meth:`get` calls needed to empty the pool. | def free(self): """Return the number of free items in the pool. """ return len(self.free_items) + self.max_size - self.current_size |
"""Generate a new pool item | """Generate a new pool item. This method must be overridden in order for the pool to function. It accepts no arguments and returns a single instance of whatever thing the pool is supposed to contain. In general, :meth:`create` is called whenever the pool exceeds its previous high-water mark of concurrently-checked-o... | def create(self): """Generate a new pool item """ raise NotImplementedError("Implement in subclass") |
saver = SysModulesSaver(additional_modules.keys()) | saver = SysModulesSaver() | def patched(*args, **kw): saver = SysModulesSaver(additional_modules.keys()) for name, mod in additional_modules: sys.modules[name] = mod try: return func(*args, **kw) finally: saver.restore() |
evt = event.Event() | def test_recv_timeout(self): listener = greenio.GreenSocket(socket.socket()) listener.bind(('', 0)) listener.listen(50) | |
eventlet.sleep(.2) | evt.wait() | def server(): # accept the connection in another greenlet sock, addr = listener.accept() |
eventlet.sleep(.5) | evt.wait() | def server(): # accept the connection in another greenlet sock, addr = listener.accept() sock = bufsized(sock) eventlet.sleep(.5) |
eventlet.sleep(.5) | evt.wait() | def server(): # accept the connection in another greenlet sock, addr = listener.accept() |
def add(self, evtype, fileno, cb): | def add(self, evtype, fileno, real_cb): if isinstance(real_cb, types.BuiltinMethodType): def cb(_d): real_cb(_d) else: cb = real_cb | def add(self, evtype, fileno, cb): if evtype is READ: evt = event.read(fileno, cb, fileno) elif evtype is WRITE: evt = event.write(fileno, cb, fileno) listener = FdListener(evtype, fileno, evt) self.listeners[evtype].setdefault(fileno, []).append(listener) return listener |
self.failUnless("debug_test:%i" % lineno in output, "Didn't find line %i in %s" % (lineno, output)) | self.failUnless("%s:%i" % (__name__, lineno) in output, "Didn't find line %i in %s" % (lineno, output)) | def test_line(self): sys.stdout = StringIO() s = debug.Spew() f = sys._getframe() s(f, "line", None) lineno = f.f_lineno - 1 # -1 here since we called with frame f in the line above output = sys.stdout.getvalue() self.failUnless("debug_test:%i" % lineno in output, "Didn't find line %i in %s" % (lineno, output)) self.fa... |
if sys.version_info >= (2,5): self.failUnless("[unknown]:1" in output, "Didn't find [unknown]:1 in %s" % (output)) else: self.failUnless("[unknown]:0" in output, "Didn't find [unknown]:0 in %s" % (output)) | self.failUnless("[unknown]:%i" % lineno in output, "Didn't find [unknown]:%i in %s" % (lineno, output)) | def test_line_nofile(self): sys.stdout = StringIO() s = debug.Spew() g = globals().copy() del g['__file__'] f = eval("sys._getframe()", g) s(f, "line", None) output = sys.stdout.getvalue() # version-dependent output here if sys.version_info >= (2,5): self.failUnless("[unknown]:1" in output, "Didn't find [unknown]:1 in ... |
self.failUnless("debug_test:%i" % lineno in output, "Didn't find line %i in %s" % (lineno, output)) | self.failUnless("%s:%i" % (__name__, lineno) in output, "Didn't find line %i in %s" % (lineno, output)) | def test_line_global(self): global GLOBAL_VAR sys.stdout = StringIO() GLOBAL_VAR = debug.Spew() f = sys._getframe() GLOBAL_VAR(f, "line", None) lineno = f.f_lineno - 1 # -1 here since we called with frame f in the line above output = sys.stdout.getvalue() self.failUnless("debug_test:%i" % lineno in output, "Didn't find... |
self.failUnless("debug_test:%i" % lineno in output, "Didn't find line %i in %s" % (lineno, output)) | self.failUnless("%s:%i" % (__name__, lineno) in output, "Didn't find line %i in %s" % (lineno, output)) | def test_line_novalue(self): sys.stdout = StringIO() s = debug.Spew(show_values=False) f = sys._getframe() s(f, "line", None) lineno = f.f_lineno - 1 # -1 here since we called with frame f in the line above output = sys.stdout.getvalue() self.failUnless("debug_test:%i" % lineno in output, "Didn't find line %i in %s" % ... |
_communicate = new.function(subprocess_orig.Popen._communicate.im_func.func_code, globals()) | try: _communicate = new.function(subprocess_orig.Popen._communicate.im_func.func_code, globals()) except AttributeError: communicate = new.function(subprocess_orig.Popen.communicate.im_func.func_code, globals()) | def wait(self, check_interval=0.01): # Instead of a blocking OS call, this version of wait() uses logic # borrowed from the eventlet 0.2 processes.Process.wait() method. try: while True: status = self.poll() if status is not None: return status eventlet.sleep(check_interval) except OSError, e: if e.errno == errno.ECHIL... |
check_call = new.function(subprocess_orig.check_call.func_code, globals()) | try: check_call = new.function(subprocess_orig.check_call.func_code, globals()) except AttributeError: pass | def wait(self, check_interval=0.01): # Instead of a blocking OS call, this version of wait() uses logic # borrowed from the eventlet 0.2 processes.Process.wait() method. try: while True: status = self.poll() if status is not None: return status eventlet.sleep(check_interval) except OSError, e: if e.errno == errno.ECHIL... |
return [open(os.path.join( os.path.dirname(__file__), 'websocket_chat.html')).read() % PORT] | html_path = os.path.join(os.path.dirname(__file__), 'websocket_chat.html') return [open(html_path).read() % {'port': PORT}] | def dispatch(environ, start_response): """Resolves to the web page or the websocket depending on the path.""" if environ['PATH_INFO'] == '/chat': return handle(environ, start_response) else: start_response('200 OK', [('content-type', 'text/html')]) return [open(os.path.join( os.path.dirname(__file__), 'websocket_chat.h... |
patched_modules.replace("psycopg,", "") | patched_modules = patched_modules.replace("psycopg,", "") | def assert_boolean_logic(self, call, expected, not_expected=''): expected_list = ", ".join(['"%s"' % x for x in expected.split(',') if len(x)]) not_expected_list = ", ".join(['"%s"' % x for x in not_expected.split(',') if len(x)]) new_mod = """ |
result = t.run() | t.run() | def __call__(self, *args, **kw): #print "first call", args, kw gr = self.gr del gr.switch run, gr.run = gr.run, None t = stackless.tasklet(run) gr.t = t tasklet_to_greenlet[t] = gr t.setup(*args, **kw) result = t.run() |
oldlisteners = bool(self.listeners[READ].get(fileno) or self.listeners[WRITE].get(fileno)) | oldlisteners = bool(self.listeners[evtype].get(fileno)) | def add(self, evtype, fileno, cb): oldlisteners = bool(self.listeners[READ].get(fileno) or self.listeners[WRITE].get(fileno)) listener = super(Hub, self).add(evtype, fileno, cb) if not oldlisteners: # Means we've added a new listener self.register(fileno, new=True) return listener |
self.failUnless("[unknown]:1" in output, "Didn't find [unknown]:1 in %s" % (output)) | if sys.version_info >= (2,5): self.failUnless("[unknown]:1" in output, "Didn't find [unknown]:1 in %s" % (output)) else: self.failUnless("[unknown]:0" in output, "Didn't find [unknown]:0 in %s" % (output)) | def test_line_nofile(self): sys.stdout = StringIO() s = debug.Spew() g = globals().copy() del g['__file__'] f = eval("sys._getframe()", g) s(f, "line", None) output = sys.stdout.getvalue() self.failUnless("[unknown]:1" in output, "Didn't find [unknown]:1 in %s" % (output)) self.failUnless("VM instruction #" in output, ... |
conn = psycopg2.connect() | conn = psycopg2.connect(dsn) | def fetch(num, secs): conn = psycopg2.connect() cur = conn.cursor() for i in range(num): cur.execute("select pg_sleep(%s)", (secs,)) |
_green_time_modules() + _green_MySQLdb()) | _green_time_modules()) | def inject(module_name, new_globals, *additional_modules): """Base method for "injecting" greened modules into an imported module. It imports the module specified in *module_name*, arranging things so that the already-imported modules in *additional_modules* are used when *module_name* makes its imports. *new_globals... |
return BoundedSemaphore(count, limit) | return BoundedSemaphore(count) | def semaphore(count=0, limit=None): warnings.warn("coros.semaphore is deprecated. Please use either " "semaphore.Semaphore or semaphore.BoundedSemaphore instead.", DeprecationWarning, stacklevel=2) if limit is None: return Semaphore(count) else: return BoundedSemaphore(count, limit) |
sys.modules['__patched_module_' + module_name] = module | sys.modules[patched_name] = module | def inject(module_name, new_globals, *additional_modules): """Base method for "injecting" greened modules into an imported module. It imports the module specified in *module_name*, arranging things so that the already-imported modules in *additional_modules* are used when *module_name* makes its imports. *new_globals... |
if e[0] != errno.EHOSTUNREACH: | if not e[0] in (errno.EHOSTUNREACH, errno.ENETUNREACH): | def test_connect_timeout(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.1) gs = greenio.GreenSocket(s) try: gs.connect(('192.0.2.1', 80)) self.fail("socket.timeout not raised") except socket.timeout, e: self.assert_(hasattr(e, 'args')) self.assertEqual(e.args[0], 'timed out') except socket.... |
self.assertEquals(e, errno.EAGAIN) | if not e in (errno.EHOSTUNREACH, errno.ENETUNREACH): self.assertEquals(e, errno.EAGAIN) | def test_connect_ex_timeout(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.1) gs = greenio.GreenSocket(s) e = gs.connect_ex(('192.0.2.1', 80)) self.assertEquals(e, errno.EAGAIN) |
except Exception, e: | except Exception: | def test_run_bad_query(self): cursor = self.connection.cursor() try: cursor.execute("garbage blah blah") self.assert_(False) except AssertionError: raise except Exception, e: pass cursor.close() |
evt2 = event.Event() | def a_query(): self.assert_cursor_works(curs) curs.execute(SHORT_QUERY) results.append(2) evt.send() | |
except (IOError, ImportError), e: | except (IOError, ImportError): | def get_auth(): """Looks in the local directory and in the user's home directory for a file named ".test_dbauth", which contains a json map of parameters to the connect function. """ files = [os.path.join(os.path.dirname(__file__), '.test_dbauth'), os.path.join(os.path.expanduser('~'), '.test_dbauth')] for f in files: ... |
print "Skipping mysql tests, error when connecting" | print >> sys.stderr, ">> Skipping mysql tests, error when connecting:" | def mysql_requirement(_f): try: import MySQLdb try: auth = get_auth()['MySQLdb'].copy() MySQLdb.connect(**auth) return True except MySQLdb.OperationalError: print "Skipping mysql tests, error when connecting" import traceback traceback.print_exc() return False except ImportError: print "Skipping mysql tests, MySQLdb no... |
print "Skipping mysql tests, MySQLdb not importable" | print >> sys.stderr, ">> Skipping mysql tests, MySQLdb not importable" | def mysql_requirement(_f): try: import MySQLdb try: auth = get_auth()['MySQLdb'].copy() MySQLdb.connect(**auth) return True except MySQLdb.OperationalError: print "Skipping mysql tests, error when connecting" import traceback traceback.print_exc() return False except ImportError: print "Skipping mysql tests, MySQLdb no... |
dbname = auth.pop('database') | def drop_db(self): auth = self._auth.copy() dbname = auth.pop('database') conn = self._dbmodule.connect(**auth) conn.set_isolation_level(0) db = conn.cursor() db.execute("drop database "+self._auth['database']) db.close() del db | |
towrite.append("0\r\n") | towrite.append("0\r\n\r\n") | def write(data, _writelines=wfile.writelines): towrite = [] if not headers_set: raise AssertionError("write() before start_response()") elif not headers_sent: status, response_headers = headers_set headers_sent.append(1) header_list = [header[0].lower() for header in response_headers] towrite.append('%s %s\r\n' % (self... |
curthread = mod._active.pop(mod.current_thread()._Thread__ident, None) | curthread = mod._active.pop(mod._get_ident(), None) | def _patch_main_thread(mod): # this is some gnarly patching for the threading module; # if threading is imported before we patch (it nearly always is), # then the main thread will have the wrong key in therading._active, # so, we try and replace that key with the correct one here # this works best if there are no other... |
response = loads(str) except (AttributeError, DeadProcess), e: | response = Pickle.loads(str) except (AttributeError, DeadProcess, Pickle.UnpicklingError), e: | def _read_response(id, attribute, input, cp): """local helper method to read respones from the rpc server.""" try: str = _read_lp_hunk(input) _prnt(`str`) response = loads(str) except (AttributeError, DeadProcess), e: raise UnrecoverableError(e) _prnt("response: %s" % response) if response[0] == 'value': return respons... |
str = dumps(param) | str = Pickle.dumps(param) | def _write_request(param, output): _prnt("request: %s" % param) str = dumps(param) _write_lp_hunk(output, str) |
request = loads(str_) | request = Pickle.loads(str_) | def loop(self): """Loop forever and respond to all requests.""" _log("Server::loop") while True: try: try: str_ = _read_lp_hunk(self._in) except EOFError: if _g_debug_mode: _log("Exiting normally") sys.exit(0) |
s = dumps(body) | s = Pickle.dumps(body) | def respond(self, body): _log("responding with: %s" % body) #_log("objects: %s" % self._objects) s = dumps(body) _log(`s`) str_ = _write_lp_hunk(self._out, s) |
self.assertEqual(lines[0].replace("psycopg", ""), | self.assertEqual(lines[0].replace("psycopg,", ""), | def test_monkey_patching(self): output, lines = self.run_script(""" |
class DummyModule(object): pass def make_original(modname): orig_mod = __import__(modname) dummy_mod = DummyModule() for attr in dir(orig_mod): setattr(dummy_mod, attr, getattr(orig_mod, attr)) _originals[modname] = dummy_mod | def patched(*args, **kw): saved = {} for name, mod in additional_modules: saved[name] = sys.modules.get(name, None) sys.modules[name] = mod try: return func(*args, **kw) finally: ## Put all the saved modules back for name, mod in additional_modules: if saved[name] is not None: sys.modules[name] = saved[name] else: del ... | |
make_original(modname) mod = _originals.get(modname) return mod | current_mod = sys.modules.pop(modname, None) try: real_mod = __import__(modname, {}, {}, modname.split('.')[:-1]) _originals[modname] = real_mod finally: if current_mod is not None: sys.modules[modname] = current_mod return _originals.get(modname) | def original(modname): mod = _originals.get(modname) if mod is None: make_original(modname) mod = _originals.get(modname) return mod |
make_original('select') | def monkey_patch(all=True, os=False, select=False, socket=False, thread=False, time=False): """Globally patches certain system modules to be greenthread-friendly. The keyword arguments afford some control over which modules are patched. If *all* is True, then all modules are patched regardless of the other arguments. ... | |
make_original('threading') | def monkey_patch(all=True, os=False, select=False, socket=False, thread=False, time=False): """Globally patches certain system modules to be greenthread-friendly. The keyword arguments afford some control over which modules are patched. If *all* is True, then all modules are patched regardless of the other arguments. ... | |
make_original('time') | def monkey_patch(all=True, os=False, select=False, socket=False, thread=False, time=False): """Globally patches certain system modules to be greenthread-friendly. The keyword arguments afford some control over which modules are patched. If *all* is True, then all modules are patched regardless of the other arguments. ... | |
except ValueError: raise socket.gaierror(-2, 'name or service not known') | except (ValueError, TypeError): if not isinstance(sockaddr, tuple): del sockaddr raise TypeError('getnameinfo() argument 1 must be a tuple') else: raise socket.gaierror(-2, 'name or service not known') | def getnameinfo(sockaddr, flags): """Replacement for Python's socket.getnameinfo. Currently only supports IPv4. """ try: host, port = sockaddr except ValueError: # must be ipv6 sockaddr, pretending we don't know how to resolve it raise socket.gaierror(-2, 'name or service not known') if (flags & socket.NI_NAMEREQD) a... |
assert not hasattr(_threadlocal, 'hub') import os os.environ['EVENTLET_HUB'] = 'zeromq' | def assert_different(ctx): assert not hasattr(_threadlocal, 'hub') import os os.environ['EVENTLET_HUB'] = 'zeromq' hub = get_hub() try: this_thread_context = hub.get_context() except: test_result.append('fail') raise test_result.append(ctx is this_thread_context) | |
count = 0 while count < 100 and not test_result: count += 1 | while not test_result: sleep(0.1) | def assert_different(ctx): assert not hasattr(_threadlocal, 'hub') import os os.environ['EVENTLET_HUB'] = 'zeromq' hub = get_hub() try: this_thread_context = hub.get_context() except: test_result.append('fail') raise test_result.append(ctx is this_thread_context) |
os.environ['EVENTLET_HUB'] = 'selects' try: self.write_to_tempfile("newmod", new_mod) output, lines = self.launch_subprocess('newmod.py') self.assertEqual(len(lines), 2, "\n".join(lines)) self.assert_("selects" in lines[0]) finally: del os.environ['EVENTLET_HUB'] | self.write_to_tempfile("newmod", new_mod) output, lines = self.launch_subprocess('newmod.py') self.assertEqual(len(lines), 2, "\n".join(lines)) self.assert_("selects" in lines[0]) | def test_eventlet_hub(self): new_mod = """from eventlet import hubs |
self.canceled_timers = 0 | self.timers_canceled = 0 | def run(self): """Run the runloop until abort is called. """ if self.running: raise RuntimeError("Already running!") try: self.running = True self.stopping = False while not self.stopping: self.prepare_timers() if self.debug_blocking: self.block_detect_pre() self.fire_timers(self.clock()) if self.debug_blocking: self.b... |
def cursor(self, cursorclass=None, **kwargs): return self._base.cursor(cursorclass, **kwargs) | def cursor(self, *args, **kwargs): return self._base.cursor(*args, **kwargs) | def cursor(self, cursorclass=None, **kwargs): return self._base.cursor(cursorclass, **kwargs) |
def errorhandler(self, conn, curs, errcls, errval): return self._base.errorhandler(conn, curs, errcls, errval) def literal(self, o): return self._base.literal(o) def set_character_set(self, charset): return self._base.set_character_set(charset) def set_sql_mode(self, sql_mode): return self._base.set_sql_mode(sql_mode) | def errorhandler(self, *args, **kwargs): return self._base.errorhandler(conn, curs, errcls, errval) def literal(self, *args, **kwargs): return self._base.literal(*args, **kwargs) def set_character_set(self, *args, **kwargs): return self._base.set_character_set(*args, **kwargs) def set_sql_mode(self, *args, **kwargs): r... | def errorhandler(self, conn, curs, errcls, errval): return self._base.errorhandler(conn, curs, errcls, errval) |
d = self.fd.read(BUFFER_SIZE) | d = self.read(BUFFER_SIZE) | def readuntil(self, terminator, size=None): buf, self.recvbuffer = self.recvbuffer, '' checked = 0 if size is None: while True: found = buf.find(terminator, checked) if found != -1: found += len(terminator) chunk, self.recvbuffer = buf[:found], buf[found:] return chunk checked = max(0, len(buf) - (len(terminator) - 1))... |
self.tempfiles = [] | self.tempdir = tempfile.mkdtemp('_patcher_test') | def setUp(self): self._saved_syspath = sys.path self.tempfiles = [] |
for tf in self.tempfiles: os.remove(tf) | shutil.rmtree(self.tempdir) | def tearDown(self): sys.path = self._saved_syspath for tf in self.tempfiles: os.remove(tf) |
def write_to_tempfile(self, contents): fn, filename = tempfile.mkstemp('_patcher_test.py') fd = os.fdopen(fn, 'w') | def write_to_tempfile(self, name, contents): filename = os.path.join(self.tempdir, name + '.py') fd = open(filename, "w") | def write_to_tempfile(self, contents): fn, filename = tempfile.mkstemp('_patcher_test.py') fd = os.fdopen(fn, 'w') fd.write(contents) fd.close() self.tempfiles.append(filename) return os.path.dirname(filename), os.path.basename(filename) |
self.tempfiles.append(filename) return os.path.dirname(filename), os.path.basename(filename) | def write_to_tempfile(self, contents): fn, filename = tempfile.mkstemp('_patcher_test.py') fd = os.fdopen(fn, 'w') fd.write(contents) fd.close() self.tempfiles.append(filename) return os.path.dirname(filename), os.path.basename(filename) | |
if socket_connect(fd, address): return 0 if time.time() >= end: raise socket.timeout(errno.EAGAIN) | def connect_ex(self, address): if self.act_non_blocking: return self.fd.connect_ex(address) fd = self.fd if self.gettimeout() is None: while not socket_connect(fd, address): try: trampoline(fd, write=True) except socket.error, ex: return ex[0] else: end = time.time() + self.gettimeout() while True: if socket_connect(fd... | |
if my_thread in _threads: | if my_thread in _threads or imp.lock_held(): | def execute(meth,*args, **kwargs): """ Execute *meth* in a Python thread, blocking the current coroutine/ greenthread until the method completes. The primary use case for this is to wrap an object or module that is not amenable to monkeypatching or any of the other tricks that Eventlet uses to achieve cooperative yiel... |
sleep(0.2) | def test_send_1k_pub_sub(self): pub, sub_all, port = self.create_bound_pair(zmq.PUB, zmq.SUB) sub1 = self.context.socket(zmq.SUB) sub2 = self.context.socket(zmq.SUB) self.sockets.extend([sub1, sub2]) addr = 'tcp://127.0.0.1:%s' % port sub1.connect(addr) sub2.connect(addr) sub_all.setsockopt(zmq.SUBSCRIBE, '') sub1.sets... | |
sleep(0.2) | def test_change_subscription(self): pub, sub, port = self.create_bound_pair(zmq.PUB, zmq.SUB) sub.setsockopt(zmq.SUBSCRIBE, 'test') | |
if sub == 'done': | sleep() if 'DONE' in msg: | def rx(sock, done_evt): count = 0 sub = 'test' while True: msg = sock.recv() if sub == 'done': break if 'LAST' in msg and sub == 'test': sock.setsockopt(zmq.UNSUBSCRIBE, 'test') sock.setsockopt(zmq.SUBSCRIBE, 'done') sub = 'done' count += 1 done_evt.send(count) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.