rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
class SMTP(basic.LineReceiver, policies.TimeoutMixin): | class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin): | def connectionLost(self): """handle message truncated |
def rawDataReceived(self, data): """Throw away rest of long line""" rest = string.split(data, '\r\n', 1) if len(rest) == 2: self.setLineMode(rest[1]) | def lineLengthExceeded(self, line): if self.mode is DATA: for message in self.__messages: message.connectionLost() self.mode = COMMAND del self.__messages self.sendCode(500, 'Line too long') | |
cmd = 'emote %s' % cmd[6:].replace('"', r'\"') | cmd = 'emote "%s"' % cmd[6:].replace('"', r'\"') | def telnet_Command(self, cmd): """Execute a command as a player. """ |
f = getattr(self, 'macro_' + line[1:3].rstrip(), None) | f = getattr(self, 'macro_' + line[1:3].rstrip().upper(), None) | def lineReceived(self, line): if line[0] == '.': f = getattr(self, 'macro_' + line[1:3].rstrip(), None) if f: f(line[3:].strip()) else: self.text(line) |
macro_DT = macro_TH | def macro_TH(self, line): self.write('<html><head>\n') parts = [stripQuotes(x) for x in line.split(' ', 2)] + ['', ''] title, manSection = parts[:2] self.write('<title>%s.%s</title>' % (title, manSection)) self.write('</head>\n<body>\n\n') self.write('<h1>%s.%s</h1>\n\n' % (title, manSection)) | |
done = 0 | def __init__(self): self.done = defer.Deferred() | def dataReceived(self, data): self.transport.write(data) if '\n' in data: self.transport.loseConnection() |
self.done = 1 unittest.assertEquals(reason.value.exitCode, 0, 'exit code was not 0: %s' % reason.value.exitCode) | log.msg("MAD(ssh): connection lost") log.msg(str(process.reapProcessHandlers.keys())) unittest._inst.assertEquals(reason.value.exitCode, 0, 'exit code was not 0: %s' % reason.value.exitCode) | def processEnded(self, reason): self.done = 1 unittest.assertEquals(reason.value.exitCode, 0, 'exit code was not 0: %s' % reason.value.exitCode) self.buf = self.buf.replace('\r\n', '\n') unittest.assertEquals(self.buf, 'goodbye\n') |
unittest.assertEquals(self.buf, 'goodbye\n') | unittest._inst.assertEquals(self.buf, 'goodbye\n') reactor.callLater(0, self.done.callback, True) | def processEnded(self, reason): self.done = 1 unittest.assertEquals(reason.value.exitCode, 0, 'exit code was not 0: %s' % reason.value.exitCode) self.buf = self.buf.replace('\r\n', '\n') unittest.assertEquals(self.buf, 'goodbye\n') |
self.done = 0 | self.done = defer.Deferred() | def __init__(self, port, fac): self.port = port self.fac = fac self.done = 0 self.connected = 0 self.buf = '' |
self.done = 1 | self.done.callback(True) | def processEnded(self, reason): log.msg('FORWARDING PROCESS CLOSED') self.done = 1 |
unittest.failUnlessEqual(self.buf, self.data) | unittest._inst.failUnlessEqual(self.buf, self.data) | def connectionLost(self, reason): log.msg('FORWARDING PORT CLOSED') unittest.failUnlessEqual(self.buf, self.data) |
d = self.server.stopListening() if d: util.wait(d) | return self.server.stopListening() | def tearDown(self): try: self.fac.proto.done = 1 except AttributeError: pass else: self.fac.proto.transport.loseConnection() reactor.iterate() d = self.server.stopListening() if d: util.wait(d) |
self.execute('echo goodbye', p) | return self.execute('echo goodbye', p) | def testExec(self): p = ConchTestOpenSSHProcess() self.execute('echo goodbye', p) |
self.execute('', p, preargs='-N -L%i:127.0.0.1:%i' % (lport, port)) serv.stopListening() | d = self.execute('', p, preargs='-N -L%i:127.0.0.1:%i' % (lport, port)) d.addBoth(lambda x: serv.stopListening()) return d | def testLocalToRemoteForwarding(self): f = EchoFactory() f.fac = self.fac serv = reactor.listenTCP(0, f) port = serv.getHost().port lport = self._getRandomPort() p = ConchTestForwardingProcess(lport,self.fac) self.execute('', p, preargs='-N -L%i:127.0.0.1:%i' % (lport, port)) serv.stopListening() |
self.execute('', p, preargs='-N -R %i:127.0.0.1:%i' % (lport, port)) serv.stopListening() | d = self.execute('', p, preargs='-N -R %i:127.0.0.1:%i' % (lport, port)) d.addBoth(lambda x: serv.stopListening()) return d | def testRemoteToLocalForwarding(self): f = EchoFactory() f.fac = self.fac serv = reactor.listenTCP(0, f) port = serv.getHost().port lport = self._getRandomPort() p = ConchTestForwardingProcess(lport, self.fac) self.execute('', p, preargs='-N -R %i:127.0.0.1:%i' % (lport, port)) serv.stopListening() |
util.spinWhile(lambda: not p.done, timeout=30) | return p.done | def execute(self, args, p, preargs = ''): cmdline = ('ssh -2 -l testuser -p %i ' '-oUserKnownHostsFile=kh_test ' '-oPasswordAuthentication=no ' # Always use the RSA key, since that's the one in kh_test. '-oHostKeyAlgorithms=ssh-rsa ' '-a ' '-i dsa_test ') + preargs + \ ' 127.0.0.1 ' + args port = self.server.getHost().... |
util.spinWhile(lambda: not p.done, timeout=30) | return p.done | def execute(self, args, p, preargs=''): if runtime.platformType == 'win32': raise unittest.SkipTest, "can't run cmdline client on win32" port = self.server.getHost().port cmd = ('-p %i -l testuser ' '--known-hosts kh_test ' '--user-authentications publickey ' '--host-key-algorithms ssh-rsa ' '-a -I ' '-K direct ' '-i d... |
util.spinWhile(lambda: not p.done, timeout=30) | d.addCallback(lambda x: p.done) return d | def _(host, *args): o['host'] = host |
def runInThread(cnt): while cnt > 0: from time import sleep sleep(.1) yield cnt cnt -= 1 def howdy(): print "howdy" source = flow.Threaded(runInThread(8)) reactor.callLater(.3,howdy) printFlow(source) | from __future__ import generators from twisted.internet import reactor, defer from twisted.flow import flow from twisted.flow.threads import Threaded def countSleep(index): from time import sleep for index in range(index): sleep(.3) print "sleep", index yield index def countCooperate(index): for index in range(index)... | def runInThread(cnt): while cnt > 0: from time import sleep sleep(.1) yield cnt cnt -= 1 |
self.stop = True | pass | def _process(self): try: self._iterable = iter(self._iterable) except: self.failure = Failure() else: try: while True: val = self._iterable.next() reactor.callFromThread(self._process_result, val) except StopIteration: self.stop = True except: self.failure = Failure() self._cooperate.immediate = True reactor.callFromTh... |
reactor.callFromThread(self._cooperate) | self._cooperate() | def _process(self): try: self._iterable = iter(self._iterable) except: self.failure = Failure() else: try: while True: val = self._iterable.next() reactor.callFromThread(self._process_result, val) except StopIteration: self.stop = True except: self.failure = Failure() self._cooperate.immediate = True reactor.callFromTh... |
This is particularly useful for executing a query in a thread. TODO: show example here | from __future__ import generators from twisted.enterprise import adbapi from twisted.internet import reactor from twisted.flow import flow from twisted.flow.threads import QueryIterator, Threaded dbpool = adbapi.ConnectionPool("SomeDriver",host='localhost', db='Database',user='User',passwd='Password') s... | def _yield(self): if self.results or self.stop or self.failure: return return self._cooperate |
conn = self.pool.connect() self.curs = conn.cursor() | self.conn = self.pool.connect() self.curs = self.conn.cursor() | def __iter__(self): conn = self.pool.connect() self.curs = conn.cursor() self.curs.execute(self.sql) return self |
write(" %s:%s='%s'" % (self.getPrefix[k[0]], k[1], escapeToXml(v, 1)).encode("utf-8")) | write((" %s:%s='%s'" % (self.getPrefix(k[0]), k[1], escapeToXml(v, 1))).encode("utf-8")) | def serialize(self, elem, closeElement = 1): # Optimization shortcuts write = self.cio.write |
attrs[k.split(" ")] = v | aqname = k.split(" ") attrs[(aqname[0], aqname[1])] = v | def _onStartElement(self, name, attrs): # Generate a qname tuple from the provided name qname = name.split(" ") |
self.stdoutClosed = 0 self.stderrClosed = 0 | self.closedNotifies = 0 | def __init__(self, command, args, environment, path): # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 |
if not self.closed: | self.closedNotifies = self.closedNotifies + 1 if self.closedNotifies == 3: | def connectionLostNotify(self): """Will be called twice, by the stdout and stderr threads.""" if not self.closed: self.closed = 1 self.connectionLost() |
print "very finished" | self.request.stopConsuming() | def resumeProducing(self): if (self.request is None) or (self.file.closed): return self.request.write(self.file.read(abstract.FileDescriptor.bufferSize)) |
print "disconcert and die" | def loseConnection(self): "Disconnect, and clean up" print "disconcert and die" if self.file is not None: if self.file.tell() == self.filesize: self.pi.reply('getok') else: self.pi.reply('getabort') self.file.close() self.file = None self.pi.queuedfile = None # just incase self.transport.loseConnection() | |
self.pi.reply('getabort') | self.pi.reply('getok') | def loseConnection(self): "Disconnect, and clean up" print "disconcert and die" if self.file is not None: if self.file.tell() == self.filesize: self.pi.reply('getok') else: self.pi.reply('getabort') self.file.close() self.file = None self.pi.queuedfile = None # just incase self.transport.loseConnection() |
print "makeTransport" | def makeTransport(self): print "makeTransport" transport = self.transport transport.finish = self.finish return transport | |
print "connectionMade" | def connectionMade(self): "Will start an transfer, if one is queued up, when the client connects" print "connectionMade" if self.pi.action is not None: self.executeAction() | |
print "executeaction" | def executeAction(self): """Initiates the transfer. This is a two-case implementation for starting the transfer. It is either started by the telnet-interface when the connection is already open, or it is called by connectionMade. The property 'pi' is the telnetconnection and its property 'action' can either be 'GET', '... | |
sendFileTransfer(self.file, self.filesize, self.makeTransport()) | dtp = sendFileTransfer(self.file, self.filesize, self.makeTransport()) dtp.resumeProducing() | def fileget(self, queuedfile): "Send the given file to the peer" self.file = open(queuedfile, "rb") self.filesize = os.path.getsize(queuedfile) sendFileTransfer(self.file, self.filesize, self.makeTransport()) |
mtime = time.strftime("%b %2d %2H:%2M", time.gmtime(os.path.getmtime(ff))) | mtime = time.strftime("%b %d %H:%M", time.gmtime(os.path.getmtime(ff))) | def listdir(self, dir): """Prints outs the files in the given directory Note that the printout is very fake, and only gives the filesize, date, time and filename. """ list = os.listdir(dir) for a in list: s = a ff = os.path.join(dir, s) # the full filename mtime = time.strftime("%b %2d %2H:%2M", time.gmtime(os.path.get... |
class FTP(protocol.Protocol): | class FTP(protocol.Protocol, protocol.Factory): """The FTP-Protocol. Also a factory for the DTP.""" | def listdir(self, dir): """Prints outs the files in the given directory Note that the printout is very fake, and only gives the filesize, date, time and filename. """ list = os.listdir(dir) for a in list: s = a ff = os.path.join(dir, s) # the full filename mtime = time.strftime("%b %2d %2H:%2M", time.gmtime(os.path.get... |
print key | def reply(self, key, s = ''): print key if ftp_reply[key].find('%s') > -1: self.transport.write(ftp_reply[key] % s + '\r\n') else: self.transport.write(ftp_reply[key] + '\r\n') | |
if not os.path.isdir(self.root + wd): | if (not os.path.isdir(self.root + wd)) or (wd.find('..') > 0) or (wd.find('\\') > 0) or (wd.find('//') > 0): | def ftp_Cwd(self, params): if self.checkauth(): return wd = os.path.normpath(params) if not os.path.isabs(wd): wd = os.path.normpath(self.wd + '/' + wd) if not os.path.isdir(self.root + wd): self.reply('nodir', params) return else: self.wd = wd self.reply('cwdok') |
self.dtp.transport.loseConnection() | self.dtp.loseConnection() | def createPassiveServer(self): # a bit silly code if self.dtp is not None: if self.dtp.transport is not None: self.dtp.transport.loseConnection() self.dtp = None # giving 0 will generate a free port self.dtpPort = tcp.Port(0, self) self.dtpPort.startListening() |
self.dtp.transport.loseConnection() | self.dtp.loseConnection() | def createActiveServer(self): # silly code repeating if self.dtp is not None: if self.dtp.transport is not None: self.dtp.transport.loseConnection() self.dtp = None self.dtpPort = tcp.Client(self.peerhost, self.peerport, self.buildProtocol(self.peerport)) self.dtp.transport = self.dtpPort |
self.dtpPort = tcp.Client(self.peerhost, self.peerport, self.buildProtocol(self.peerport)) | self.dtp = self.buildProtocol(self.peerport) self.dtpPort = tcp.Client(self.peerhost, self.peerport, self.dtp) | def createActiveServer(self): # silly code repeating if self.dtp is not None: if self.dtp.transport is not None: self.dtp.transport.loseConnection() self.dtp = None self.dtpPort = tcp.Client(self.peerhost, self.peerport, self.buildProtocol(self.peerport)) self.dtp.transport = self.dtpPort |
def buildProtocol(self, addr): self.dtp = DTP() | def createActiveServer(self): # silly code repeating if self.dtp is not None: if self.dtp.transport is not None: self.dtp.transport.loseConnection() self.dtp = None self.dtpPort = tcp.Client(self.peerhost, self.peerport, self.buildProtocol(self.peerport)) self.dtp.transport = self.dtpPort | |
self.dtp.factory = self return self.dtp | def buildProtocol(self,addr): p = DTP() p.factory = self p.pi = self p.transport = self.dtpPort if self.dtpPort: p.DTPLoseConnection = self.dtpPort.loseConnection self.dtp = p return p | def buildProtocol(self, addr): self.dtp = DTP() self.dtp.pi = self self.dtp.factory = self return self.dtp |
if self.peerport < 1024: | if peerport < 1024: | def ftp_Port(self, params): """Request for an active connection This command may be potentially abused, and the only countermeasure so far is that no port below 1024 may be targeted. An extra approach is to disable port'ing to a third-party ip, which is optional through ALLOW_THIRDPARTY. Note that this disables 'Cross-... |
print self.dtp, "is the DTP" print self.dtp.transport, "is the Transport" | def ftp_List(self, params): if self.checkauth(): return # The reason for this long join, is to exclude access below the root npath = self.buildFullpath(params) if not os.path.isdir(npath): self.reply('nodir', params) return self.reply('get') self.queuedfile = npath self.action = 'LIST' print self.dtp, "is the DTP" prin... | |
print line | def processLine(self, line): "Process the input from the client" line = line.strip() print line command = line.split() if command == []: self.reply('unknown') return 0 commandTmp, command = command[0], '' for c in commandTmp: if ord(c) < 128: command = command + c command = command.capitalize() print "-"+command+"-" if... | |
self.xml.get_widget("NickLabel").set_text(self.group.account.client.name) | self.xml.get_widget("NickLabel").set_text( getattr(self.group.account.client,"name","(no name)")) | def __init__(self, group): InputOutputWindow.__init__(self, "GroupChatBox", "GroupInput", "GroupOutput") self.group = group self.members = [] self.membersHidden = 0 self._colorcache = {} alloc_color = self.output.get_colormap().alloc self.myColor = alloc_color("#0000ff") self.xml.get_widget("NickLabel").set_text(self.g... |
return davxml.GETContentType.fromString(self.resource.contentType()) | mimeType = self.resource.contentType() mimeType.params = None return davxml.GETContentType.fromString(generateContentType(mimeType)) | def __getitem__(self, key): namespace, name = key |
self.skt.close() self.protocol.connectionLost() | if not self.disconnected: self.skt.close() self.protocol.connectionLost() abstract.FileDescriptor.connectionLost(self) | def connectionLost(self, arg=None): # print 'closing the connection' self.skt.close() self.protocol.connectionLost() |
class Blocker: | class Blocker(threading.Thread): | def loseConnection(self): self.writeQ.put(None) |
def start(self): threading.Thread(target=self.blockForever).start() | def run(self): self.blockForever() | def start(self): threading.Thread(target=self.blockForever).start() |
l = self.fdes.istream.read(bytes) | try: l = self.fdes.istream.read(bytes) except SocketException: self.stop() return (self.fdes.connectionLost, 0) | def block(self): bytes = jarray.zeros(8192, 'b') l = self.fdes.istream.read(bytes) if l == -1: self.stop() return (self.fdes.connectionLost,0) return (self.fdes.protocol.dataReceived, bytes[:l].tostring()) |
protocol.makeConnection(transport, tcpPort) | def portGotSocket(tcpPort, skt): # make this into an address... protocol = tcpPort.factory.buildProtocol(None) transport = JConnection(skt, protocol) # make read and write blockers wb = WriteBlocker(transport, theMultiplexor.q) wb.start() transport.writeBlocker = wb ReadBlocker(transport, theMultiplexor.q).start() pro... | |
def _setUpDebugging(config, suite): suite.reporter.debugger = 1 | def _getDebugger(): | def _setUpDebugging(config, suite): suite.reporter.debugger = 1 dbg = pdb.Pdb() try: rcFile = open("../.pdbrc") except IOError: hasattr(sys, 'exc_clear') and sys.exc_clear() else: dbg.rcLines.extend(rcFile.readlines()) if config['until-failure']: call_until_failure(suite.reporter, dbg.run, "suite.run(config['random'])"... |
if config['until-failure']: call_until_failure(suite.reporter, dbg.run, "suite.run(config['random'])", globals(), locals()) else: dbg.run("suite.run(config['random'])", globals(), locals()) | return dbg def _setUpDebugging(config, suite): suite.reporter.debugger = 1 _getDebugger().run("suite.run(config['random'])", globals(), locals()) | def _setUpDebugging(config, suite): suite.reporter.debugger = 1 dbg = pdb.Pdb() try: rcFile = open("../.pdbrc") except IOError: hasattr(sys, 'exc_clear') and sys.exc_clear() else: dbg.rcLines.extend(rcFile.readlines()) if config['until-failure']: call_until_failure(suite.reporter, dbg.run, "suite.run(config['random'])"... |
def call_until_failure(suite, callable, *args, **kwargs): | def call_until_failure(f, *args, **kwargs): | def _doProfilingRun(config, suite): if config['until-failure']: raise RuntimeError, \ "you cannot use both --until-failure and --profile" import profile prof = profile.Profile() try: prof.runcall(suite.run, config['random']) prof.dump_stats('profile.data') except SystemExit: pass prof.print_stats() |
callable(*args, **kwargs) | suite = f(*args, **kwargs) | def call_until_failure(suite, callable, *args, **kwargs): count = 1 print "Test Pass %d" % count callable(*args, **kwargs) while itrial.ITestStats(suite).allPassed: count += 1 print "Test Pass %d" % count callable(*args, **kwargs) |
callable(*args, **kwargs) def reallyRun(config, suite): | suite = f(*args, **kwargs) return suite def reallyRun(config): if config['until-failure']: if not config['debug']: def _doRun(config): suite = _getSuite(config) suite.run(config['random']) return suite return call_until_failure(_doRun, config) else: def _doRun(config): suite = _getSuite(config) _getDebugger().run("su... | def call_until_failure(suite, callable, *args, **kwargs): count = 1 print "Test Pass %d" % count callable(*args, **kwargs) while itrial.ITestStats(suite).allPassed: count += 1 print "Test Pass %d" % count callable(*args, **kwargs) |
if config['until-failure']: call_until_failure(suite, suite.run, config['random']) else: suite.run(config['random']) | suite.run(config['random']) | def reallyRun(config, suite): if config['debug']: _setUpDebugging(config, suite) elif config['profile']: _doProfilingRun(config, suite) else: if config['until-failure']: call_until_failure(suite, suite.run, config['random']) else: suite.run(config['random']) return suite |
suite = _getSuite(config) | def run(): _monkeyPatchPyunit() if len(sys.argv) == 1: sys.argv.append("--help") config = Options() try: config.parseOptions() except usage.error, ue: raise SystemExit, "%s: %s" % (sys.argv[0], ue) _setUpAdapters() _initialDebugSetup(config) suite = _getSuite(config) _setUpTestdir() _setUpLogging(config) reallyRu... | |
reallyRun(config, suite) | suite = reallyRun(config) | def run(): _monkeyPatchPyunit() if len(sys.argv) == 1: sys.argv.append("--help") config = Options() try: config.parseOptions() except usage.error, ue: raise SystemExit, "%s: %s" % (sys.argv[0], ue) _setUpAdapters() _initialDebugSetup(config) suite = _getSuite(config) _setUpTestdir() _setUpLogging(config) reallyRu... |
* stubs: a set of definitions of classes to construct, of the form [ (StubClass, args, databaseTableName, KeyColumns) ] | * stubs: a set of definitions of classes to construct, of the form [ (StubClass, databaseTableName, KeyColumns) ] | def __init__(self, dbpool, stubs, populatedCallback): """ Initialize me against a database. |
versionNum = '$Revision: 1.28 $'[11:-2] | versionNum = '$Revision: 1.29 $'[11:-2] | def receiveDirectMessage(self, sender, message, metadata=None): """Pass this message through tendril to my IRC counterpart. """ self.tendril.msgFromWords(self.nickname, sender, message, metadata) |
__implements__ = IWordsClient | implements(IWordsClient) | def memberLeft(self, member, group): """Tells me a member has left a group. """ |
__implements__ = IWordsPolicy | implements(IWordsPolicy) | def lookUpParticipant(self, nick): """ Get a Participant, given a name.""" |
NO_BODY_CODES = (204, 304, 302, 303) | NO_BODY_CODES = (204, 304) | def rawDataReceived(self, data): if self.length is not None: data, rest = data[:self.length], data[self.length:] self.length -= len(data) else: rest = '' self.handleResponsePart(data) if self.length == 0: self.handleResponseEnd() self.setLineMode(rest) |
if self.chunked and self.code not in NO_BODY_CODES: | if not self.startedWriting: self.write('') if self.chunked and self.code in NO_BODY_CODES: raise RuntimeError, "we screwed up" if self.chunked: | def finish(self): """We are finished writing data.""" if not hasattr(self, 'channel'): warnings.warn("Warning! request.finish called twice.", stacklevel=2) return if self.chunked and self.code not in NO_BODY_CODES: # write last chunk and closing CRLF self.transport.write("0\r\n\r\n") elif not self.startedWriting: # wri... |
elif not self.startedWriting: self.write('') | def finish(self): """We are finished writing data.""" if not hasattr(self, 'channel'): warnings.warn("Warning! request.finish called twice.", stacklevel=2) return if self.chunked and self.code not in NO_BODY_CODES: # write last chunk and closing CRLF self.transport.write("0\r\n\r\n") elif not self.startedWriting: # wri... | |
self.setHeader("content-length", "0") | def redirect(self, url): """Utility function that does a redirect. | |
portal = self.service.defaultPortal() return portal.login( cred.credentials.UsernamePassword(user, password), None, pop3.IMailbox ) | user, domain = self.lookupDomain(user) try: portal = self.service.lookupPortal(domain) except KeyError: return defer.fail(cred.error.UnauthorizedLogin()) else: return portal.login( cred.credentials.UsernamePassword(user, password), None, pop3.IMailbox ) | def authenticateUserPASS(self, user, password): portal = self.service.defaultPortal() return portal.login( cred.credentials.UsernamePassword(user, password), None, pop3.IMailbox ) |
print 'do a transfer' | def transfer(self): if self.transferring: return self.transfering = True | |
print 'gawt', zone | def _cbZone(self, zone): ans, _, _ = zone print 'gawt', zone self.records = r = {} for rec in ans: if rec.type == dns.SOA: self.soa = (str(rec.name).lower(), rec.payload) else: r.setdefault(str(rec.name).lower(), []).append(rec.payload) | |
print 'uperdate' | def update(self): print 'uperdate' self.transfer().addCallbacks(self._cbTransferred, self._ebTransferred) | |
print 'done xferred' | def _cbTransferred(self, result): print 'done xferred' self.transferring = False | |
def getObjectRetreiver(): | def getObjectRetriever(): | def getObjectRetreiver(): """Get a factory which retreives a root object from its client @returns: A pair: A ClientFactory and a Deferred which will be passed a remote reference to the root object of a PB server.x """ d = defer.Deferred() b = Broker(1) bf = BrokerClientFactory(b) _ObjectRetrieval(b, d) return bf, d |
bf, d = getObjectRetreiver() | bf, d = getObjectRetriever() | def getObjectAt(host, port, timeout=None): """Establishes a PB connection and returns with a L{RemoteReference}. @param host: the host to connect to @param port: the port number to connect to @param timeout: a value in milliseconds to wait before failing by default. (OPTIONAL) @returns: A Deferred which will be pas... |
bf, d = getObjectRetreiver() | bf, d = getObjectRetriever() | def getObjectAtSSL(host, port, timeout=None): """Establishes a PB connection over SSL and returns with a RemoteReference. @param host: the host to connect to @param port: the port number to connect to @param timeout: a value in milliseconds to wait before failing by default. (OPTIONAL) @returns: A Deferred which w... |
if node.getAttribute("class", "").find('listing') == -1: | if node.getAttribute("class", "").find('listing') != -1: | def fixLinks(document, ext): supported_schemes=['http', 'https', 'ftp', 'mailto'] for node in domhelpers.findElementsWithAttribute(document, 'href'): href = node.getAttribute("href") if urlparse.urlparse(href)[0] in supported_schemes: continue if node.getAttribute("class", "") == "absolute": continue if node.getAttrib... |
controllerResult, request, node, controller, view, success): | controllerResult, request, node, controller, view): | def handleControllerResults(self, controllerResult, request, node, controller, view, success): """Handle a deferred from a controller. """ self.outstandingCallbacks -= 1 if controllerResult is not None: self.outstandingCallbacks += 1 controllerResult.addCallback( self.handleControllerResults, request, node, controller,... |
if controllerResult is not None: | if isinstance(controllerResult, defer.Deferred): | def handleControllerResults(self, controllerResult, request, node, controller, view, success): """Handle a deferred from a controller. """ self.outstandingCallbacks -= 1 if controllerResult is not None: self.outstandingCallbacks += 1 controllerResult.addCallback( self.handleControllerResults, request, node, controller,... |
returnNode = self.dispatchResult(request, node, view) | viewResult = view.generate(request, node) returnNode = self.dispatchResult(request, node, viewResult) | def handleControllerResults(self, controllerResult, request, node, controller, view, success): """Handle a deferred from a controller. """ self.outstandingCallbacks -= 1 if controllerResult is not None: self.outstandingCallbacks += 1 controllerResult.addCallback( self.handleControllerResults, request, node, controller,... |
self.producerPaused = 0 | def doWrite(self): """Called when data is available for writing. | |
You can call connector.stopConnecting() to stop the connection attempt. | def startedConnecting(self, connector): """Called when a connection has been started. | |
def testSuperfluousDisableRequestRaise(self): | def testSuperfluousDisableRequestRaises(self): | def testSuperfluousDisableRequestRaise(self): # Try to disable a disabled option. Make sure it fails properly. d = self.p.requestDisable('\xab') self.assertRaises(telnet.AlreadyDisabled, util.wait, d) |
testdir = "_trial_temp" if os.path.exists(testdir): import shutil shutil.rmtree(testdir) os.mkdir(testdir) os.chdir(testdir) | 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']: from twisted.python import reflect mod = 'twisted.internet.' + config['reactor'] print "Using %s reactor" % mod reflect... | |
return UnauthorizedLogin() | return failure.Failure(UnauthorizedLogin()) | def _ebRequestAvatarId(self, f): if not f.check(UnauthorizedLogin, error.ValidPublicKey): log.msg(f) return UnauthorizedLogin() return f |
elif fine("PASS"): | elif find("PASS"): | def lineReceived(self, line): """Error Conditions""" uline = line.upper() find = lambda s: uline.find(s) != -1 |
return self.append(FlowMerge(self.addMerge(bucket=bucket))) | return self.append(FlowMerge(bucket=bucket)) | def addMergeToList(self, bucket=None): return self.append(FlowMerge(self.addMerge(bucket=bucket))) |
for link, bucket in self._flush: data = self.get(bucket, None) flow.push(data, link.stage, link.next) flow.context = self._parent | if not(self._flush): flow.context = self._parent return (link, bucket) = self._flush.pop(0) data = self.get(bucket, None) flow.push(cntx, self.onFlush) flow.push(data, link.stage, link.next) | def onFlush(self, flow, cntx): ''' cleans up the context and fires onFlush events ''' assert flow.context is self assert flow.context is cntx for link, bucket in self._flush: data = self.get(bucket, None) flow.push(data, link.stage, link.next) flow.context = self._parent |
def __init__(self, func = list.append, start = lambda: [], bucket = None, reduce = 0): | def __init__(self, func = lambda lst, val: lst.append(val) or lst, start = lambda: [], bucket = None, reduce = 1): | def __init__(self, func = list.append, start = lambda: [], bucket = None, reduce = 0): if not bucket: bucket = id(self) self.bucket = str(bucket) self.start = start self.func = func self.reduce = reduce |
if not self.bucket in cntx: | if not cntx.has_key(self.bucket): | def __call__(self, flow, data): cntx = flow.context if not self.bucket in cntx: start = self.start if callable(start): start = start() cntx[self.bucket] = start cntx.addFlush(flow.nextLinkItem(), self.bucket) curr = self.func(cntx[self.bucket], data) if self.reduce: cntx[self.bucket] = curr else: if curr: cntx[self.buc... |
cntx[self.bucket] = curr[0] flow.push(curr[1]) | (save, data) = curr cntx[self.bucket] = save if data: flow.push(data) | def __call__(self, flow, data): cntx = flow.context if not self.bucket in cntx: start = self.start if callable(start): start = start() cntx[self.bucket] = start cntx.addFlush(flow.nextLinkItem(), self.bucket) curr = self.func(cntx[self.bucket], data) if self.reduce: cntx[self.bucket] = curr else: if curr: cntx[self.buc... |
def pickColor(self, value, mode, BOLD = map(str.upper, ColorText.COLORS)): | def pickColor(self, value, mode, BOLD = ColorText.BOLD_COLORS): | def pickColor(self, value, mode, BOLD = map(str.upper, ColorText.COLORS)): if mode: return ColorText.COLORS[value] else: return self.bold and BOLD[value] or ColorText.COLORS[value] |
node.appendChild(document.createTextNode(str(self.getData()))) | textNode = document.createTextNode(str(self.getData())) if node is None: return textNode node.appendChild(textNode) | def generateDOM(self, request, node): if isinstance(self.text, Model): node.appendChild(document.createTextNode(str(self.getData()))) return node else: return document.createTextNode(self.text) |
footnotes(document) notes(document) | def munge(document, template, linkrel, d, fullpath, ext, url): fixRelativeLinks(template, linkrel) addMtime(template, fullpath) removeH1(document) expandAPI(document) fixAPI(document, url) fontifyPython(document) addPyListings(document, d) addHTMLListings(document, d) fixLinks(document, ext) putInToC(template, generate... | |
data = escapingRE.sub(r'\\\1{}', data).replace('\\', '$\backslash$') | data = escapingRE.sub(r'\\\1{}', data.replace('\\', '$\\backslash$')) | def gotText(self, data): if self.ignoring: return if self.normalizing: data = data.replace('\n', ' ') if self.escaping: data = escapingRE.sub(r'\\\1{}', data).replace('\\', '$\backslash$') self.writer(data) |
self._runCallbacks() | if self.called: self._runCallbacks() | def unpause(self): """Process all callbacks made since pause() was called. """ self.paused = 0 self._runCallbacks() |
oldstdin.close() oldstdout.close() oldstderr.close() | for i in range(3): try: os.close(i) except OSError, e: import errno if e.errno != errno.EBADF: raise | def rotateLog(signal, frame, logFile=logFile): logFile.rotate() |
escape('(--%s)-%s[%s]' % (long, short, descr)) | out_file.write(escape('(--%s)-%s[%s]' % (long, short, descr))) out_file.write(' \\\n') | out_file.write('#compdef %s\n' % cmd_name) |
out_file.write(escape('%s-%s[%s]' % (longExclusion, long, descr))) | out_file.write(escape('%s--%s[%s]' % (longExclusion, long, descr))) | out_file.write('#compdef %s\n' % cmd_name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.