rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print "SR DEBUG:", se.args[0], EWOULDBLOCK, EALREADY, EINPROGRESS
def doConnect(self): """I connect the socket. Then, call the protocol's makeConnection, and start waiting for data. """ try: self.socket.connect(self.addr) except socket.error, se: print "SR DEBUG:", se.args[0], EWOULDBLOCK, EALREADY, EINPROGRESS if se.args[0] == EMYSTERY: self.startWriting() elif se.args[0] in (EWOUL...
self.writer('\\begin{center}\\raisebox{1ex}[1ex]{%s --- ' '\\begin{em}%s\\end{em}}\\end{center}'
self.writer('\parbox[b]{\linewidth}{\\begin{center}%s --- ' '\\begin{em}%s\\end{em}\\end{center}}'
def visitNode_a_listing(self, node): fileName = os.path.join(self.currDir, node.getAttribute('href')) self.writer('\\begin{verbatim}\n') lines = map(string.rstrip, open(fileName).readlines()) lines = lines[int(node.getAttribute('skipLines', 0)):] self.writer(text.removeLeadingTrailingBlanks('\n'.join(lines))) self.writ...
start_title = end_title = end_body = start_body = start_html = None
end_title = end_body = start_body = start_html = None
def visitNode_title(self, node): self.visitNodeDefault(node) self.writer('\\label{%s}}\n' % os.path.basename(self.filename))
def getIO(self): return sys.stdout.getvalue() + sys.stderr.getvalue()
def getIO(self): return sys.stdout.getvalue() + sys.stderr.getvalue()
return utils.getProcessOutput(getTrialPath(), args=args, errortoo=1,
params = [ '-c', 'from twisted.scripts.trial import run; run()' ] params.extend(args) return utils.getProcessOutput(sys.executable, args=params, errortoo=1,
def runTrialWithEnv(env, *args): return utils.getProcessOutput(getTrialPath(), args=args, errortoo=1, env=env)
path = self._getMockPath()
def _getMockEnvironment(self): path = self._getMockPath() env = os.environ.copy() if not env.has_key('PYTHONPATH'): env['PYTHONPATH'] = path else: env['PYTHONPATH'] += os.pathsep + path return env
if not env.has_key('PYTHONPATH'): env['PYTHONPATH'] = path else: env['PYTHONPATH'] += os.pathsep + path
path = [self._getMockPath()] + sys.path env['PYTHONPATH'] = os.pathsep.join(path)
def _getMockEnvironment(self): path = self._getMockPath() env = os.environ.copy() if not env.has_key('PYTHONPATH'): env['PYTHONPATH'] = path else: env['PYTHONPATH'] += os.pathsep + path return env
return self._runTrial(os.environ, *args)
env = os.environ.copy() env['PYTHONPATH'] = os.pathsep.join(sys.path) return self._runTrial(env, *args)
def runTrialPure(self, *args): return self._runTrial(os.environ, *args)
unittest.TestCase.failUnlessSubstring(self, containee, container, *args, **kwargs)
self.failUnlessSubstring(containee, container, *args, **kwargs)
def failUnlessIn(self, container, containee, *args, **kwargs): # redefined to be useful in callbacks unittest.TestCase.failUnlessSubstring(self, containee, container, *args, **kwargs) return container
unittest.TestCase.failIfSubstring(self, containee, container, *args, **kwargs)
self.failIfSubstring(containee, container, *args, **kwargs)
def failIfIn(self, container, containee, *args, **kwargs): # redefined to be useful in callbacks unittest.TestCase.failIfSubstring(self, containee, container, *args, **kwargs) return container
def test_trialFound(self): self.failUnless(os.path.isfile(getTrialPath()), getTrialPath())
def failIfIn(self, container, containee, *args, **kwargs): # redefined to be useful in callbacks unittest.TestCase.failIfSubstring(self, containee, container, *args, **kwargs) return container
reactor.callLater(2, self.reducingMsg, (fmt, lines))
self.reducingMsg(fmt, lines)
def msg(self, user, message, length = None): fmt = "PRIVMSG %s :%%s" % (user,)
reactor.callLater(2, self.reducingMsg, (fmt, lines[1:]))
reactor.callLater(2, self.reducingMsg, fmt, lines[1:])
def reducingMsg(self, fmt, lines): self.sendLine(fmt % lines[0]) if len(lines) > 1: reactor.callLater(2, self.reducingMsg, (fmt, lines[1:]))
@rtype: C{int} @return: An string of printable characters uniquely identifying for all time the specified message.
@rtype: C{str} @return: A string of printable characters uniquely identifying for all time the specified message.
def getUidl(self, index): """Get a unique identifier for a particular message. @type index: C{int} @param index: The number of the message for which to retrieve a UIDL @rtype: C{int} @return: An string of printable characters uniquely identifying for all time the specified message. """
cmdline = "%s %s" % (command, string.join(args[1:], ' ')) self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, env, path, StartupInfo)
cmdline = ' '.join([_cmdLineQuote(a) for a in args[1:]]) self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(command, cmdline, None, None, 1, 0, env, path, StartupInfo)
def __init__(self, reactor, protocol, command, args, environment, path): self.reactor = reactor self.protocol = protocol
return base64.encodestring(k)
return string.replace(base64.encodestring(k), '\n', '_')
def _encode(self, k): """Encode a key so it can be used as a filename. """ return base64.encodestring(k)
return base64.decodestring(k)
return base64.decodestring(string.replace(k, '_', '\n'))
def _decode(self, k): """Decode a filename to get the key. """ return base64.decodestring(k)
pbecho.SimpleService("pbecho",appl).getPerspectiveNamed("guest").makeIdentity("guest") appl.listenTCP(pb.portno, pb.BrokerFactory(pb.AuthRoot(appl)))
auth = DefaultAuthorizer(appl) service = pbecho.SimpleService("pbecho", appl, auth) service.getPerspectiveNamed("guest").makeIdentity("guest") appl.listenTCP(pb.portno, pb.BrokerFactory(pb.AuthRoot(auth)))
def getPerspectiveNamed(self, name): p = SimplePerspective(name) p.setService(self) return p
L{twisted.internet.interfaces.Transport}.
L{twisted.internet.interfaces.ITransport}.
def resetDelay(self): """Call me after a successful connection to reset.
class WordsGateway(gateway.Gateway,pb.Referenceable):
class WordsGateway(gateway.Gateway,pb.Referenced):
def pbCallback(self,perspective): self.im.attachGateway(self.ref) self.ref.connected(perspective) self.ref.b=self.b self.attached=1
def saveApplications(p, type, enc, filename):
def saveApplication(p, type, enc, filename):
def saveApplications(p, type, enc, filename): p.setStyle(type) p.save(filename=(not enc) and filename, passphrase=enc and util.getPassword("Encryption passphrase: "))
p.save(filename=(not enc) and filename, passphrase=enc and util.getPassword("Encryption passphrase: "))
if enc: passphrase = util.getPassword("Encryption passphrase: ") filename = None else: passphrase = None p.save(filename=filename, passphrase=passphrase)
def saveApplications(p, type, enc, filename): p.setStyle(type) p.save(filename=(not enc) and filename, passphrase=enc and util.getPassword("Encryption passphrase: "))
plugins = getPlugIns("tap", debug, progress)
plugins = plugin.getPlugIns("tap", debug, progress)
def loadPlugins(debug = None, progress = None): try: plugins = getPlugIns("tap", debug, progress) except IOError: print "Couldn't load the plugins file!" sys.exit(2) tapLookup = {} for plug in plugins: if hasattr(plug, 'tapname'): shortTapName = plug.tapname else: shortTapName = plug.module.split('.')[-1] tapLookup[sh...
GeneralOptions.postOptions(self)
def postOptions(self): if self.recursing: GeneralOptions.postOptions(self) return debug = progress = None if self['debug']: debug = self._reportDebug if self['progress']: progress = self._reportProgress self.pb = util.makeStatBar(60, 1.0) self.tapLookup = loadPlugins(debug, progress) self.init(self.tapLookup) self.rec...
def getApplication(uid, gid, filename):
def getApplication(uid, gid, name, filename):
def getApplication(uid, gid, filename): if filename and os.path.exists(filename): return sob.load(filename, 'pickle') else: uid, gid = getid(uid, gid): return service.Application(options.subCommand, uid, gid)
uid, gid = getid(uid, gid): return service.Application(options.subCommand, uid, gid) def makeService(mod, s):
uid, gid = getid(uid, gid) return service.Application(name, uid, gid) def makeService(mod, s, options):
def getApplication(uid, gid, filename): if filename and os.path.exists(filename): return sob.load(filename, 'pickle') else: uid, gid = getid(uid, gid): return service.Application(options.subCommand, uid, gid)
mod.updateApplication(compat.IOldApplication(s), options.subOptions)
ser = service.MultiService() mod.updateApplication(compat.IOldApplication(ser), options)
def makeService(mod, s): if hasattr(mod, 'updateApplication'): mod.updateApplication(compat.IOldApplication(s), options.subOptions) else: mod.makeService(options.subOptions).setServiceParent(s)
mod.makeService(options.subOptions).setServiceParent(s)
ser = mod.makeService(options) ser.setServiceParent(s)
def makeService(mod, s): if hasattr(mod, 'updateApplication'): mod.updateApplication(compat.IOldApplication(s), options.subOptions) else: mod.makeService(options.subOptions).setServiceParent(s)
packages=dist.getPackages('twisted'), data_files=dist.getDataFiles('twisted'),
packages=dist.getPackages(util.sibpath(__file__, 'twisted')), data_files=dist.getDataFiles(util.sibpath(__file__, 'twisted')),
def dict(**kw): return kw
try: os.unlink('dist/%s' % twisteddist) os.unlink('dist/%s' % twisteddistnodocs) except EnvironmentError: pass
for f in (twisteddist, twisteddistnodocs): try: os.unlink('dist/%s' % f) except EnvironmentError: pass
def infozip(args=''): invoke(r'%s\bin\zip.exe' % options['cyghome'], args)
class Option(Input):
class Option(Widget):
def setUp(self, request, node, data): self['type'] = 'button' Input.setUp(self, request, node, data)
Input.setUp(self, request, node, data)
if data is None: data = '' if not self.attributes.has_key('value'): self['value'] = str(data)
def setUp(self, request, node, data): self.add(Text(self.text or data)) Input.setUp(self, request, node, data)
import gtk
def _our_mainquit(): # XXX: gtk.main_quit() (which is used for crash()) raises an exception if # gtk.main_level() == 0; however, all the tests freeze if we use this # function to stop the reactor. what gives? if gtk.main_level(): gtk.main_quit()
self.__crash = gtk.main_quit
self.__crash = _our_mainquit
def __init__(self, useGtk=True): self.context = gobject.main_context_default() self.loop = gobject.MainLoop() posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the glib iteration and mainloop functions didn't release # global interpreter lock, thus breaking thread and signal support. if (hasattr(gobject, "pygtk_ve...
d=utils.getProcessOutput(exe, ['-c', 'print "hello world"']) d.addCallback(self.saveOutput) ttl = time.time() + 5 while self.output is None and time.time() < ttl: reactor.iterate(0.01) self.failIf(self.output is None, "timeout") self.assertEquals(self.output, "hello world\n")
scriptFile = self.makeSourceFile( 'import sys\n' 'sys.stderr.write("hello world\\n")\n')
def testOutput(self): exe = sys.executable d=utils.getProcessOutput(exe, ['-c', 'print "hello world"']) d.addCallback(self.saveOutput) ttl = time.time() + 5 while self.output is None and time.time() < ttl: reactor.iterate(0.01) self.failIf(self.output is None, "timeout") self.assertEquals(self.output, "hello world\n")
def testOutputWithError(self):
d = utils.getProcessOutput(exe, [scriptFile], errortoo=0) return assertions.assertFailure(d, IOError) def testOutputWithErrorCollected(self):
def testOutputWithError(self): exe = sys.executable sx = r'import sys; sys.stderr.write("hello world\n")' res1 = [] # make sure stderr raises an error normally d = utils.getProcessOutput(exe, ['-c', sx], errortoo=0) d.addBoth(res1.append) ttl = time.time() + 5 while len(res1) == 0 and time.time() < ttl: reactor.iterate...
sx = r'import sys; sys.stderr.write("hello world\n")' res1 = [] d = utils.getProcessOutput(exe, ['-c', sx], errortoo=0) d.addBoth(res1.append) ttl = time.time() + 5 while len(res1) == 0 and time.time() < ttl: reactor.iterate(0.01) self.failUnless(len(res1), "timeout") self.failUnless(isinstance(res1.pop().value, IOErr...
scriptFile = self.makeSourceFile( 'import sys\n' 'sys.stderr.write("hello world\\n")\n') d = utils.getProcessOutput(exe, [scriptFile], errortoo=1) return d.addCallback(self.assertEquals, "hello world\n")
def testOutputWithError(self): exe = sys.executable sx = r'import sys; sys.stderr.write("hello world\n")' res1 = [] # make sure stderr raises an error normally d = utils.getProcessOutput(exe, ['-c', sx], errortoo=0) d.addBoth(res1.append) ttl = time.time() + 5 while len(res1) == 0 and time.time() < ttl: reactor.iterate...
d=utils.getProcessValue(exe, ['-c', 'import sys;sys.exit(1)']) d.addCallback(self.saveValue) ttl = time.time() + 5 while self.value is None and time.time() < ttl: reactor.iterate(0.01) self.failIf(self.value is None, "timeout") self.assertEquals(self.value, 1)
scriptFile = self.makeSourceFile( "import sys\n" "sys.exit(1)\n")
def testValue(self): exe = sys.executable d=utils.getProcessValue(exe, ['-c', 'import sys;sys.exit(1)']) d.addCallback(self.saveValue) ttl = time.time() + 5 while self.value is None and time.time() < ttl: reactor.iterate(0.01) self.failIf(self.value is None, "timeout") self.assertEquals(self.value, 1)
def saveValue(self, o): self.value = o def saveOutput(self, o): self.output = o
d = utils.getProcessValue(exe, [scriptFile]) return d.addCallback(self.assertEquals, 1)
def saveValue(self, o): self.value = o
sx = r'import sys; sys.stdout.write("hello world!\n"); ' \ r'sys.stderr.write("goodbye world!\n"); sys.exit(1)' result = [] d = utils.getProcessOutputAndValue(exe, ['-c', sx]) d.addCallback(result.append) ttl = time.time() + 5 while len(result) == 0 and time.time() < ttl: reactor.iterate(0.01) self.failUnless(len(resul...
scriptFile = self.makeSourceFile( "import sys\n" "sys.stdout.write('hello world!\\n')\n" "sys.stderr.write('goodbye world!\\n')\n" "sys.exit(1)") def gotOutputAndValue((out, err, code)): self.assertEquals(out, "hello world!\n") self.assertEquals(err, "goodbye world!\n") self.assertEquals(code, 1) d = utils.getProcessO...
def testOutputAndValue(self): exe = sys.executable sx = r'import sys; sys.stdout.write("hello world!\n"); ' \ r'sys.stderr.write("goodbye world!\n"); sys.exit(1)' result = [] d = utils.getProcessOutputAndValue(exe, ['-c', sx]) d.addCallback(result.append) ttl = time.time() + 5 while len(result) == 0 and time.time() < t...
sx = r'import os, signal;os.kill(os.getpid(), signal.SIGKILL)' result = [] d = utils.getProcessOutputAndValue(exe, ['-c', sx]) d.addErrback(result.append) ttl = time.time() + 5 while len(result) == 0 and time.time() < ttl: reactor.iterate(0.01) self.failUnless(len(result), "timeout") actual = result[0].value expected =...
scriptFile = self.makeSourceFile( "import sys, os, signal\n" "sys.stdout.write('stdout bytes\\n')\n" "sys.stderr.write('stderr bytes\\n')\n" "sys.stdout.flush()\n" "sys.stderr.flush()\n" "os.kill(os.getpid(), signal.SIGKILL)\n")
def testOutputSignal(self): # Use SIGKILL here because it's guaranteed to be delivered. Using # SIGHUP might not work in, e.g., a buildbot slave run under the # 'nohup' command. exe = sys.executable sx = r'import os, signal;os.kill(os.getpid(), signal.SIGKILL)' result = [] d = utils.getProcessOutputAndValue(exe, ['-c',...
if not interfaces.IReactorProcess(reactor, None):
def gotOutputAndValue(err): (out, err, sig) = err.value self.assertEquals(out, "stdout bytes\n") self.assertEquals(err, "stderr bytes\n") self.assertEquals(sig, signal.SIGKILL) d = utils.getProcessOutputAndValue(exe, [scriptFile]) return d.addErrback(gotOutputAndValue) if interfaces.IReactorProcess(reactor, None) is ...
def testOutputSignal(self): # Use SIGKILL here because it's guaranteed to be delivered. Using # SIGHUP might not work in, e.g., a buildbot slave run under the # 'nohup' command. exe = sys.executable sx = r'import os, signal;os.kill(os.getpid(), signal.SIGKILL)' result = [] d = utils.getProcessOutputAndValue(exe, ['-c',...
components.fixClassImplements(Sub) components.fixClassImplements(MultiplyAndAdd)
def testClasses(self): # is this a right thing to do? self.assert_( IMultiply.implementedBy(MultiplyAndAdd) ) self.assert_( IAdder.implementedBy(MultiplyAndAdd) ) self.assert_( IAdder.implementedBy(Sub) ) self.assert_( ISub.implementedBy(Sub) )
el=doc1.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName
el1=doc1.documentElement actual=domhelpers.getElementsByTagName(el1, 'foo')[0].nodeName
def test_getElementsByTagName(self): doc1=microdom.parseString('<foo/>') actual=domhelpers.getElementsByTagName(doc1, 'foo')[0].nodeName expected='foo' self.assertEquals(actual, expected) el=doc1.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName self.assertEqual(actual, expected)
el=doc2.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName
el2=doc2.documentElement tag_list=domhelpers.getElementsByTagName(el2, 'foo') actual=''.join([node.getAttribute('in') for node in tag_list])
def test_getElementsByTagName(self): doc1=microdom.parseString('<foo/>') actual=domhelpers.getElementsByTagName(doc1, 'foo')[0].nodeName expected='foo' self.assertEquals(actual, expected) el=doc1.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName self.assertEqual(actual, expected)
el=doc3.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName
el3=doc3.documentElement tag_list=domhelpers.getElementsByTagName(el3, 'foo') actual=''.join([node.getAttribute('in') for node in tag_list])
def test_getElementsByTagName(self): doc1=microdom.parseString('<foo/>') actual=domhelpers.getElementsByTagName(doc1, 'foo')[0].nodeName expected='foo' self.assertEquals(actual, expected) el=doc1.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName self.assertEqual(actual, expected)
el=doc4.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName
actual=domhelpers.getElementsByTagName(root, 'foo')
def test_getElementsByTagName(self): doc1=microdom.parseString('<foo/>') actual=domhelpers.getElementsByTagName(doc1, 'foo')[0].nodeName expected='foo' self.assertEquals(actual, expected) el=doc1.documentElement actual=domhelpers.getElementsByTagName(el, 'foo')[0].nodeName self.assertEqual(actual, expected)
if path == '': return self
def getChild(self, path, request): """See twisted.web.Resource.getChild. """ if path == '': return self
childPath = os.path.join(self.path, path)
if path == '': childPath = self.path else: childPath = os.path.join(self.path, path)
def getChild(self, path, request): """See twisted.web.Resource.getChild. """ if path == '': return self
socket.getservbyname = lambda s, p,n=self.n: s == 'http' and p == 'tcp' and n or 10
socket.getservbyname = (lambda s, p,n=self.n: s == 'http' and p == 'tcp' and n or 10)
def testConnectByService(self): serv = socket.getservbyname 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 = MyClientFactory() try: c = reactor.co...
p = reactor.listenTCP(0, AServerFactory(self, IPv4Address('TCP', '127.0.0.1', portno)))
f = AServerFactory(self, IPv4Address('TCP', '127.0.0.1', portno)) p = reactor.listenTCP(0, f)
def testBuildProtocol(self): portno = self.getFreePort()
ProperlyCloseFilesTestCase.numberRounds = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + 10
numRounds = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + 10 ProperlyCloseFilesTestCase.numberRounds = numRounds
def testWriteNotificationRaises(self): self.client.writeConnectionLost = self.aBug self.client.transport.loseWriteConnection() spinUntil(lambda :self.client.closed) log.flushErrors(RuntimeError)
for childNum in range(node.childNodes.length):
if hasattr(node.childNodes, 'length'): length = node.childNodes.length else: length = len(node.childNodes) for childNum in length:
def _get(node, nodeId): if hasattr(node, 'hasAttributes') and node.hasAttributes() and ((str(node.getAttribute("id")) == nodeId) or (str(node.getAttribute("class")) == nodeId) or (str(node.getAttribute("model")) == nodeId)): return node if node.hasChildNodes(): for childNum in range(node.childNodes.length): result = _g...
@param dest: C{URL}. This should be a *physical* URL, not a logical one.
@param destURL: C{URL}. This should be a *physical* URL, not a logical one.
def sendMessage(self, destURL, message): """Send a message.
@param userURL: a logical C{URL}.
@param logicalURL: a logical C{URL}.
def getAddress(self, logicalURL): """Return physical URL of server for logical URL of user.
@type peer: The client's address
@param peer: The client's address
def getChallenge(self, peer): """Generate a challenge the client may respond to. @type peer: C{tuple} @type peer: The client's address @rtype: C{str} @return: The challenge string """
if ose.errno == errno.EPERM:
if ose.errno in (errno.EACCES, errno.ENOENT):
def _clearCache(self): try: os.remove(sibpath(plugins.__file__, 'dropin.cache')) except OSError, ose: if ose.errno == errno.EPERM: print 'Testing in deployed mode.' else: raise
except OSError, ose: if ose.errno == errno.EPERM: raise unittest.SkiptTest(
except IOError, ioe: if ioe.errno == errno.EACCES: raise unittest.SkipTest(
def _testDetectNewFiles(self): writeFileName = sibpath(plugins.__file__, 'pluginextra.py') try: wf = file(writeFileName, 'w') except OSError, ose: if ose.errno == errno.EPERM: raise unittest.SkiptTest( "No permission to add things to twisted.plugins") else: raise else: try: wf.write(begintest) wf.flush()
writeFile = file(writeFileName, 'w')
try: writeFile = file(writeFileName, 'w') except IOError, ioe: if ioe.errno == errno.EACCES: raise unittest.SkipTest( "No permission to add things to twisted.plugins") else: raise
def _testDetectFilesChanged(self): writeFileName = sibpath(plugins.__file__, 'pluginextra.py') writeFile = file(writeFileName, 'w') try: writeFile.write(begintest) writeFile.flush() plgs = list(plugin.getPlugIns(plugin.ITestPlugin)) # Sanity check self.assertEquals( len(plgs), 2, "Unexpected plugins found: %r" % ( [p._...
print repr(data) d = self.sendGlobalRequest('tcpip-forward', data, 1)
d = self.sendGlobalRequest('tcpip-forward', data)
def serviceStarted(self): if not options['notty']: self.openChannel(SSHSession()) if options.localForwards: for localPort, hostport in options.localForwards: reactor.listenTCP(localPort, forwarding.SSHLocalForwardingFactory(self, hostport)) if options.remoteForwards: for remotePort, hostport in options.remoteForwards: ...
d.addCallback(self.reply) def reply(self, data): log.msg('GLOBAL MESSAGE REPLY: %s' % repr(data))
def serviceStarted(self): if not options['notty']: self.openChannel(SSHSession()) if options.localForwards: for localPort, hostport in options.localForwards: reactor.listenTCP(localPort, forwarding.SSHLocalForwardingFactory(self, hostport)) if options.remoteForwards: for remotePort, hostport in options.remoteForwards: ...
if s:
if s and not self.raw:
def gotTagStart(self, name, attributes): s = getattr(self, "mapStart_"+name, None) if s: self.writer(s) m = getattr(self, "start_"+name, None) m and m(name, attributes)
if s:
if s and not self.raw:
def gotTagEnd(self, name): s = getattr(self, "mapEnd_"+name, None) if s: self.writer(s) m = getattr(self, "end_"+name, None) m and m(name)
write('''<table border=0 cellpadding=2> <tr>''')
write('''<table border=0 cellpadding=2 width=100%> ''') write('''<tr><td colspan=7 bgcolor=black><font color=white><center><b>%s %s</b></center></font></td></tr> <tr>'''%(calendar.month_name[self.month],self.year))
def stream(self,write,request): write('''<table border=0 cellpadding=2>
write("</center></td>")
write("</center></td>\n")
def stream(self,write,request): write('''<table border=0 cellpadding=2>
%%%%displayAuth(request)%%%%
%%%%displayFooter(request)%%%%
def process(self,write,request,day,month,year,title,data):
def __init__(self,password=None,filename=None):
def __init__(self,password="twisted",filename=None):
def __init__(self,password=None,filename=None): widgets.Page.__init__(self) self.password=password self.events={} self.filename=filename self.loadPickle()
def setDate(self,request): curtime=time.localtime(time.time()) if request.args.has_key("m"): self.month=int(request.args['m'][0]) else: self.month=curtime[1] if request.args.has_key("y"): self.year=int(request.args['y'][0]) else: self.year=curtime[0] request.auth=0
def setValues(self,request): self.auth=0
def setDate(self,request): curtime=time.localtime(time.time()) if request.args.has_key("m"): self.month=int(request.args['m'][0]) else: self.month=curtime[1] if request.args.has_key("y"): self.year=int(request.args['y'][0]) else: self.year=curtime[0] request.auth=0 if request.postpath: if self.password: if request.post...
if self.password: if request.postpath[0]==self.password: request.auth=1 del request.postpath[0] else: request.auth=1
if request.postpath[0]==self.password: self.auth=1 del request.postpath[0]
def setDate(self,request): curtime=time.localtime(time.time()) if request.args.has_key("m"): self.month=int(request.args['m'][0]) else: self.month=curtime[1] if request.args.has_key("y"): self.year=int(request.args['y'][0]) else: self.year=curtime[0] request.auth=0 if request.postpath: if self.password: if request.post...
if int(request.postpath[0])<=12 and int(request.postpath[0])>=1: self.month=int(request.postpath[0]) del request.postpath[0] if request.postpath: self.year=int(request.postpath[0]) if self.year==0: self.year=2000 elif self.year<100: self.year=1900+self.year del request.postpath[0] except ValueError: pass
test=int(request.postpath[0]) self.command="calendar" self.options=request.postpath except: self.command=request.postpath[0] self.options=request.postpath[1:] else: self.command="calendar" self.options=[] request.postpath=[] def setDate(self): curtime=time.localtime(time.time()) self.month=curtime[1] self.year=curtime...
def setDate(self,request): curtime=time.localtime(time.time()) if request.args.has_key("m"): self.month=int(request.args['m'][0]) else: self.month=curtime[1] if request.args.has_key("y"): self.year=int(request.args['y'][0]) else: self.year=curtime[0] request.auth=0 if request.postpath: if self.password: if request.post...
self.setDate(request) return calendar.month_name[self.month]+" "+str(self.year)
self.setValues(request) func=getattr(self,"title_%s"%self.command,None) if func: return func(request) else: return "No Title"
def title(self,request): self.setDate(request) return calendar.month_name[self.month]+" "+str(self.year)
if not request.postpath: return self.displayCalendar(request)
func=getattr(self,"page_%s"%self.command,None) if func: return func(request)
def displayPage(self,request): #self.setDate(request) if not request.postpath: return self.displayCalendar(request) else: if request.postpath[0]=="event": year,month,day,ind=map(int,request.postpath[1:]) return self.events[year][month][day][ind] elif request.auth and self.displayAuth(request): return "" else: return er...
if request.postpath[0]=="event": year,month,day,ind=map(int,request.postpath[1:]) return self.events[year][month][day][ind] elif request.auth and self.displayAuth(request): return "" else: return error.NoResource(string.join(request.postpath,"/")).render(request) def displayCalendar(self,request): return CalendarWidge...
return "No page for command %s"%self.command def displayFooter(self,request): func=getattr(self,"footer_%s"%self.command,None) if func: return func(request)
def displayPage(self,request): #self.setDate(request) if not request.postpath: return self.displayCalendar(request) else: if request.postpath[0]=="event": year,month,day,ind=map(int,request.postpath[1:]) return self.events[year][month][day][ind] elif request.auth and self.displayAuth(request): return "" else: return er...
return """<a href="%s">Back To the Calendar</a>"""%url def displayAuth(self,request): if request.auth: if request.postpath and request.postpath[0]=="post": return PostForm(self) elif request.postpath and request.postpath[0]=="event": return """<a href="%s/%s/%s/%s/%s">Delete</a>""" % ( request.sibLink("%s/delete"%self...
def backToCalendar(self,request): url="/"+string.join(request.prepath,"/") if request.auth: return """<a href="%s">Back To the Calendar</a>"""%(url+"/"+self.password) else: return """<a href="%s">Back To the Calendar</a>"""%url
c=c+"""<a href="%s/event/%s/%s/%s/%s">%s</a><br>""" % ( request.path,
c=c+"""* <a href="%s/event/%s/%s/%s/%s">%s</a><br> """ % ( self.currentPath(request),
def getDay(self,request,day,month,year): if not self.events.has_key(year): return if not self.events[year].has_key(month): return if not self.events[year][month].has_key(day): return c="" for event in self.events[year][month][day]: c=c+"""<a href="%s/event/%s/%s/%s/%s">%s</a><br>""" % ( request.path, year, month, day, ...
self.data=data
self.data=string.replace(data,"\n","<br>\n")
def __init__(self,day,month,year,title,data): self.day=day self.month=month self.year=year self.title=title self.data=data
self.deferredContext = self._getChild(requestContext, site.getRootResource(), self.postpath)
self.deferredContext = self._getChild(requestContext, self.site.getRootResource(), self.postpath)
def process(self): "Process a request." # get site from channel if not self.site: self.site = self.chanRequest.channel.site self.defaultHeaders() self.parseURL() self.host = self.getHost() if not self.host: return # Resource Identification if self.prepathuri: # We were given an initial prepath. prepath = map(unquote, s...
self.handleSegment, path, newctx
self._handleSegment, path, newctx
def _getChild(self, ctx, res, path): """Create a PageContext for res, call res.locateChild, and pass the result on to _handleSegment.""" # Create a context object to represent this new resource newctx = context.PageContext(tag=res, parent=ctx) newctx.remember(tuple(self.prepath), iweb.ICurrentSegments) newctx.remember...
log.msg("cleaning popsicle")
def clean(self): """Persistence tick. Clean out the fridge, persist everything that wants to be saved. """ log.msg("cleaning popsicle") self.cleaning = True savers = {} try: while self.dirtySet: l = self.dirtySet.items() self.dirtySet.clear() for obj, doSave in l: ent = self.persistentObjects.get(obj) if not ent: cont...
paths = filter(os.path.isdir, map(cacheTransform, sys.path))
paths = filter(os.path.isdir, map(cacheTransform, filter(lambda x:isinstance(x, type('')), sys.path)))
def getPluginFileList(debugInspection=None, showProgress=None): """Find plugin.tml files in subdirectories of paths in C{sys.path} @type debugInspection: C{None} or a callable taking one argument @param debugInspection: If not None, this is invoked with strings containing debug information about the loading process. ...
if not (options['noshell'] and options['fork']):
if not options['noshell']:
def onConnect(): if not (options['noshell'] and options['fork']): conn.openChannel(SSHSession()) if options.localForwards: for localPort, hostport in options.localForwards: reactor.listenTCP(localPort, forwarding.SSHListenForwardingFactory(conn, hostport, SSHListenClientForwardingChannel)) if options.remoteForwards: fo...
if len(conn.channels) == 1 and not (options['fork'] and not options['nocache']):
if len(conn.channels) == 1 and not (options['noshell'] and not options['nocache']):
def closed(self): self.unix.sendMessage('closed', self.id) if len(conn.channels) == 1 and not (options['fork'] and not options['nocache']): # just us left reactor.stop()
if len(self.conn.channels) == 1 and not (options['fork'] and not options['nocache']):
if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']):
def closed(self): log.msg('closed %s' % self) if len(self.conn.channels) == 1 and not (options['fork'] and not options['nocache']): # just us left reactor.stop()
if len(self.conn.channels) == 1 and not (options['fork'] and not options['nocache']):
if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']):
def closed(self): forwarding.SSHListenClientForwardingChannel.closed(self) if len(self.conn.channels) == 1 and not (options['fork'] and not options['nocache']): # just us left reactor.stop()
f.results = []
del f.results[:len(result)]
def process(): coop = f._yield() if f.results: result.extend(f.results) f.results = [] reactor.callLater(0, process) return if coop: sleep(.3) reactor.callLater(0, coop.callLater, process) return if f.stop: reactor.callLater(0, d.callback, result)
handleStatus_200 = lambda *args: None
def handleStatus_200(self): self.factory.gotHeaders(self.headers)
self.addresses = {}
self.addresses = {} self.resolver._sendQuery([dns.Query(service, dns.PTR, dns.IN)])
def __init__(self, service, resolver): self.service = service self.resolver = resolver self.subscribers = [] self.addresses = {} # map name to (host, port)
del self.service.subscriptions[self.service]
self.resolver._removeSubscription(self.service)
def unsubscribe(self, subscriber): self.subscribers.remove(subscriber) if not self.subscribers: del self.service.subscriptions[self.service]
self.subscriptions = {}
self.subscriptions = {} self.cachedDomains = {}
def __init__(self): self.protocol = mDNSDatagramProtocol(self) self.subscriptions = {}
self._sendQuery([dns.Query('_workstation._tcp.local', dns.PTR, dns.IN)])
def startListening(self): self.protocol.startListening() # XXX set QU self._sendQuery([dns.Query('_workstation._tcp.local', dns.PTR, dns.IN)])
subscription.gotSRV(name, r.payload)
reactor.callLater(0, subscription.gotSRV, name[:-len(service) - 1], r.payload)
def messageReceived(self, message, protocol, address = None): #print message.queries, message.answers for r in message.answers: if r.type == dns.PTR: service = r.name.name if self.subscriptions.has_key(service): self._sendQuery([dns.Query(r.payload.name.name, dns.SRV, dns.IN)]) elif r.type == dns.SRV: name = r.name.nam...
def serviceAdded(self, *args): print args
def _resolved(self, ip, host): print host, "is actually", ip def serviceAdded(self, name, host, port): print "%s is ('%s', %s)" % (name, host, port) d.getIP(host).addCallback(self._resolved, host)
def serviceAdded(self, *args): print args
d.startListening()
def serviceAdded(self, *args): print args
return self.remote._prePathURL
return self._prePathURL
def prePathURL(self): return self.remote._prePathURL
if cm.func_code.co_argcount == 1 and not type(vm) == types.LambdaType:
if cm.func_code.co_argcount == 1 and not type(cm) == types.LambdaType:
def getSubcontroller(self, request, node, model, controllerName): controller = None cm = getattr(self, 'wcfactory_' + controllerName, None) if cm is None: cm = getattr(self, 'factory_' + controllerName, None) if cm is not None: warnings.warn("factory_ methods are deprecated; please use " "wcfactory_ instead", Deprecati...
"Wrap <pre> tags around some text and escape it with web.escapehtml."
"Wrap <pre> tags around some text and HTML-escape it."
def PRE(text): "Wrap <pre> tags around some text and escape it with web.escapehtml." return "<pre>"+escape(text)+"</pre>"
import shutil shutil.copyfile('win32/twisted-postinstall.py', 'twisted-postinstall.py') setup_args['scripts'].append('twisted-postinstall.py')
setup_args['scripts'].append('win32/twisted-postinstall.py')
def _detect_modules(self): """ Determine which extension modules we should build on this system. """
self.sendCode(250, '%s Hello %s, nice to meet you' % (self.host, peer))
self.sendCode(250, '%s Hello %s, nice to meet you' % (self.host, host))
def do_HELO(self, rest): peer = self.transport.getPeer() try: host = peer.host except AttributeError: host = str(peer) self._helo = (rest, host) self._from = None self._to = [] self.sendCode(250, '%s Hello %s, nice to meet you' % (self.host, peer))
timeOut = 60 * 60 * 12
def connectionLost(self, reason): """connection was lost""" pass
_getDebugger().run("suite.run(config['random'])", globals(), locals())
suite.debugger = suite.reporter.debugger = True suite.run(config['random'])
def _doRun(config): suite = _getSuite(config) _getDebugger().run("suite.run(config['random'])", globals(), locals()) return suite