rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
def fetch(): return self.client.fetchFlags(self.messages, uid=uid) | self.function = self.client.fetchFlags | def fetch(): return self.client.fetchFlags(self.messages, uid=uid) |
self._fetchWork(fetch, uid) | self._fetchWork(uid) | def fetch(): return self.client.fetchFlags(self.messages, uid=uid) |
def fetch(): return self.client.fetchInternalDate(self.messages, uid=uid) | self.function = self.client.fetchInternalDate | def fetch(): return self.client.fetchInternalDate(self.messages, uid=uid) |
self.msgObjs = [FakeyMessage({}, (), 'Tuesday', '', 23232, None)] self.expected = {0: {'INTERNALDATE': 'Tuesday'}} self._fetchWork(fetch, uid) | self.msgObjs = [ FakeyMessage({}, (), 'Tuesday', '', 23232, None), FakeyMessage({}, (), '20-Oct-1981 03:25:19 -0500', '', 101, None), FakeyMessage({}, (), '15-Feb-1985 01:30:05 +0900', '', 202, None), FakeyMessage({}, (), '01-Jun-1992 13:51:48 -0100', '', 303, None), ] self.expected = { 0: {'INTERNALDATE': 'Tuesday'}, ... | def fetch(): return self.client.fetchInternalDate(self.messages, uid=uid) |
def fetch(): return self.client.fetchEnvelope(self.messages, uid=uid) | self.function = self.client.fetchEnvelope | def fetch(): return self.client.fetchEnvelope(self.messages, uid=uid) |
self.msgObjs = [FakeyMessage({'from': 'user@domain', 'to': 'resu@domain', 'date': 'thursday', 'subject': 'it is a message', 'message-id': 'id-id-id-yayaya'}, (), '', '', 65656, None)] self.expected = {0: {'ENVELOPE': [ 'thursday', 'it is a message', [[None, None, 'user', 'domain']], [[None, None, 'user', 'domain']], [[... | self.msgObjs = [ FakeyMessage({ 'from': 'user@domain', 'to': 'resu@domain', 'date': 'thursday', 'subject': 'it is a message', 'message-id': 'id-id-id-yayaya'}, (), '', '', 65656, None), ] self.expected = { 0: {'ENVELOPE': ['thursday', 'it is a message', [[None, None, 'user', 'domain']], [[None, None, 'user', 'domain']]... | def fetch(): return self.client.fetchEnvelope(self.messages, uid=uid) |
def fetch(): return self.client.fetchBodyStructure(self.messages, uid=uid) | self.function = self.client.fetchBodyStructure | def fetch(): return self.client.fetchBodyStructure(self.messages, uid=uid) |
self._fetchWork(fetch, uid) | self._fetchWork(uid) | def fetch(): return self.client.fetchBodyStructure(self.messages, uid=uid) |
def fetch(): return self.client.fetchSimplifiedBody(self.messages, uid=uid) | self.function = self.client.fetchSimplifiedBody | def fetch(): return self.client.fetchSimplifiedBody(self.messages, uid=uid) |
self._fetchWork(fetch, uid) | self._fetchWork(uid) | def fetch(): return self.client.fetchSimplifiedBody(self.messages, uid=uid) |
def testFetchMessage(self, uid=0): self.function = self.client.fetchMessage self.messages = '1,3,7,10101' self.msgObjs = [ FakeyMessage({'Header': 'Value'}, (), '', 'BODY TEXT\r\n', 91, None), ] self.expected = { 0: {'RFC822': 'Header: Value\r\nBODY TEXT\r\n'} } self._fetchWork(uid) def testFetchMessageUID(self): self... | def testFetchSimplifiedBodyRFC822UID(self): self.testFetchSimplifiedBodyRFC822(1) | |
def testFetchUID(self): def fetch(): return self.client.fetchUID(self.messages) self.expected = { 1: {'UID': '10'}, 2: {'UID': '20'}, 3: {'UID': '21'}, 4: {'UID': '101'}, 101: {'UID': '202'} } self.messages = '1:56,60,103:109' self.parts = ['UID'] self.uid = 0 self._fetchWork(fetch) def testFetchFlags(self, uid=0): d... | def testFetchUID(self): def fetch(): return self.client.fetchUID(self.messages) self.expected = { 1: {'UID': '10'}, 2: {'UID': '20'}, 3: {'UID': '21'}, 4: {'UID': '101'}, 101: {'UID': '202'} } self.messages = '1:56,60,103:109' self.parts = ['UID'] self.uid = 0 self._fetchWork(fetch) | |
p.control(_epoll.CTL_ADD, client.fileno(), _epoll.IN | _epoll.OUT) p.control(_epoll.CTL_ADD, server.fileno(), _epoll.IN | _epoll.OUT) | p.control(_epoll.CTL_ADD, client.fileno(), _epoll.IN | _epoll.OUT | _epoll.ET) p.control(_epoll.CTL_ADD, server.fileno(), _epoll.IN | _epoll.OUT | _epoll.ET) | def testControlAndWait(self): port = socket.socket() port.bind(('127.0.0.1', 0)) port.listen(1) |
events = p.wait(4, 1) | events = p.wait(4, 1000) | def testControlAndWait(self): port = socket.socket() port.bind(('127.0.0.1', 0)) port.listen(1) |
self.assertEquals(events, [(client.fileno(), _epoll.OUT), (server.fileno(), _epoll.OUT)]) | self.assertEquals( dict(events), {client.fileno(): _epoll.OUT, server.fileno(): _epoll.OUT}) | def testControlAndWait(self): port = socket.socket() port.bind(('127.0.0.1', 0)) port.listen(1) |
events = p.wait(4, 1) | events = p.wait(4, 200) | def testControlAndWait(self): port = socket.socket() port.bind(('127.0.0.1', 0)) port.listen(1) |
self.failUnless(then - now > 1) | self.failUnless(then - now > 0.1) | def testControlAndWait(self): port = socket.socket() port.bind(('127.0.0.1', 0)) port.listen(1) |
self.assertEquals(events, [(client.fileno(), _epoll.IN | _epoll.OUT), (server.fileno(), _epoll.IN | _epoll.OUT)]) | events.sort() self.assertEquals( dict(events), {client.fileno(): _epoll.IN | _epoll.OUT, server.fileno(): _epoll.IN | _epoll.OUT}) | def testControlAndWait(self): port = socket.socket() port.bind(('127.0.0.1', 0)) port.listen(1) |
if self._listenerDict.has_key((port_, interface_)): self._listenerDict[port_,interface_].stopListening() | if self._listenerDict.has_key((port, interface)): self._listenerDict[(port, interface)].stopListening() | def unlistenTCP(self, port, interface=''): toRemove = [] for t in self.tcpPorts: port_, factory_, backlog_, interface_ = t if port == port_ and interface == interface_: toRemove.append(t) if toRemove: for t in toRemove: self.tcpPorts.remove(t) if self._listenerDict.has_key((port_, interface_)): self._listenerDict[port_... |
if self._listenerDict.has_key((filename_)): self._listenerDict[filename_].stopListening() | if self._listenerDict.has_key(filename): self._listenerDict[filename].stopListening() | def unlistenUNIX(self, filename): toRemove = [] for t in self.unixPorts: filename_, factory_, backlog_, mode_ = t if filename == filename_: toRemove.append(t) if toRemove: for t in toRemove: self.unixPorts.remove(t) if self._listenerDict.has_key((filename_)): self._listenerDict[filename_].stopListening() else: raise er... |
if node.getAttribute('class') == 'API': | if node.getAttribute('class') == 'API' and not self.filename.startswith('glossary'): | def visitNode_code(self, node): fout = StringIO() getLatexText(node, fout.write, latexEscape) data = fout.getvalue() # Automatically fully-qualify the first (and only the first) mention of # APIs, i.e turn "pb.Root" into "twisted.spread.pb.Root". if node.getAttribute('class') == 'API': base = node.getAttribute('base',... |
externalhref = 1 | external = 1 | def visitNode_a_href(self, node): href = node.getAttribute('href') externalhref = None if href.startswith('http://') or href.startswith('https://'): externalhref = 1 # If the text of the link is the url already, don't bother # repeating the url. if node.childNodes[0].data == href: return externalhref = '\\footnote{%s}'... |
if node.childNodes[0].data == href: return externalhref = '\\footnote{%s}' % latexEscape(href) | if node.childNodes[0].data != href: externalhref = '\\footnote{%s}' % latexEscape(href) | def visitNode_a_href(self, node): href = node.getAttribute('href') externalhref = None if href.startswith('http://') or href.startswith('https://'): externalhref = 1 # If the text of the link is the url already, don't bother # repeating the url. if node.childNodes[0].data == href: return externalhref = '\\footnote{%s}'... |
elif not externalhref: | elif not external: | def visitNode_a_href(self, node): href = node.getAttribute('href') externalhref = None if href.startswith('http://') or href.startswith('https://'): externalhref = 1 # If the text of the link is the url already, don't bother # repeating the url. if node.childNodes[0].data == href: return externalhref = '\\footnote{%s}'... |
mapStart_li = mapStart_ul = '\\item ' mapEnd_li = mapEnd_ul = '\n' | mapStart_li = '\\item ' mapEnd_li = '\n' | def visitNode_table(self, node): # All of my children should be <tr> elements numCols = 0 for child in node.childNodes: numCols = max(numCols, len(child.childNodes)) numCols += 1 self.writer('\\begin{table}[ht]\\begin{center}') self.writer('\\begin{tabular}{@{}'+'l'*numCols+'@{}}') for child in node.childNodes: th = 0 ... |
return proto.list("", "" | return proto.list("", "*" | def cbAuthentication(result, proto): # List a bunch of mailboxes return proto.list("", "" ).addCallback(cbMailboxList, proto ) |
import threadpool | from twisted.python import threadpool | def suggestThreadPoolSize(size): """Suggest the maximum size of the thread pool.""" if not theThreadPool: _initThreading() oldSize = theThreadPool.max theThreadPool.max = size if oldSize > size: import threadpool for i in range(oldSize - size): theThreadPool.q.put(threadpool.WorkerStop) else: theThreadPool._startSomeWo... |
% (self, resc)) | % (self, resrc)) | def process(self): "Process a request." # Log the request to a file. log.msg( self ) |
assert callable(f) | assert callable(f), "%s is not callable" % f | def addSystemEventTrigger(self, phase, eventType, f, *args, **kw): """See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger. """ assert callable(f) if self._eventTriggers.has_key(eventType): triglist = self._eventTriggers[eventType] else: triglist = [[], [], []] self._eventTriggers[eventType] = triglist ev... |
assert callable(f) | assert callable(f), "%s is not callable" % f | def callLater(self, seconds, f, *args, **kw): """See twisted.internet.interfaces.IReactorTime.callLater. """ assert callable(f) assert seconds >= 0 tple = DelayedCall(time() + seconds, f, args, kw, self._pendingTimedCalls.remove, self._resetCallLater) insort(self._pendingTimedCalls, tple) return tple |
self.assertIn( "I'm a test drop-in.", dropin.description.strip()) | self.assertNotEquals(dropin.description.find("I'm a test drop-in."), -1) | def _testCache(self): cache = plugin.getCache(plugins) |
if string.lower(name) == keyColumn: | if name == keyColumn.lower(): | def getKeyColumn(rowClass, name): for keyColumn, type in rowClass.rowKeyColumns: if string.lower(name) == keyColumn: return name return None |
columnName = rowClass.dbColumns[i][0] | columnName = rowClass.dbColumns[i][0].lower() | def makeKW(rowClass, args): """Utility method to construct a dictionary for the attributes of an object from set of args. This also fixes the case of column names. """ kw = {} for i in range(0,len(args)): columnName = rowClass.dbColumns[i][0] for attr in rowClass.rowColumns: if string.lower(attr) == string.lower(column... |
if string.lower(attr) == string.lower(columnName): | if attr.lower() == columnName: | def makeKW(rowClass, args): """Utility method to construct a dictionary for the attributes of an object from set of args. This also fixes the case of column names. """ kw = {} for i in range(0,len(args)): columnName = rowClass.dbColumns[i][0] for attr in rowClass.rowColumns: if string.lower(attr) == string.lower(column... |
if self.tagName and str(node.tagName) != self.tagName: | if node is not self.templateNode: | def generateDOM(self, request, node): """ @returns: A DOM Node to replace the Node in the template that this Widget handles. This Node is created based on L{tagName}, L{children}, and L{attributes} (You should populate these in L{setUp}, probably). """ if DEBUG: template = node.toxml() log.msg(template) if self.tagName... |
self.producer = producer | def registerProducer(self, producer, streaming): """Register a producer.""" self.producer = producer self.streamingProducer = streaming if self.queued: producer.pauseProducing() else: self.transport.registerProducer(producer, streaming) | |
reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None, | def fixup(l): for path in l: if os.path.isabs(path): yield path else: yield os.path.join(os.path.pardir, path) env = {"PYTHONPATH": os.pathsep.join(fixup(sys.path))} reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=env, | def testStdio(self): """twisted.internet.stdio test.""" exe = sys.executable scriptPath = util.sibpath(__file__, "process_twisted.py") p = Accumulator() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None, path=None, usePTY=self.usePTY) p.transport.write("hello, world") p.transport.write("abc") p.transport.w... |
args.update( cgi.parse_multipart(self.content, pdict)) | try: args.update(cgi.parse_multipart(self.content, pdict)) except KeyError, e: if e.args[0] == 'content-dispostion': self.channel.transport.write( "HTTP/1.1 400 Bad Request\r\n\r\n") self.channel.transport.loseConnection() return raise | def requestReceived(self, command, path, version): """Called by channel when all data has been received. |
controllerFactory = getattr(self.controller, 'factory_' + controllerName, None) | controllerFactory = getattr(namespace, 'factory_' + controllerName, None) | def getNodeController(self, request, node): controllerName = node.getAttribute('controller') # Look up an InputHandler controllerFactory = DefaultHandler if controllerName: namespaces = [self.controller] for namespace in namespaces: controllerFactory = getattr(self.controller, 'factory_' + controllerName, None) if con... |
controllerFactory = getattr(dominput, controllerName, None) | controllerFactory = getattr(input, controllerName, None) | def getNodeController(self, request, node): controllerName = node.getAttribute('controller') # Look up an InputHandler controllerFactory = DefaultHandler if controllerName: namespaces = [self.controller] for namespace in namespaces: controllerFactory = getattr(self.controller, 'factory_' + controllerName, None) if con... |
raise NotImplementedError, "You specified controller name %s on a node, but no factory_%s method was found." % (controllerName, controllerName) | raise NotImplementedError, "You specified controller name %s on a node, but no factory_%s method was found in %s." % (controllerName, controllerName, namespaces + [input]) | def getNodeController(self, request, node): controllerName = node.getAttribute('controller') # Look up an InputHandler controllerFactory = DefaultHandler if controllerName: namespaces = [self.controller] for namespace in namespaces: controllerFactory = getattr(self.controller, 'factory_' + controllerName, None) if con... |
raise NotImplementedError, "You specified view name %s on a node, but no factory_%s method was found." % (viewName, viewName) | raise NotImplementedError, "You specified view name %s on a node, but no factory_%s method was found in %s or %s." % (viewName, viewName, self, widgets) | def getNodeView(self, request, node): view = None viewName = node.getAttribute('view') |
def __init__(self, port, protocol, interface='', maxPacketSize=8192, reactor=None): | def __init__(self, port, proto, interface='', maxPacketSize=8192, reactor=None): | def __init__(self, port, protocol, interface='', maxPacketSize=8192, reactor=None): """Initialize with a numeric port to listen on. """ base.BasePort.__init__(self, reactor) self.port = port self.protocol = protocol self.maxPacketSize = maxPacketSize self.interface = interface self.setLogStr() |
self.protocol = protocol | self.protocol = proto | def __init__(self, port, protocol, interface='', maxPacketSize=8192, reactor=None): """Initialize with a numeric port to listen on. """ base.BasePort.__init__(self, reactor) self.port = port self.protocol = protocol self.maxPacketSize = maxPacketSize self.interface = interface self.setLogStr() |
def __init__(self, (remotehost, remoteport), port, protocol, interface='', maxPacketSize=8192, reactor=None): Port.__init__(self, port, protocol, interface, maxPacketSize, reactor) | def __init__(self, (remotehost, remoteport), port, proto, interface='', maxPacketSize=8192, reactor=None): assert isinstance(proto, protocol.ConnectedDatagramProtocol) Port.__init__(self, port, proto, interface, maxPacketSize, reactor) | def __init__(self, (remotehost, remoteport), port, protocol, interface='', maxPacketSize=8192, reactor=None): Port.__init__(self, port, protocol, interface, maxPacketSize, reactor) self.remotehost = remotehost self.remoteport = remoteport |
All attributes besides '__double_underscored__' attributes are RemoteMethod instances; these act like methods which return Deferreds. | All attributes besides '__double_underscored__' attributes and attributes beginning with 'local_' are RemoteMethod instances; these act like methods which return Deferreds. Methods beginning with 'local_' are methods that run locally on the instance. | def __init__(self, object, messageType="remote"): """Initialize me with an object. """ self.remoteMessageReceived = getattr(object, messageType + "MessageReceived") |
self.disconnectCallbacks = [] def local_notifyOnDisconnect(self, callback): """Register a callback to be called if our broker gets disconnected. This callback will be called with one method, this instance. """ assert callable(callback) self.disconnectCallbacks.append(callback) if len(self.disconnectCallbacks): self.b... | def __init__(self, perspective, broker, luid, doRefCount): """(internal) Initialize me with a broker and a locally-unique ID. | |
if key[:2]=='__' and key[-2:]=='__': | if (key[:2]=='__' and key[-2:]=='__') or key[:6] == 'local_': | def __getattr__(self, key): """Get a RemoteMethod for this key. """ |
if message == '__ping__': result = (object is not None) else: netResult = object.remoteMessageReceived(self, message, netArgs, netKw) | netResult = object.remoteMessageReceived(self, message, netArgs, netKw) | def _recvMessage(self, findObjMethod, requestID, objectID, message, answerRequired, netArgs, netKw): """Received a message-send. |
self.eb("connection lost") | self.deferred.armAndErrback("connection lost") | def connectionLost(self): if not self.term: self.term = 1 del self.broker self.eb("connection lost") |
self.logInAs(participant, self.paswd) | self.logInAs(participant, self.passwd) | def irc_NICK(self, prefix, params): """Nick message -- Set your nickname. |
log.msg(buffer_dump(self.buf, title = 'encrypted:\t')) log.msg(buffer_dump(first, title = 'plain:\t')) | def getPacket(self): bs = self.currentEncryptions and self.currentEncryptions.dec_block_size or 8 if len(self.buf) < bs: return # not enough data if not hasattr(self, 'first'): if self.currentEncryptions: first = self.currentEncryptions.decrypt(self.buf[:bs]) else: first = self.buf[:bs] else: first = self.first del se... | |
self.socket.close() | self.socket.shutdown(2) | def connectionLost(self): """See abstract.FileDescriptor.connectionLost(). """ abstract.FileDescriptor.connectionLost(self) self.socket.close() protocol = self.protocol del self.protocol del self.socket del self.fileno protocol.connectionLost() |
declarations.directlyProvides(origInterface, IMarker) | declarations.classImplements(origInterface, IMarker) | def registerAdapter(self, adapterFactory, origInterface, *interfaceClasses): """Register an adapter class. |
def setUp(self): self.msgs = [] self.p = FakeProtocol(self.msgs) def testSingleLevel(self): host = 'domain.tld' m = dns.Message() rr = dns.RRHeader('tld', dns.NS, payload=dns.Record_NS(host)) m.answers.append(rr) self.msgs.append(m) m = dns.Message() rr = dns.RRHeader(host, dns.NS, payload=dns.Record_NS(host)) m.ans... | pass | def setUp(self): self.msgs = [] self.p = FakeProtocol(self.msgs) |
if self.chunked: self.transport.write(toChunk(data)) else: self.transport.write(data) | if data: if self.chunked: self.transport.write(toChunk(data)) else: self.transport.write(data) else: log.msg("(harmless warning): discarding zero-length data for request %s" % self) | def write(self, data): """ Write some data as a result of an HTTP request. The first time this is called, it writes out response data. """ if not self.startedWriting: self.startedWriting = 1 if self.clientproto != "HTTP/0.9": message = RESPONSES.get(self.code, "Unknown Status") self._sendStatus(self.code, message) # i... |
@return true if and only if s is a canonical IPv4 address | @return: true if and only if s is a canonical IPv4 address | def is_ipv4(s): """ @return true if and only if s is a canonical IPv4 address """ ns = string.split(s, '.') if len(ns) != 4: return false os = map(int, ns) if len(filter(lambda x: (x >= 0) and (x < 256), os)) != 4: return false if string.join(map(str, os), '.') != s: return false return true |
def queryHitReceived(self, descriptorId, ttl, hops, ipAddress, port, resultSet, serventIdentifer, speed): | def queryHitReceived(self, descriptorId, ttl, hops, ipAddress, port, resultSet, serventIdentifier, speed): | def queryHitReceived(self, descriptorId, ttl, hops, ipAddress, port, resultSet, serventIdentifer, speed): """ Override this to handle query hit messages. |
def pushReceived(descriptorId, ttl, hops, ipAddress, port, serventIdentifer, fileIndex): | def pushReceived(descriptorId, ttl, hops, ipAddress, port, serventIdentifier, fileIndex): | def pushReceived(descriptorId, ttl, hops, ipAddress, port, serventIdentifer, fileIndex): """ Override this to handle push messages. Precondition: descriptorId must be a string of length DESCRIPTORLENGTH.: (type(descriptorId) is types.StringType) and (len(descriptorId) == DESCRIPTORLENGTH): "descriptorId: %s :: %s" % (... |
self.queryHitReceived(descriptorId, ttl, hops, ipAddress, port, resultSet, serventIdentifer, speed) | self.queryHitReceived(descriptorId, ttl, hops, ipAddress, port, resultSet, serventIdentifier, speed) | def handleQueryHit(self, descriptorId, ttl, hops, payload): try: (numberOfHits, port, ipA0, ipA1, ipA2, ipA3, speed,) = struct.unpack(PARTIALQUERYHITPAYLOADENCODING, payload[:PARTIALQUERYHITPAYLOADLENGTH]) except struct.error, le: self._abortConnection("Received ill-formatted QueryHit payload. Closing connection. pay... |
(serventIdentifer, fileIndex, ipA0, ipA1, ipA2, ipA3, port,) = struct.unpack(PUSHPAYLOADENCODING, payload) | (serventIdentifier, fileIndex, ipA0, ipA1, ipA2, ipA3, port,) = struct.unpack(PUSHPAYLOADENCODING, payload) | def handlePush(self, descriptorId, ttl, hops, payload): try: (serventIdentifer, fileIndex, ipA0, ipA1, ipA2, ipA3, port,) = struct.unpack(PUSHPAYLOADENCODING, payload) except struct.error, le: self._abortConnection("Received ill-formatted Push payload. Closing connection. i: %s, ill-formed part of query hit payload: ... |
self.pushReceived(descriptorId, ttl, hops, ipAddress, port, serventIdentifer, fileIndex) | self.pushReceived(descriptorId, ttl, hops, ipAddress, port, serventIdentifier, fileIndex) | def handlePush(self, descriptorId, ttl, hops, payload): try: (serventIdentifer, fileIndex, ipA0, ipA1, ipA2, ipA3, port,) = struct.unpack(PUSHPAYLOADENCODING, payload) except struct.error, le: self._abortConnection("Received ill-formatted Push payload. Closing connection. i: %s, ill-formed part of query hit payload: ... |
print "Received:" + repr(datagram) | if datagram == 'UniqueID': print "Server Received:" + repr(datagram) self.transport.write("data", address) | def datagramReceived(self, datagram, address): print "Received:" + repr(datagram) |
reactor.listenUDP(0, MulticastClientUDP()).write('UniqueID', ('224.0.0.1', 8005)) | reactor.listenMulticast(8005, MulticastServerUDP()) | def datagramReceived(self, datagram, address): print "Received:" + repr(datagram) |
if sys.version_info[:2] > (2, 2): | if sys.version_info[:2] > (2, 2) and not config['nothotshot']: | def runReactorWithLogging(config, oldstdout, oldstderr): from twisted.internet import reactor try: if config['profile']: if sys.version_info[:2] > (2, 2): runWithHotshot(reactor, config) else: runWithProfiler(reactor, config) elif config['debug']: failure.startDebugMode() sys.stdout = oldstdout sys.stderr = oldstderr i... |
"The specified tap/aos/xml file is encrypted."]] | "The specified tap/aos/xml file is encrypted."], ['nothotshot', None, "Don't use the 'hotshot' profiler even if it's available."]] | def reportProfile(report_profile, name): if not report_profile: return if name: from twisted.python.dxprofile import report log.msg("Sending DXP stats...") report(report_profile, name) log.msg("DXP stats sent.") else: log.err("--report-profile specified but application has no " "name (--appname unspecified)") |
for (longOpt, shortOpt, docs, settings, synonyms, dispatch)\ in map( lambda c: c(), collectors): | for c in collectors: (longOpt, shortOpt, docs, settings, synonyms, dispatch) = c() | def __init__(self): UserDict.UserDict.__init__(self) self.opts = self.data # These are strings/lists we will pass to getopt self.longOpt = [] self.shortOpt = '' self.docs = {} self.synonyms = {} self.__dispatch = {} |
docs[prettyName] = None | docs[prettyName] = self.docs.get(prettyName) | def _gather_handlers(self): """Gather up options with their own handler methods. """ |
viewMethod = getattr(self, 'factory_' + viewName, None) if viewMethod is None: view = getattr(domwidgets, viewName, DefaultWidget)(self.model) viewMethod = view.generate | viewMethod = getattr(self, 'factory_' + viewName, defaultViewMethod) if viewMethod is defaultViewMethod: widget = getattr(domwidgets, viewName, None) if widget is not None: view = widget(self.model) viewMethod = view.generate | def getNodeView(self, request, node): result = None # Most specific viewName = node.getAttribute('view') # Next-most specific if not viewName: viewName = node.getAttribute('id') # Least specific if not viewName: viewName = node.getAttribute('class') |
if viewName and viewMethod is defaultViewMethod: del defaultViewMethod del viewMethod del view del result nodeText = node.toxml() raise NotImplementedError, "You specified view name %s on a node, but no factory_%s method was found." % (viewName, viewName) | def getNodeView(self, request, node): result = None # Most specific viewName = node.getAttribute('view') # Next-most specific if not viewName: viewName = node.getAttribute('id') # Least specific if not viewName: viewName = node.getAttribute('class') | |
def buildProtocol(self, connection): | def buildProtocol(self, addr): | def buildProtocol(self, connection): """Create an instance of a subclass of Protocol. |
def getOutputFileName(originalFileName, outputExtension): | def getOutputFileName(originalFileName, outputExtension, index=None): | def getOutputFileName(originalFileName, outputExtension): return os.path.splitext(originalFileName)[0]+outputExtension |
elif self.size is not None and len(self.pending) < self.size: | elif self.size is None or len(self.pending) < self.size: | def put(self, obj): """Add an object to this queue. |
elif self.size is not None and len(self.waiting) < self.backlog: | elif self.backlog is None or len(self.waiting) < self.backlog: | def get(self): """Attempt to retrieve and remove an object from the queue. |
t=threading.Thread(target=self.doWrite, name="win32er.Process.doWrite pid=%d" % dwPid) t.setDaemon(True) t.start() t=threading.Thread(target=self.doReadOut, name="win32er.Process.doReadOut pid=%d" % dwPid) t.setDaemon(True) t.start() threading.Thread(target=self.doReadErr, name="win32er.Process.doReadErr pid=%d" % dwPi... | for meth in self.doWrite, self.doReadOut, self.doReadErr: t = threading.Thread( target=meth, name="win32er.Process.%s pid=%d" % (meth.__name__, dwPid)) t.setDaemon(True) t.start() | def __init__(self, reactor, protocol, command, args, environment, path): self.reactor = reactor self.protocol = protocol |
d = loopUntil(lambda :getattr(s, 'protocol', None) is not None) | d = loopUntil( lambda: (getattr(s, 'protocol', None) is not None and getattr(cf, 'protocol', None) is not None)) | def testConnectByService(self): serv = socket.getservbyname d = defer.succeed(None) try: s = MyServerFactory() port = reactor.listenTCP(0, s, interface="127.0.0.1") self.n = port.getHost().port socket.getservbyname = (lambda s, p,n=self.n: s == 'http' and p == 'tcp' and n or 10) self.ports.append(port) cf = MyClientFac... |
for t in self.dispensers.getDispensers(container.entityType): | if components.implements(container, coil.IConfigurator) and container.getType(name): interface = container.getType(name) elif components.implements(container, coil.IConfigCollection): interface = container.entityType else: interface = None for t in self.dispensers.getDispensers(interface): | def makeConfigurable(self, cfgInfo, container, name): """Add a new configurable to a container, based on input from web form.""" cmd, args = string.split(cfgInfo, ' ', 1) if cmd == "new": # create obj = coil.createConfigurable(reflect.namedClass(args), container, name) elif cmd == "dis": # dispense methodHash = int(arg... |
raise DBError("RowClass must have class variable: %s" % att) | raise DBError("RowClass %s must have class variable: %s" % (rc, att)) | def _populateSchemaFor(self, transaction, rc): """construct all the SQL for database operations on <tableName> and populate the class <rowClass> with that info. """ attributes = ("rowColumns", "rowKeyColumns", "rowTableName" ) for att in attributes: if not hasattr(rc, att): raise DBError("RowClass must have class varia... |
Example: | Example:: | def loadObjectsFrom(self, tableName, parentRow=None, data=None, whereClause=None, forceChildren=0): """Load a set of RowObjects from a database. |
if not self.received.has_key('host'): self.received['host'] = host clientProtocol = class_(self.method, rest, self.clientproto, self.received, | headers = self.getAllHeaders().copy() if not headers.has_key('host'): headers['host'] = host clientProtocol = class_(self.method, rest, self.clientproto, headers, | def process(self): parsed = urlparse.urlparse(self.uri) protocol = parsed[0] host = parsed[1] port = self.ports[protocol] if ':' in host: host, port = string.split(host, ':') rest = urlparse.urlunparse(('','')+parsed[2:]) if not rest: rest = rest+'/' class_ = self.protocols[protocol] if not self.received.has_key('host'... |
self.received['host'] = self.factory.host | self.received_headers['host'] = self.factory.host | def process(self): self.received['host'] = self.factory.host clientProtocol = ProxyClient(self.method, self.uri, self.clientproto, self.getAllHeaders(), self.content.read(), self) client = reactor.clientTCP(self.factory.host, self.factory.port, clientProtocol) |
testCaseInstance = lambda x: None | testCaseInstance = lambda self: None | def isDebuggingRun(self): return self.parent.isDebuggingRun() |
methodNames = self.methodNames | def _setUpClassError(tm): tm.errors.extend(setUpClass.errors) reporter.startTest(tm) self.methodsWithStatus.setdefault(tm.status, []).append(tm) reporter.endTest(tm) | |
del attrs3['uid'], attrs3['gid'] | def testOpenFile(self): d = self.client.openFile("testfile1", filetransfer.FXF_READ | \ filetransfer.FXF_WRITE, {}) openFile = self._waitWithBuffer(d) self.failUnlessEqual(filetransfer.ISFTPFile(openFile), openFile) bytes = self._waitWithBuffer(openFile.readChunk(0, 20)) self.failUnlessEqual(bytes, 'a'*10 + 'b'*10) sel... | |
assert self.ss.ownedResources[("int", "17")] == 17, str(self.ss.ownedResources) | self.assertEquals(self.ss.ownedResources[("int", "17")], 17) | def testDummyResource(self): from twisted.internet import reactor self.ss.registerResourceLoader("int", int) self.ps.loadRemoteResource("int", "17", 0).addBoth(stopTheReactor).setTimeout(5) self.app.bindPorts() reactor.run() assert self.ss.ownedResources[("int", "17")] == 17, str(self.ss.ownedResources) |
def testRaiseExceptionWithTB(self): | def _getDivisionFailure(self): | def testRaiseExceptionWithTB(self): try: 1/0 except: f = failure.Failure() |
self.assertEquals(tb[-1][-1], '1/0') | return tb[-1][-1] | def testRaiseExceptionWithTB(self): try: 1/0 except: f = failure.Failure() |
self.assertEquals(c(), struct.pack('!H', i + 1)) | self.assertEquals(c(), struct.pack('!H', (i + 1) % (2 ** 16))) | def testCounter(self): c = transport._Counter('\x00\x00', 2) for i in xrange(256 * 256): self.assertEquals(c(), struct.pack('!H', i + 1)) # It should wrap around, too. for i in xrange(256 * 256): self.assertEquals(c(), struct.pack('!H', i + 1)) |
port = self.server.getHost()[2] | port = self.server.getHost().port | def testOurServerOurClient(self): """test the SSH server against the SSH client """ if os.name != 'posix': raise unittest.SkipTest("cannot run on non-posix") # why? global theTest theTest = self realm = ConchTestRealm() p = portal.Portal(realm) sshpc = ConchTestSSHChecker() sshpc.registerChecker(ConchTestPasswordChecke... |
port = self.server.getHost()[2] | port = self.server.getHost().port | def testOurServerOpenSSHClient(self): """test the SSH server against the OpenSSH client """ if os.name != 'posix': raise unittest.SkipTest("cannot run on non-posix") cmdline = ('ssh -2 -l testuser -p %i ' '-oUserKnownHostsFile=kh_test ' '-oPasswordAuthentication=no ' # Always use the RSA key, since that's the one in kh... |
extra = "\n" if hasattr(self, "creator"): extra += " C: Deferred was created:\n C:" extra += "".join(self.creator).rstrip().replace("\n","\n C:") extra += "\n" if hasattr(self, "invoker"): extra += " I: First Invoker was:\n I:" extra += "".join(self.invoker).rstrip().replace("\n","\n I:") extra += "\n" | extra = "\n" + self._debugInfo() | def _startRunCallbacks(self, result): if self.called: if not self.debug: raise AlreadyCalledError extra = "\n" if hasattr(self, "creator"): extra += " C: Deferred was created:\n C:" extra += "".join(self.creator).rstrip().replace("\n","\n C:") extra += "\n" if hasattr(self, "invoker"): extra += " I: First Invoker was:\... |
pdb.run("suite.run(reporter)", globals(), locals()) | pdb.run("suite.run(reporter, config['random'])", globals(), locals()) | def run(): if len(sys.argv) == 1: sys.argv.append("--help") config = Options() try: config.parseOptions() except usage.error, ue: print "%s: %s" % (sys.argv[0], ue) os._exit(1) if config['reactor']: mod = 'twisted.internet.' + config['reactor'] print "Using %s reactor" % mod reflect.namedModule(mod).install() suite ... |
fireOnOneErrback=True) | fireOnOneErrback=True, consumeErrors=True) | def _openDataConnection(self, commands, protocol): """ This method returns a DeferredList. """ cmds = [FTPCommand(command, public=1) for command in commands] cmdsDeferred = DeferredList([cmd.deferred for cmd in cmds], fireOnOneErrback=True) |
d = DeferredList(results, fireOnOneErrback=1) | d = DeferredList(results, fireOnOneErrback=1, consumeErrors=1) | def close(x, m=_mutable): m[0] and m[0].disconnect() return x |
lp = '(buggy logPrefix method)' | def callWithLogger(logger, func, *args, **kw): """ Utility method which wraps a function in a try:/except:, logs a failure if one occurrs, and uses the system's logPrefix. """ lp = '(buggy logPrefix method)' try: lp = logger.logPrefix() callWithContext({"system": lp}, func, *args, **kw) except: err(system=lp) | |
softspace = 0 | softspace = 1 | def stop(self): removeObserver(self._emit) |
for c in c2, c4: c.transport.loseConnection() p.stopListening() return defer.DeferredList([c2.dDisconnected, c4.dDisconnected]) | for c in c2, c4: c.transport.loseConnection() return defer.DeferredList([ defer.maybeDeferred(p.stopListening), c2.dDisconnected, c4.dDisconnected]) | def _cleanup(results): for c in c2, c4: c.transport.loseConnection() p.stopListening() return defer.DeferredList([c2.dDisconnected, c4.dDisconnected]) |
def connectionLost(self): | def connectionLost(self, reason): | def connectionLost(self): print 'connection lost (protocol)' reactor.stop() |
def sendLine(self, line): print 'S:', repr(line) return basic.LineReceiver.sendLine(self, line) | def sendLine(self, line): print 'S:', repr(line) return basic.LineReceiver.sendLine(self, line) | |
print 'C: ' + repr(line) | def lineReceived(self, line): print 'C: ' + repr(line) if self._parts is None: lastPart = line.rfind(' ') if lastPart != -1: lastPart = line[lastPart + 1:] if lastPart.startswith('{') and lastPart.endswith('}'): # It's a literal a-comin' in try: octets = int(lastPart[1:-1]) except ValueError: raise IllegalServerRespons... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.