rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
raise IRCBadMessage, "malformed DCC ACCEPT request: %r" % (data,)
raise IRCBadMessage, "malformed DCC SEND ACCEPT request: %r" % (data,)
def dcc_ACCEPT(self, user, channel, data): data = text.splitQuoted(data) if len(data) < 3: raise IRCBadMessage, "malformed DCC ACCEPT request: %r" % (data,) (filename, port, resumePos) = data[:3]
def dcc_RESUME(self, user, channel, data):
def dcc_SEND_RESUME(self, user, channel, data):
def dcc_RESUME(self, user, channel, data): data = text.splitQuoted(data) if len(data) < 3: raise IRCBadMessage, "malformed DCC RESUME request: %r" % (data,) (filename, port, resumePos) = data[:3] self.dccDoResume(user, filename, port, resumePos)
raise IRCBadMessage, "malformed DCC RESUME request: %r" % (data,)
raise IRCBadMessage, "malformed DCC SEND RESUME request: %r" % (data,)
def dcc_RESUME(self, user, channel, data): data = text.splitQuoted(data) if len(data) < 3: raise IRCBadMessage, "malformed DCC RESUME request: %r" % (data,) (filename, port, resumePos) = data[:3] self.dccDoResume(user, filename, port, resumePos)
lines = string.split(line,'\n') for line in lines: line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(p...
line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, params) except IRCBadMessage: apply...
def lineReceived(self, line): # some servers (dalnet!) break RFC and send their first few # lines just delimited by \n lines = string.split(line,'\n') for line in lines: line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] ...
elif None not in self.resultList:
elif self.finishedCount == len(self.resultList):
def _cbDeferred(self, result, index, succeeded): """(internal) Callback for when one of my deferreds fires. """ self.resultList[index] = (succeeded, result)
def accept(self, destdir=None, filename=None, resume_overwrite=False): """ We will attempt to open the destination path immediately. If that fails, either IOError or DccDestFileExists will be raised. If successful, a Deferred will be returned. It will fire when the file is saved, or errback is something funky happens ...
def accept(self, destfile=None, resume_overwrite=False): """ Call this to retreive and save the incoming dcc file. The 'destfile' parameter is optional. If unset, we will use the default directory and filename. Or you may pass a path to use, or an open file-like-object that data will be written to. Unless you pass a ...
def accept(self, destdir=None, filename=None, resume_overwrite=False): """ We will attempt to open the destination path immediately. If that fails, either IOError or DccDestFileExists will be raised. If successful, a Deferred will be returned. It will fire when the file is saved, or errback is something funky happens ...
if destdir == None: destdir = self.default_destdir if filename == None: filename = self.default_filename if destdir.endswith(path.sep): destpath = destdir + filename else: destpath = destdir + path.sep + filename
if hasattr(destfile, 'write'): self.file_obj = destfile else: if destfile is None: destfile = self.default_filename elif type(destfile) == types.StringType: pass else: raise 'destfile must be None, a string, or a file-like-object'
def accept(self, destdir=None, filename=None, resume_overwrite=False): """ We will attempt to open the destination path immediately. If that fails, either IOError or DccDestFileExists will be raised. If successful, a Deferred will be returned. It will fire when the file is saved, or errback is something funky happens ...
if path.exists(destpath): if not resume_overwrite: raise DccFileExists() if resume_overwrite == 'resume': self.file_obj = file(destpath, 'a+b')
if path.exists(destfile): if not resume_overwrite: raise DccFileExists() if resume_overwrite == 'resume': self.file_obj = file(destfile, 'a+b') else: self.file_obj = file(destfile, 'wb') if resume_overwrite == 'resume':
def accept(self, destdir=None, filename=None, resume_overwrite=False): """ We will attempt to open the destination path immediately. If that fails, either IOError or DccDestFileExists will be raised. If successful, a Deferred will be returned. It will fire when the file is saved, or errback is something funky happens ...
else: self.file_obj = file(destpath, 'wb')
else:
def accept(self, destdir=None, filename=None, resume_overwrite=False): """ We will attempt to open the destination path immediately. If that fails, either IOError or DccDestFileExists will be raised. If successful, a Deferred will be returned. It will fire when the file is saved, or errback is something funky happens ...
self.destdir = destdir self.filename = filename self.destpath = destpath
def accept(self, destdir=None, filename=None, resume_overwrite=False): """ We will attempt to open the destination path immediately. If that fails, either IOError or DccDestFileExists will be raised. If successful, a Deferred will be returned. It will fire when the file is saved, or errback is something funky happens ...
howLong = 2000 while howLong and len(f.allMessages) != 2: howLong -= 1
now = time.time() while len(f.allMessages) != 2 and (time.time() < now + 5):
def testStopTrying(self): f = Factory() f.protocol = In f.connections = 0 f.allMessages = []
return response.NOT_FOUND
return responsecode.NOT_FOUND
def render(self, ctx): """You know what you doing.""" self.fp.restat() request = iweb.IRequest(ctx) response = http.Response() if self.type is None: self.type, self.encoding = getTypeAndEncoding(self.fp.basename(), self.contentTypes, self.contentEncodings, self.defaultType)
self.processors = processors
self.processors = dict([ (key.lower(), value) for key, value in processors.items() ])
def __init__(self, path, defaultType="text/plain", ignoredExts=(), processors=None, indexNames=None): """Create a file with the given path. """ self.fp = filepath.FilePath(path) # Remove the dots from the path to split self.defaultType = defaultType self.ignoredExts = list(ignoredExts) self.children = {} if processors ...
if platformType == "win32": processor = InsensitiveDict(self.processors).get(fpath.splitext()[1]) else: processor = self.processors.get(fpath.splitext()[1])
processor = self.processors.get(fpath.splitext()[1].lower())
def locateChild(self, ctx, segments): r = self.children.get(segments[0], None) if r: return r, segments[1:] path=segments[0] self.fp.restat() if not self.fp.isdir(): return None, ()
@cvar method: The HTTP method that was used. @cvar uri: The full URI that was requested (includes arguments).
Subclasses should override the process() method to determine how the request will be processed. @ivar method: The HTTP method that was used. @ivar uri: The full URI that was requested (includes arguments).
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)
__implements__ = interfaces.IConsumer
__implements__ = interfaces.IConsumer,
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 len(f.value.args) > 1:
if len(f.value.args) > 0:
def _eb(self, f): log.msg(f.printTraceback()) if isinstance(f.value, util.DirtyReactorWarning): # This will eventually become an error, but for now # we delegate the responsibility of warning the user # to the reporter so that we can test for this self.getReporter().cleanupErrors(f) elif f.check(unittest.FAILING_EXCEPT...
l.signal_connect('delete_event', self.closeConsole)
def on_ConsoleButton_clicked(self, b): #### For debugging purposes... from twisted.manhole.ui.pywidgets import LocalInteraction l = LocalInteraction() l.localNS['chat'] = self.chatui l.signal_connect('delete_event', self.closeConsole) l.show_all()
def closeConsole(self, w, evt): return 1
def on_ConsoleButton_clicked(self, b): #### For debugging purposes... from twisted.manhole.ui.pywidgets import LocalInteraction l = LocalInteraction() l.localNS['chat'] = self.chatui l.signal_connect('delete_event', self.closeConsole) l.show_all()
reads[reader] = self._makeSocketEvent(reader, reader.doRead, FD_READ|FD_ACCEPT|FD_CONNECT|FD_CLOSE)
reads[reader] = self._makeSocketEvent(reader, 'doRead', FD_READ|FD_ACCEPT|FD_CONNECT|FD_CLOSE)
def addReader(self, reader, reads=reads): """Add a socket FileDescriptor for notification of data available to read. """ if not reads.has_key(reader): reads[reader] = self._makeSocketEvent(reader, reader.doRead, FD_READ|FD_ACCEPT|FD_CONNECT|FD_CLOSE)
closed = action()
closed = getattr(fd, action)()
def _runAction(self, action, fd): try: closed = action() except: closed = sys.exc_info()[1] log.deferr()
self._disconnectSelectable(fd, closed, action == fd.doRead)
self._disconnectSelectable(fd, closed, action == 'doRead')
def _runAction(self, action, fd): try: closed = action() except: closed = sys.exc_info()[1] log.deferr()
testPath = os.path.join("twisted", 'test') testFiles = ['server.pem', 'template.tpl']
loreTestPath = os.path.join('twisted', 'lore', 'test') loreTestFiles = ['template.tpl'] webTestPath = os.path.join('twisted', 'web', 'test') webTestFiles = ['server.pem']
def _detect_modules(self): """ Determine which extension modules we should build on this system. """
(testPath, testFiles),
(loreTestPath, loreTestFiles), (webTestPath, webTestFiles),
def _detect_modules(self): """ Determine which extension modules we should build on this system. """
def sendMessage(self): self.perspective.do(self.input.get_text(), pbcallback=self.messageReceived)
def sendMessage(self, unused_data=None): self.perspective.do(self.input.get_chars(0,-1), pbcallback=self.messageReceived)
def sendMessage(self): self.perspective.do(self.input.get_text(), pbcallback=self.messageReceived)
else:
elif err.check(ecred.UnauthorizedLogin):
def _ebLogin(self, err, nickname): if err.check(ewords.AlreadyLoggedIn): self.privmsg( NICKSERV, nickname, "Already logged in. No pod people allowed!") else: self.privmsg( NICKSERV, nickname, "Login failed. Goodbye.") self.transport.loseConnection()
assert isinstance(avatarId, str)
if isinstance(avatarId, str): avatarId = avatarId.decode(self._encoding)
def requestAvatar(self, avatarId, mind, *interfaces): assert isinstance(avatarId, str)
avatarId = avatarId.decode(self._encoding)
def gotAvatar(avatar): if avatar.realm is not None: raise ewords.AlreadyLoggedIn() for iface in interfaces: facet = iface(avatar, None) if facet is not None: avatar.loggedIn(self, mind) mind.name = avatarId mind.realm = self mind.avatar = avatar return iface, facet, self.logoutFactory(avatar, facet) raise NotImplemente...
mode = COMMAND __from_ = None __helo = None __to = ()
def __init__(self): self.mode = COMMAND self.__from = None self.__helo = None self.__to = ()
def __init__(self, destination, helo, protocol, orig): try: self.name, self.domain = string.split(destination, '@', 1) except ValueError: self.name = destination self.domain = '' self.helo = helo self.protocol = protocol self.orig = orig
def handleMessage(self, helo, origin, recipients, message,
def handleMessage(self, recipients, message,
def handleMessage(self, helo, origin, recipients, message, success, failure): success()
def joined(self, group):
def joined(self, channel):
def joined(self, group): """Called when I finish joining a channel. """
"""
channel has the starting character ( """ pass
def joined(self, group): """Called when I finish joining a channel. """
self.sendLine("JOIN else: self.sendLine("JOIN
self.sendLine("JOIN %s %s" (channel, key)) else: self.sendLine("JOIN %s" % (channel,))
def join(self, channel, key=None): if key: self.sendLine("JOIN #%s %s" (channel, key)) else: self.sendLine("JOIN #%s" % (channel,))
self.sendLine("PART else: self.sendLine("PART
self.sendLine("PART %s :%s" % (channel, reason)) else: self.sendLine("PART %s" % (channel,))
def leave(self, channel, reason=None): if reason: self.sendLine("PART #%s :%s" % (channel, reason)) else: self.sendLine("PART #%s" % (channel,))
self.sendLine("PRIVMSG
if channel[0] not in '& self.sendLine("PRIVMSG %s :%s" % (channel, message))
def say(self, channel, message): self.sendLine("PRIVMSG #%s :%s" % (channel, message))
self.ctcpMakeQuery('
if channel[0] not in '& self.ctcpMakeQuery(channel, [('ACTION', action)])
def me(self, channel, action): """Strike a pose. """ self.ctcpMakeQuery('#' + channel, [('ACTION', action)])
self.joined(params[-1][1:])
nick = string.split(prefix,'!')[0] if nick == self.nickname: self.joined(params[-1])
def irc_JOIN(self, prefix, params): self.joined(params[-1][1:])
line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, params) except IRCBadMessage: apply...
lines = string.split(line,'\n') for line in lines: line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(p...
def lineReceived(self, line): line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, param...
self.bytesReceived = self.bytesReceived + len(data)
def dataReceived(self, data): """Called when data is received.
return type_, luid, jstate
l.extend([type_, luid, jstate]) return jellier.preserve(self, l)
def jellyFor(self, jellier): """Return an appropriate tuple to serialize me.
return self.processWidget(request, widget, node)
return self.processWidget(request, result, node)
def dispatchResult(self, request, node, result): """ Check a given result from handling a node and hand it to a process* method which will convert the result into a node and insert it into the DOM tree. Return the new node. """ if isinstance(result, Widget): return self.processWidget(request, widget, node) elif isinsta...
return self.processString(request, string, node)
return self.processString(request, result, node)
def dispatchResult(self, request, node, result): """ Check a given result from handling a node and hand it to a process* method which will convert the result into a node and insert it into the DOM tree. Return the new node. """ if isinstance(result, Widget): return self.processWidget(request, widget, node) elif isinsta...
child = parseString(html)
child = minidom.parseString(html)
def processString(self, request, html, node): try: child = parseString(html) except Exception, e: print "damn, error parsing, probably invalid xml", e child = self.d.createTextNode(html) return self.processNode(request, child, node)
print "damn, error parsing, probably invalid xml", e
print "damn, error parsing, probably invalid xml:", e
def processString(self, request, html, node): try: child = parseString(html) except Exception, e: print "damn, error parsing, probably invalid xml", e child = self.d.createTextNode(html) return self.processNode(request, child, node)
L.append(getBodyStructure(submsg))
result.append(getBodyStructure(submsg))
def getBodyStructure(msg, extended=False): # XXX - This does not properly handle multipart messages # BODYSTRUCTURE is obscenely complex and criminally under-documented. attrs = {} headers = 'content-type', 'content-id', 'content-description', 'content-transfer-encoding' headers = msg.getHeaders(False, *headers) mm = ...
self._deferredWasDebugging = defer.Deferred.debug
self._deferredWasDebugging = defer.getDebugging()
def setUp(self): self._deferredWasDebugging = defer.Deferred.debug defer.setDebugging(True)
if not isinstance(serviceName, types.StringType):
if not isinstance(serviceName, types.StringTypes):
def __init__(self, serviceName, serviceParent=None, application=None): """Create me, attached to the given application.
if isinstance(port, StringTypes):
if isinstance(port, types.StringTypes):
def upgradeToVersion11(self): self._extraListeners = {} self.extraPorts = [] self.extraConnectors = [] self.unixPorts = [] self.udpConnectors = []
self.proxy.datagramReceived(r.toString()m ("client.com", 5060))
self.proxy.datagramReceived(r.toString(), ("client.com", 5060))
def unregister(self): r = sip.Request("REGISTER", "sip:bell.example.com") r.addHeader("to", "sip:joe@bell.example.com") r.addHeader("contact", "*") r.addHeader("via", sip.Via("client.com").toString()) r.addHeader("expires", "0") self.proxy.datagramReceived(r.toString()m ("client.com", 5060))
def loadMimeTypes(): """Ugg, does this even need to exist anymore? Stupid stdlib"""
def loadMimeTypes(mimetype_locations=['/etc/mime.types']): ''' Multiple file locations containing mime-types can be passed as a list. The files will be sourced in that order, overriding mime-types from the files sourced beforehand, but only if a new entry explicitly overrides the current entry. '''
def loadMimeTypes(): """Ugg, does this even need to exist anymore? Stupid stdlib""" import mimetypes # let's try a few of the usual suspects... contentTypes = { ".css": "text/css", ".exe": "application/x-executable", ".flac": "audio/x-flac", ".gif": "image/gif", ".gtar": "application/x-gtar", ".html": "text/html", ".h...
contentTypes = { ".css": "text/css", ".exe": "application/x-executable", ".flac": "audio/x-flac", ".gif": "image/gif", ".gtar": "application/x-gtar", ".html": "text/html", ".htm": "text/html", ".java": "text/plain", ".jpeg": "image/jpeg", ".jpg": "image/jpeg", ".lisp": "text/x-lisp", ".mp3": "audio/mpeg", ".oz": "text...
contentTypes = mimetypes.types_map contentTypes.update( { '.conf': 'text/plain', '.diff': 'text/plain', '.exe': 'application/x-executable', '.flac': 'audio/x-flac', '.java': 'text/plain', '.ogg': 'application/ogg', '.oz': 'text/x-oz', '.swf': 'application/x-shockwave-flash', '.tgz': 'application/x-gtar...
def loadMimeTypes(): """Ugg, does this even need to exist anymore? Stupid stdlib""" import mimetypes # let's try a few of the usual suspects... contentTypes = { ".css": "text/css", ".exe": "application/x-executable", ".flac": "audio/x-flac", ".gif": "image/gif", ".gtar": "application/x-gtar", ".html": "text/html", ".h...
upd = contentTypes.update if os.path.exists("/etc/mime.types"): upd(mimetypes.read_mime_types("/etc/mime.types"))
) for location in mimetype_locations: if os.path.exists(location): contentTypes.update(mimetypes.read_mime_types(location))
def loadMimeTypes(): """Ugg, does this even need to exist anymore? Stupid stdlib""" import mimetypes # let's try a few of the usual suspects... contentTypes = { ".css": "text/css", ".exe": "application/x-executable", ".flac": "audio/x-flac", ".gif": "image/gif", ".gtar": "application/x-gtar", ".html": "text/html", ".h...
return tcp.Port(address, factory, backlog=backlog)
p = tcp.Port(address, factory, backlog=backlog) p.startListening() return p
def listenUNIX(self, address, factory, backlog=5): """Listen on a UNIX socket. """ return tcp.Port(address, factory, backlog=backlog)
self.sendReply(protocol, message, protocol, address)
self.sendReply(protocol, message, address)
def recursiveLookupFailed(self, failure, message, protocol, address): message.rCode = dns.ESERVER self.sendReply(protocol, message, protocol, address) if self.verbose: log.msg("Recursive lookup failed")
def say(self,event):
def say(self,event=None):
def say(self,event): message=self.input.get('1.0',END)[:-1] self.input.delete('1.0',END) if message: self.messageReceived(message,self.gateway.username) self.im.directMessage(self.gateway,self.contact,message) return "break" # don't put the newline in
log.err("Read-only property %s: %s" % (property.sname(),))
log.err("Read-only property %s" % (property.sname(),))
def writeProperty(self, property): """ See L{IDAVResource.writeProperty}. """ try: self.getProperties()[property.qname()] = property except ValueError: log.err("Read-only property %s: %s" % (property.sname(),)) raise HTTPError(responsecode.CONFLICT)
security according to the given contextFactory, or which fails
secured according to the given contextFactory, or which fails
def startTLS(self, contextFactory=None): """ Initiates a 'STARTTLS' request and negotiates the TLS / SSL Handshake.
if not components.implements(m, interfaces.IModel):
if not interfaces.IModel.providedBy(m):
def __init__(self, m, templateFile=None, templateDirectory=None, template=None, controller=None, doneCallback=None, modelStack=None, viewStack=None, controllerStack=None): """ A view must be told what its model is, and may be told what its controller is, but can also look up its controller if none specified. """ if not...
already be disabled.
already be enabled.
def will(self, option): """Indicate our willingness to begin performing this option locally.
class CUDPPort(cudp.UDPPortMixin, udp.Port):
_origUDPPort = udp.Port class CUDPPort(cudp.UDPPortMixin, _origUDPPort):
def _makeTransport(self): return CClient(self.host, self.port, self.bindAddress, self, self.reactor)
udp.Port.__init__(self, *args, **kwargs)
_origUDPPort.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): udp.Port.__init__(self, *args, **kwargs) cudp.UDPPortMixin.__init__(self, self)
return clazz.__module__+'.'+clazz.__name__
return str(clazz)
def qual(clazz): return clazz.__module__+'.'+clazz.__name__
names = L.split()
names = parseNestedParens(L)
def finish(self, lastLine, unusedCallback): send = [] unuse = [] for L in self.lines: names = L.split() N = len(names) if (N >= 1 and names[0] in self._1_RESPONSES or N >= 2 and names[1] in self._2_RESPONSES): send.append(L) else: print 'Appending unused', L unuse.append(L) self.defer.callback((send, lastLine)) if unus...
N >= 2 and names[1] in self._2_RESPONSES):
N >= 2 and names[1] in self._2_RESPONSES or N >= 2 and names[0] == 'OK' and isinstance(names[1], types.ListType) and names[1][0] in self._OK_RESPONSES):
def finish(self, lastLine, unusedCallback): send = [] unuse = [] for L in self.lines: names = L.split() N = len(names) if (N >= 1 and names[0] in self._1_RESPONSES or N >= 2 and names[1] in self._2_RESPONSES): send.append(L) else: print 'Appending unused', L unuse.append(L) self.defer.callback((send, lastLine)) if unus...
print 'Appending unused', L
def finish(self, lastLine, unusedCallback): send = [] unuse = [] for L in self.lines: names = L.split() N = len(names) if (N >= 1 and names[0] in self._1_RESPONSES or N >= 2 and names[1] in self._2_RESPONSES): send.append(L) else: print 'Appending unused', L unuse.append(L) self.defer.callback((send, lastLine)) if unus...
cmd.finish(line, self._extraInfo)
cmd.finish(rest, self._extraInfo)
def _defaultHandler(self, tag, rest): if tag == '*' or tag == '+': if not self.waiting: # XXX - This is rude. self.transport.loseConnection() raise IllegalServerResponse(tag + ' ' + rest) else: cmd = self.tags[self.waiting] if tag == '+': cmd.continuation.callback(rest) else: cmd.lines.append(rest) else: try: cmd = sel...
d.addCallback(self._cbSelect)
d.addCallback(self._cbSelect, 1)
def select(self, mailbox): """Select a mailbox
resp = 'FLAGS', 'EXISTS', 'RECENT', 'UNSEEN', 'PERMANENTFLAGS'
resp = ('FLAGS', 'EXISTS', 'RECENT', 'UNSEEN', 'PERMANENTFLAGS', 'UIDVALIDITY')
def examine(self, mailbox): """Select a mailbox in read-only mode
d.addCallback(self._cbSelect) return d def _cbSelect(self, (lines, tagline)):
d.addCallback(self._cbSelect, 0) return d def _cbSelect(self, (lines, tagline), rw):
def examine(self, mailbox): """Select a mailbox in read-only mode
datum = {'READ-WRITE': 1}
datum = {'READ-WRITE': rw}
def _cbSelect(self, (lines, tagline)): # In the absense of specification, we are free to assume: # READ-WRITE access datum = {'READ-WRITE': 1} lines.append(tagline) for parts in lines: split = parts.split() if len(split) == 2: if split[1].upper().strip() == 'EXISTS': try: datum['EXISTS'] = int(split[0]) except ValueE...
if self.site.sessions.has_key(self.uid):
if self.guard.sessions.has_key(self.uid):
def checkExpired(self): # If I haven't been touched in 15 minutes: if time.time() - self.lastModified > self.lifetime / 2: if self.site.sessions.has_key(self.uid): self.expire() else: log.msg("no session to expire: %s" % self.uid) else: log.msg("session given the will to live for %s more seconds" % self.lifetime) self....
def __init__(self, rsrc):
def __init__(self, rsrc, cookieKey=None):
def __init__(self, rsrc): Resource.__init__(self) self.resource = rsrc self.cookieKey = "woven_session_" + _sessionCookie() self.sessions = {}
self.cookieKey = "woven_session_" + _sessionCookie()
if cookieKey is None: cookieKey = "woven_session_" + _sessionCookie() self.cookieKey = cookieKey
def __init__(self, rsrc): Resource.__init__(self) self.resource = rsrc self.cookieKey = "woven_session_" + _sessionCookie() self.sessions = {}
elif why is not None:
elif self.watcher:
def write(self, sock): why = None w = self.watcher self.setEnabled(0) try: why = w.doWrite() except: why = sys.exc_value log.msg('Error in %s.doWrite()' % w) log.deferr() if why: try: w.connectionLost(failure.Failure(why)) except: log.deferr() self.reactor.removeReader(w) self.reactor.removeWriter(w) elif why is not No...
self.transport.write(line+"\r\n")
self.transport.write("%s%s%s" % (line, CR, LF))
def sendLine(self, line): self.transport.write(line+"\r\n")
classDccPbRequest = None
nickname = None
def dataReceived(self, data): """This hack is to support mIRC, which sends LF only, even though the RFC says CRLF. (Also, the flexibility of LineReceiver to turn "line mode" on and off was not required.) """ self.buffer = self.buffer + data lines = string.split(self.buffer, LF) # Put the (possibly empty) element after...
def ctcpQuery_ACTION(self, channel, user, data):
def ctcpQuery_ACTION(self, user, channel, data):
def ctcpQuery_ACTION(self, channel, user, data): self.action(user, channel, data)
def ctcpQuery_PING(self, channel, user, data):
def ctcpQuery_PING(self, user, channel, data):
def ctcpQuery_PING(self, channel, user, data): nick = string.split(user,"!")[0] self.ctcpMakeReply(nick, [("PING", data)])
string.join(self.sourceFiles, ' ')
sourceFiles,
def ctcpQuery_SOURCE(self, user, channel, data): if data is not None: self.quirkyMessage("Why did %s send '%s' with a SOURCE query?" % (user, data)) if self.sourceHost: nick = string.split(user,"!")[0] self.ctcpMakeReply(nick, [('SOURCE', "%s:%s:%s" % (self.sourceHost, self.sourceDir, string.join(self.sourceFiles, ' ')...
(dcctype, arg, address, port) = data
(dcctype, arg, address, port) = data[:4] port = int(port) if '.' in address: pass else: try: address = long(address) except ValueError: raise IRCBadMessage,\ "Indecipherable address '%s'" % (address,) else: address = ( (address >> 24) & 0xFF, (address >> 16) & 0xFF, (address >> 8) & 0xFF, address & 0xFF, ) address =...
def ctcpQuery_DCC(self, user, channel, data): data = string.split(data) if len(data) < 4: raise IRCBadMessage, "malformed DCC request: %s" % (data,)
size = data[4] else: size = -1 filename = arg raise NotImplementedError, "XXX: DCC SEND not implemented."
try: size = int(data[4]) except ValueError: pass filename = path.basename(arg) protocol = DccFileReceive(filename, size, queryData=(user,channel,data)) tcp.Client(address, port, protocol) self.dcc_sessions.append(protocol)
def ctcpQuery_DCC(self, user, channel, data): data = string.split(data) if len(data) < 4: raise IRCBadMessage, "malformed DCC request: %s" % (data,)
raise NotImplementedError, "XXX: DCC CHAT not implemented." elif dcctype == 'PB': b = self.classDccPbRequest(user, channel, arg) pb.getObjectAt(address, port, b.callback, b.errback)
protocol = DccChat(self, queryData=(user, channel, data)) tcp.Client(address, port, protocol) self.dcc_sessions.append(protocol)
def ctcpQuery_DCC(self, user, channel, data): data = string.split(data) if len(data) < 4: raise IRCBadMessage, "malformed DCC request: %s" % (data,)
if not self._pings.has_key(data):
if (not self._pings) or (not self._pings.has_key(data)):
def ctcpReply_PING(self, user, channel, data): if not self._pings.has_key(data): raise IRCBadMessage,\ "Bogus PING response from %s: %s" % (user, data)
self.log(traceback.format_exception(excType, excValue, tb))
self.log(string.join(traceback.format_exception(excType, excValue, tb),''))
def badMessage(self, line, excType, excValue, tb): """When I get a message that's so broken I can't use it. """ self.log(line) self.log(traceback.format_exception(excType, excValue, tb))
NUL = chr(0) CR = chr(015) NL = chr(012) LF = NL
def sendLine(self, line): basic.LineReceiver.sendLine(self, lowQuote(line))
SPC = chr(040)
def sendLine(self, line): basic.LineReceiver.sendLine(self, lowQuote(line))
util.spinUntil(lambda :p.disconnected)
spinUntil(lambda :p.disconnected)
def cleanPorts(self, *ports): for p in ports: if not hasattr(p, 'disconnected'): raise RuntimeError, ("You handed something to cleanPorts that" " doesn't have a disconnected attribute, dummy!") if not p.disconnected: d = getattr(p, self.callToLoseCnx)() if isinstance(d, defer.Deferred): wait(d) else: try: util.spinUnti...
packageDir = os.path.dirname(package.__file__)
def loadPackageRecursive(self, package): packageDir = os.path.dirname(package.__file__) suite = self.suiteFactory() os.path.walk(packageDir, self._packageRecurse, suite) return suite
os.path.walk(packageDir, self._packageRecurse, suite)
for packageDir in package.__path__: os.path.walk(packageDir, self._packageRecurse, suite)
def loadPackageRecursive(self, package): packageDir = os.path.dirname(package.__file__) suite = self.suiteFactory() os.path.walk(packageDir, self._packageRecurse, suite) return suite
reactor.connectTCP(host, port, factory) return d.addCallback(lambda x: (x, [], []))
connector = reactor.connectTCP(host, port, factory) return d.addCallback(self._cbLookupZone, connector) def _cbLookupZone(self, result, connector): connector.disconnect() return (result, [], [])
def lookupZone(self, name, timeout = 10): """ Perform an AXFR request. This is quite different from usual DNS requests. See http://cr.yp.to/djbdns/axfr-notes.html for more information. """ address = self.pickServer() if address is None: return defer.fail(IOError('No domain name servers available')) host,port = address ...
def sendMessage(self, text, meta={}): if meta.get("style", None) == "emote": text="* "+text+"* "
def sendMessage(self, text, meta=None): if meta: if meta.get("style", None) == "emote": text="* "+text+"* "
def sendMessage(self, text, meta={}): if meta.get("style", None) == "emote": text="* "+text+"* " self.account.say(self.name,html(text)) return succeed(text)
def sendGroupMessage(self, text, meta={}): if meta.get("style", None) == "emote": text="* "+text+"* "
def sendGroupMessage(self, text, meta=None): if meta: if meta.get("style", None) == "emote": text="* "+text+"* "
def sendGroupMessage(self, text, meta={}): if meta.get("style", None) == "emote": text="* "+text+"* " self.account.chat_say(self.roomID,html(text)) return succeed(text)
if self.addSlash and request.prepath[-1] != '' and request.prepath[-1] != 'index.rpy':
if self.addSlash and request.uri[-1] != '/':
def render(self, request): """ Trigger any inputhandlers that were passed in to this Page, then delegate to the View for traversing the DOM. Finally, call gatheredControllers to deal with any InputHandlers that were constructed from any controller= tags in the DOM. gatheredControllers will render the page to the browse...
f.HTTPChannel = Proxy
f.protocol = Proxy
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] headers = self.getAllHeaders().copy...
synopsis = "Usage: tapconvert in-file [options]" optParameters = [['in', 'i', None, "The filename of the tap to read from"], ['out', 'o', None, "A filename to write the tap to"], ['typein', 'f', 'pickle', "The format to use; this can be 'python', 'pickle', 'xml', or 'source'."], ['typeout', 't', 'source', "The output ...
synopsis = "Usage: tapconvert [options]" optParameters = [ ['in', 'i', None, "The filename of the tap to read from"], ['out', 'o', None, "A filename to write the tap to"], ['typein', 'f', 'guess', "The format to use; this can be 'guess', 'python', 'pickle', 'xml', or 'source'."], ['typeout', 't', 's...
def savePersisted(app, filename, encrypted): if encrypted: try: import Crypto app.save(filename=filename, passphrase=util.getPassword("Encryption passphrase: ")) except ImportError: print "The --encrypt flag requires the PyCrypto module, no file written." else: app.save(filename=filename)
ts = self.path.sibling('sibling_test') self.assertEquals(ts.dirname(), self.path.dirname())
p = self.path.child('sibling_start') ts = p.sibling('sibling_test') self.assertEquals(ts.dirname(), p.dirname())
def testSibling(self): ts = self.path.sibling('sibling_test') self.assertEquals(ts.dirname(), self.path.dirname()) self.assertEquals(ts.basename(), 'sibling_test') ts.createDirectory() self.assertIn(ts, self.path.parent().children())
self.assertIn(ts, self.path.parent().children())
self.assertIn(ts, self.path.children())
def testSibling(self): ts = self.path.sibling('sibling_test') self.assertEquals(ts.dirname(), self.path.dirname()) self.assertEquals(ts.basename(), 'sibling_test') ts.createDirectory() self.assertIn(ts, self.path.parent().children())
@param contextFactory: a L{twisted.internet.ssl.ContextFactory} object.
@param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.
def connectSSL(self, host, port, factory, contextFactory, timeout=30, bindAddress=None): """Connect a client Protocol to a remote SSL socket.
self.assertApproximates(self._resetcallbackTime, start + 0.5, 0.1) self.assertApproximates(self._delaycallbackTime, start + 0.8, 0.1)
self.assert_(self._resetcallbackTime>start + 0.5) self.assert_(self._delaycallbackTime>start + 0.8) self.assert_(self._delaycallbackTime>self._resetcallbackTime)
def testCallLaterDelayAndReset(self): self._resetcallbackTime = None self._delaycallbackTime = None ireset = reactor.callLater(0.5, self._resetcallback) idelay = reactor.callLater(0.5, self._delaycallback) start = time.time() # chug a little before delaying while time.time() - start < 0.2: reactor.iterate(0.01) ireset....
p = process.Process(*([None] * 7))
p = reactor.spawnProcess(protocol.ProcessProtocol(), "/bin/ls")
def testAliasResolution(self): aliases = {} domain = {'': TestDomain(aliases, ['user1', 'user2', 'user3'])} A1 = mail.alias.AliasGroup(['user1', '|process', '/file'], domain, 'alias1') A2 = mail.alias.AliasGroup(['user2', 'user3'], domain, 'alias2') A3 = mail.alias.AddressAlias('alias1', domain, 'alias3') aliases.updat...