rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
gotPassword, host, port).addErrback(
gotPassword, host, port, usn).addErrback(
def connectionError(err, host, port, usn): if isinstance(err.value, Pearl.AuthenticationError): # Bad password, let the user try again keychain.lookup(usn, ignoreStored=True).addCallback( gotPassword, host, port).addErrback( connectionError, host, port, usn) else: # Pass on other errors result.errback(err)
def gotPassword(password, host, port): connect(host, port, password).chainDeferred(result)
def gotPassword(password, host, port, usn): connect(host, port, password).addCallback( result.callback).addErrback( connectionError, host, port, usn)
def gotPassword(password, host, port): connect(host, port, password).chainDeferred(result)
while len(received) < size: chunk = self.recv(size - len(received)) if not chunk: self.readBuffer = received return None received += chunk self.readBuffer = received[size:] return received[:size]
self.readBuffer = self.readBuffer[size:] return received
def read(self, size=None, bufferSize=64*1024): """High level interface for reading from the socket, includes a buffering scheme that works well for receiving fixed size messages. """ if size is None: # Keep reading until there's no more to read received = self.readBuffer self.readBuffer = '' try: while 1: received += s...
self.hub.addClient(lambda msg: self.queryStats(msg), Message.Filter('<find path="/message/body/queryStats">'))
hub.addClient(lambda msg: self.queryStats(msg), Message.Filter('<find path="/message/body/queryStats">'))
def addClients(self, hub): """Add our own clients to the Message.Hub. We use this to listen for queryStats messages. The extra level of indirection here helps rebuild() work its magic without breaking. """ self.hub.addClient(lambda msg: self.queryStats(msg), Message.Filter('<find path="/message/body/queryStats">'))
"""Get a matrix that converts BZFlag coordinates to Blender coordinates
"""Get a 3x3 matrix that converts BZFlag coordinates to Blender coordinates
def getBzToBlendMatrix(self): """Get a matrix that converts BZFlag coordinates to Blender coordinates relative to this world. Requires that the world have an associated Blender object. """ scale = 1.0 / self.size return self.blendObject.mat * Blender.Mathutils.Matrix( [scale, 0, 0 , 0], [0, scale, 0 , 0],...
return self.blendObject.mat * Blender.Mathutils.Matrix( [scale, 0, 0 , 0], [0, scale, 0 , 0], [0, 0, scale, 0], [0, 0, 0, 1])
return self.blendObject.mat.rotationPart() * scale
def getBzToBlendMatrix(self): """Get a matrix that converts BZFlag coordinates to Blender coordinates relative to this world. Requires that the world have an associated Blender object. """ scale = 1.0 / self.size return self.blendObject.mat * Blender.Mathutils.Matrix( [scale, 0, 0 , 0], [0, scale, 0 , 0],...
"""Get a matrix that converts Blender coordintes back to BZFlag coordinates,
"""Get a 3x3 matrix that converts Blender coordintes back to BZFlag coordinates,
def getBlendToBzMatrix(self): """Get a matrix that converts Blender coordintes back to BZFlag coordinates, relative to this world. Requires that the world have an associated Blender object. """ inv = self.getBzToBlendMatrix() inv.invert() return inv
mat *= self.world.getBzToBlendMatrix()
transform = self.world.getBzToBlendMatrix() transform.resize4x4() mat *= transform mat *= Blender.Mathutils.TranslationMatrix( self.world.blendObject.mat.translationPart())
def transformBlenderObject(self, obj): """Set the transformation on the given Blender object to match our position, size, and rotation. This will be used both by the Box object and by other objects with similar interfaces that subclass Box. """ mat = Blender.Mathutils.Matrix( [self.size[0], 0, 0, ...
mat = obj.mat * self.world.getBlendToBzMatrix()
transform = self.world.getBlendToBzMatrix() transform.resize4x4() mat *= transform
def loadBlenderTransform(self, obj): """Retrieves the object's position, size, and rotation from a Blender object- the inverse of transformBlenderObject(). """ # Convert to BZFlag coordinates, relative to the World object mat = obj.mat * self.world.getBlendToBzMatrix()
self.fork_command('sh', ('-c', editor),
self.fork_command('sh', ('sh', '-c', editor),
def __init__(self): vte.Terminal.__init__(self) self.set_color_foreground(gtk.gdk.color_parse('Black')) self.set_color_background(gtk.gdk.color_parse('White')) editor = os.environ.get('EDITOR', 'vim') childEnv = dict(os.environ) del childEnv['DISPLAY'] self.fork_command('sh', ('-c', editor), ["=".join(i) for i in child...
if 'url' in self.target.metadata: return self.target.metadata['url'] else: return StatsLink(self.target).getURL(context)
return self.target.metadata.get('url', StatsLink(self.target).getURL(context))
def render_link(self, context): if 'url' in self.target.metadata: return self.target.metadata['url'] else: return StatsLink(self.target).getURL(context)
if 'description' in self.target.metadata: return self.target.metadata['description'] else: return "CIA Stats" def render_metadata(self, context): """Renders optional metadata to RSS""" tags = [] if 'photo' in self.target.metadata: tags.append(tag('image')[
return self.target.metadata.get('description', 'CIA Stats') def render_photo(self, context): result = defer.Deferred() self.target.metadata.has_key('photo').addCallback( self._render_photo, context, result).addErrback(result.errback) return result def _render_photo(self, hasPhoto, context, result): if hasPhoto: resu...
def render_description(self, context): if 'description' in self.target.metadata: return self.target.metadata['description'] else: return "CIA Stats"
return tags
else: result.callback([])
def render_metadata(self, context): """Renders optional metadata to RSS""" tags = [] if 'photo' in self.target.metadata: tags.append(tag('image')[ tag('url')[ MetadataLink(self.target, 'photo').getURL(context) ], tag('title')[ place('title') ], tag('link')[ place('link') ], ]) return tags
latest = self.target.messages.getLatest(limit) latest.reverse() for m in latest:
for m in messages:
def render_items(self, context, limit=15): """Renders the most recent commits as items in the RSS feed""" formatter = Message.AutoFormatter('rss') items = [] # Get the latest message, in reverse chronological order latest = self.target.messages.getLatest(limit) latest.reverse() for m in latest: i = formatter.format(Mes...
return items
result.callback(items)
def render_items(self, context, limit=15): """Renders the most recent commits as items in the RSS feed""" formatter = Message.AutoFormatter('rss') items = [] # Get the latest message, in reverse chronological order latest = self.target.messages.getLatest(limit) latest.reverse() for m in latest: i = formatter.format(Mes...
place('metadata'),
place('photo'),
def render_items(self, context, limit=15): """Renders the most recent commits as items in the RSS feed""" formatter = Message.AutoFormatter('rss') items = [] # Get the latest message, in reverse chronological order latest = self.target.messages.getLatest(limit) latest.reverse() for m in latest: i = formatter.format(Mes...
"There seems to have been a 'changedpage' module in the works for RSS 1.0 that provides "
"There was a 'changedpage' module in the works for RSS 1.0 that would have provided "
def render_form(self, context): return tag('form', action = Link.RSSLink(self.statsPage.target).getURL(context), )[place('formContent')]
offset = mminfo._find_header(f)[0]
offset = mp3info.MPEG(f)._find_header(f)[0]
def fromFile(self, filename, length=None, mminfo=None): """Calculate the RID from a file, given its name. The file's length and mmpython results may be provided if they're known, to avoid duplicating work. """ if mminfo is None: mminfo = mmpython.parse(filename)
print filename
def scan(self, path): """Recursively scan all files within the specified path, creating or updating their cache entries. """ for root, dirs, files in os.walk(path): for name in files: filename = os.path.join(root, name) print filename self.lookup(filename)
self.parse(email.message_from_string(string))
return self.parse(email.message_from_string(string))
def parseString(self, string): """Convert the given string to an email.Message, then parse it""" self.parse(email.message_from_string(string))
print xml.toXml()
return Message(xml)
def command_Announce(self, project): """Old-style announcements: Announce <project> in the subject line. The body of the email contained the message's text, marked up with {color} tags but with no metadata. """ xml = domish.Element((None, "message"))
self.dev = open(devs[0], "rw")
self.writeDev = open(devs[0], "w") self.readDev = open(devs[0], "r")
def __init__(self, devPattern="/dev/usb/uvswitch*", eventLoop=None): devs = glob.glob(devPattern) if not devs: raise IOError, "No uvswitch device found" self.dev = open(devs[0], "rw")
self.dev.write("%d %d %d %d\n" % (self._videoChannel,
self.writeDev.write("%d %d %d %d\n" % (self._videoChannel,
def update(self): """Send all current settings to the device""" self.dev.write("%d %d %d %d\n" % (self._videoChannel, self._bypassSwitch, self._whiteAudioChannel, self._redAudioChannel)) self.dev.flush()
self.dev.flush()
self.writeDev.flush()
def update(self): """Send all current settings to the device""" self.dev.write("%d %d %d %d\n" % (self._videoChannel, self._bypassSwitch, self._whiteAudioChannel, self._redAudioChannel)) self.dev.flush()
return self.dev
return self.readDev
def getSelectable(self): """Called by the main loop to see what items we have for its select()""" return self.dev
line = self.dev.readline().strip()
line = self.readDev.readline().strip()
def pollRead(self, eventLoop): """Called by the main loop when we have new data from the device. From the uvswitch, this will be a line of text indicating which input ports are active. """ line = self.dev.readline().strip() if line: newActiveChannels = map(int, line.split(" ")) else: newActiveChannels = [] for channel ...
self.activeChannels = newActiveList
self.activeChannels = newActiveChannels
def pollRead(self, eventLoop): """Called by the main loop when we have new data from the device. From the uvswitch, this will be a line of text indicating which input ports are active. """ line = self.dev.readline().strip() if line: newActiveChannels = map(int, line.split(" ")) else: newActiveChannels = [] for channel ...
Requires the universe key, for obvious reasons.
Requires the universe key, since it would be trivial to use this to access CapabilityDB or SecurityInterface directly and ask for the universe key.
def xmlrpc_eval(self, code, key): """Evaluate arbitrary code in the context of this module. Requires the universe key, for obvious reasons. Returns the repr() of the result. """ self.caps.faultIfMissing(key, 'universe') try: return repr(eval(code)) except: catchFault()
return "\n".join([ "%30s : %-10d %s..." % (key, typeFreq[key], ", ".join(typeInstances[key])[:80]) for key in keys])
lines = [] for key in keys: contents = ", ".join(typeInstances[key]).replace("\n", "\\n") if len(contents) > 100: contents = contents[:100] + "..." lines.append("%45s : %-10d %s" % (key, typeFreq[key], contents)) return "\n".join(lines)
def xmlrpc_typeProfile(self, key): """Print a chart showing the most frequently occurring types in memory""" self.caps.faultIfMissing(key, 'universe', 'debug', 'debug.gc', 'debug.gc.typeProfile')
xml('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'),
xml('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />'),
def __getitem__(self, rows): return self.__class__(self.title, [rows])
return self.target.metadata.get('url', Link.StatsLink(self.target).getURL(context))
return self.target.metadata.getValue('url', Link.StatsLink(self.target).getURL(context))
def render_link(self, context): return self.target.metadata.get('url', Link.StatsLink(self.target).getURL(context))
return self.target.metadata.get('description', 'CIA Stats')
return self.target.metadata.getValue('description', 'CIA Stats')
def render_description(self, context): return self.target.metadata.get('description', 'CIA Stats')
return dict([(node.attributes.item(i).name,\ node.getAttribute(node.attributes.item(i).name))\
return dict([(node.attributes.item(i).name, node.getAttribute(node.attributes.item(i).name))
def getAttrs(self, node): ''' Store all of the tags attributes in a dictionary with attribute names as the keys.
self.data = int(character.getData(node.childNodes[0].data))
try: self.data = int(character.getData(node.childNodes[0].data)) except ValueError: self.data = 0
def __init__(self, node, character): self.name = node.tagName if node.childNodes[0].data.count('/') > 0: self.data = int(character.getData(node.childNodes[0].data)) else: self.data = int(node.childNodes[0].data)
for other in graph.nodes: if other.position: repulsionForce(self, other, 80) edgeStrength = 200 for axis in (0,1): self.position[axis] += edgeStrength / max(self.position[axis], 1) self.position[axis] -= edgeStrength / max(graph.viewport.size[axis] - self.position[axis], 1) self.position += (random.normalvariate(0,...
if not self.isGrabbed: for other in graph.nodes: if other.position: repulsionForce(self, other, 80) edgeStrength = 200 for axis in (0,1): self.position[axis] += edgeStrength / max(self.position[axis], 1) self.position[axis] -= edgeStrength / max(graph.viewport.size[axis] - self.position[axis], 1) self.position +...
def animate(self, graph): # If we're new, start in the middle if self.position is None: self.position = Numeric.array(graph.viewport.size, Numeric.Float)/2
irc.IRCClient.connectionMade(self)
self.requestedChannels = []
def connectionMade(self): self.nickname = self.factory.allocator.allocateNick() self.channels = [] irc.IRCClient.connectionMade(self)
def __init__(self, server, nickFormat, channelsPerBot=15):
def __init__(self, server, nickFormat, channelsPerBot=18):
def __init__(self, server, nickFormat, channelsPerBot=15): self.nickFormat = nickFormat self.channelsPerBot = channelsPerBot self.host, self.port = server self.kickCallback = None
self.existingBotRequests = []
def __init__(self, server, nickFormat, channelsPerBot=15): self.nickFormat = nickFormat self.channelsPerBot = channelsPerBot self.host, self.port = server self.kickCallback = None
self.existingBotRequests.append(channel) self.newBotRequests.remove(channel)
def botConnected(self, bot): """Called by one of our bots when it's connected successfully and ready to join channels""" log.msg("Bot %r on server %r connected" % (bot.nickname, self.host)) self.bots[bot.nickname] = bot
self.existingBotRequests.remove(channel)
def botJoined(self, bot, channel): """Called by one of our bots when it's successfully joined to a channel""" log.msg("Bot %r on server %r joined %r" % (bot.nickname, self.host, channel)) self.existingBotRequests.remove(channel) self.channels[channel] = bot
if not bot.channels:
if not (bot.channels or bot.requestedChannels):
def botLeft(self, bot, channel): """Called by one of our bots when it has finished leaving a channel""" log.msg("Bot %r on server %r left %r" % (bot.nickname, self.host, channel)) del self.channels[channel]
self.addChannel(channel)
for channel in bot.channels: self.addChannel(channel) for channel in bot.requestedChannels: self.addChannel(channel)
def botDisconnected(self, bot): """Called when one of our bots has been disconnected""" log.msg("Bot %r on server %r disconnected" % (bot.nickname, self.host)) del self.bots[bot.nickname] for channel in self.channels.keys(): if self.channels[channel] == bot: # This is a channel formerly serviced by the bot that was jus...
if channel in self.existingBotRequests: return None
def addChannel(self, channel): """Add a channel to the list of those supported by the bots on this server, if it's not there already. The channel may not be available right away if a new bot has to be connected for it. Returns a Bot instance if one is already available to talk on this channel, or None if we're in the p...
if len(bot.channels) < self.channelsPerBot:
if len(bot.channels) + len(bot.requestedChannels) < self.channelsPerBot:
def addChannel(self, channel): """Add a channel to the list of those supported by the bots on this server, if it's not there already. The channel may not be available right away if a new bot has to be connected for it. Returns a Bot instance if one is already available to talk on this channel, or None if we're in the p...
self.existingBotRequests.append(channel)
def addChannel(self, channel): """Add a channel to the list of those supported by the bots on this server, if it's not there already. The channel may not be available right away if a new bot has to be connected for it. Returns a Bot instance if one is already available to talk on this channel, or None if we're in the p...
self.existingBotRequests.remove(channel)
self.newBotRequests.remove(channel) log.msg("Removing channel %r on server %r from newBotRequests" % (channel, self.host))
def delChannel(self, channel): """Remove a channel from the list of those supported by the bots on this server, deleting any bots no longer necessary. """ # Remove it from our requested channel lists if it's there try: self.existingBotRequests.remove(channel) except: pass try: self.newBotRequests.remove(channel) except...
try: self.newBotRequests.remove(channel) except: pass
for bot in self.bots.itervalues(): try: bot.requestedChannels.remove(channel) log.msg("Removing channel %r on server %r from the requestedChannels for %r" % (channel, self.host, bot.nickname)) except: pass
def delChannel(self, channel): """Remove a channel from the list of those supported by the bots on this server, deleting any bots no longer necessary. """ # Remove it from our requested channel lists if it's there try: self.existingBotRequests.remove(channel) except: pass try: self.newBotRequests.remove(channel) except...
def foundService(result): if result is None:
def foundService(service): if service is None:
def foundService(result): if result is None: raise Exception("No Rio Karma device could be found automatically") usn, (host, port) = result keychain.lookup(usn).addCallback( gotPassword, host, port, usn).addErrback( result.errback)
usn, (host, port) = result
usn, (host, port) = service print usn, host, port
def foundService(result): if result is None: raise Exception("No Rio Karma device could be found automatically") usn, (host, port) = result keychain.lookup(usn).addCallback( gotPassword, host, port, usn).addErrback( result.errback)
interpolated.save (sys.argv[2])
def interpolate (points): """Add frames to smooth the animation using cubic natural splines.""" n = len (points) # A semi-arbitrary size limit for the chunk we're interpolating. if n > 10: mid = n / 2 return interpolate (points[:mid]) + interpolate (points[mid-1:]) # n is now the number of intervals over which we inte...
print 'added path', newpaths[-1]
def step (self): newpaths = [] for path in self.paths: node = path[-1] for edge in self.adjacency.query (node): if edge.u is node: newpaths.append (list (path + [edge.v])) print 'added path', newpaths[-1] self.paths = newpaths
request.write(xml)
request.write(unicode(xml).encode('utf-8'))
def _render(self, xml, request): if xml: request.setHeader('content-type', 'text/xml') request.write(xml) request.finish() else: request.write(error.NoResource("Message #%d not found" % self.id).render(request)) request.finish()
net = bayes_net[bone]
net = self.bayes[bone]
def combine(self, bones, items, position=0, current=[], current_probability=1.0): """Recusively create combinatoric successors.
def successor (graphs, node):
def successor (self, graphs, node):
def successor (graphs, node): """Generate successors of a combinatoric node.""" immediate_successors = {} # Create a dictionary mapping bone name to the list of successors for that # bone in its current position. for bone, n in node.iteritems (): immediate_successors[bone] = [edge.v for edge in self.adjacency[bone].que...
for bone in comb_order:
for bone in self.order:
def successor (graphs, node): """Generate successors of a combinatoric node.""" immediate_successors = {} # Create a dictionary mapping bone name to the list of successors for that # bone in its current position. for bone, n in node.iteritems (): immediate_successors[bone] = [edge.v for edge in self.adjacency[bone].que...
for succ in combine(bones, items):
for succ in self.combine(self.order, items):
def successor (graphs, node): """Generate successors of a combinatoric node.""" immediate_successors = {} # Create a dictionary mapping bone name to the list of successors for that # bone in its current position. for bone, n in node.iteritems (): immediate_successors[bone] = [edge.v for edge in self.adjacency[bone].que...
retsucc[comb_order[pos]] = succ[pos]
retsucc[self.order[pos]] = succ[pos]
def successor (graphs, node): """Generate successors of a combinatoric node.""" immediate_successors = {} # Create a dictionary mapping bone name to the list of successors for that # bone in its current position. for bone, n in node.iteritems (): immediate_successors[bone] = [edge.v for edge in self.adjacency[bone].que...
if hasattr(opts, "fps"):
if hasattr(opts, "fps") and opts.fps is not None:
def buildFrame(data, index): frame = {} for name, value in data.iteritems(): frame[name] = value[index] return frame
childFactories = { '.metadata': Metadata.MetadataPage, '.rss': Feed.RSSFeed, '.xml': Feed.XMLFeed, }
def __contains__(self, page): for cls in (Page, Metadata.MetadataPage): if isinstance(page, cls): return True return False
xchat.command( 'py unload '+__module_name__ )
if self.loaded: xchat.command( 'py unload '+__module_name__ )
def close( self, window, event=None, user_data=None ): ''' Unload the module when you close the window. ''' # FIXME: In the future this might just hide the window if we can add a # item to the main window that would allow us to show the window, # in which case we wouldn't unload the plugin here. xchat.com...
print therm_total, therm_count
def log(*values): """Log a tuple of values in CSV format to stdout and a log file""" global logFile if logFile is None: logFile = open("rx-log.csv", "w") line = ", ".join([str(value) for value in values]) print line logFile.write(line + "\n") logFile.flush()
arc = CaselessLiteral('arc') + OneOrMore(arcProperty) + end
arc = Group(CaselessLiteral('arc') + OneOrMore(arcProperty) + end)
def getGrammar (self): if self.grammar is None: comment = Literal('#') + Optional (restOfLine) float = Combine(Word('+-'+nums, nums) + Optional(Literal('.') + Optional(Word(nums))) + Optional(CaselessLiteral('E') + Word('+-'+nums, nums))) TwoDPoint = float + float ThreeDPoint = float + float + float globalReference = W...
tetra = Group(CaselessLiteral('tetra') + OneOrMore(tetraProperty))
tetra = Group(CaselessLiteral('tetra') + OneOrMore(tetraProperty) + end)
def getGrammar (self): if self.grammar is None: comment = Literal('#') + Optional (restOfLine) float = Combine(Word('+-'+nums, nums) + Optional(Literal('.') + Optional(Word(nums))) + Optional(CaselessLiteral('E') + Word('+-'+nums, nums))) TwoDPoint = float + float ThreeDPoint = float + float + float globalReference = W...
| Word(alphas, min=1, max=2)
| flagShortName
def getGrammar (self): if self.grammar is None: comment = Literal('#') + Optional (restOfLine) float = Combine(Word('+-'+nums, nums) + Optional(Literal('.') + Optional(Word(nums))) + Optional(CaselessLiteral('E') + Word('+-'+nums, nums))) TwoDPoint = float + float ThreeDPoint = float + float + float globalReference = W...
zone = CaselessLiteral('zone') + OneOrMore(zoneProperty)
zone = Group(CaselessLiteral('zone') + OneOrMore(zoneProperty) + end) weaponProperty = \ Group(CaselessLiteral('initdelay') + float) \ | Group(CaselessLiteral('delay') + OneOrMore(float)) \ | Group(CaselessLiteral('type') + flagShortName) \ | locationProperty weapon = Group(CaselessLiteral('weapon') + OneOr...
def getGrammar (self): if self.grammar is None: comment = Literal('#') + Optional (restOfLine) float = Combine(Word('+-'+nums, nums) + Optional(Literal('.') + Optional(Word(nums))) + Optional(CaselessLiteral('E') + Word('+-'+nums, nums))) TwoDPoint = float + float ThreeDPoint = float + float + float globalReference = W...
if iconName: icon = Link.ThumbnailLink(Stats.Target.StatsTarget(targetPath), iconName, (48,32)) else: icon = () link = self.makeLink(targetPath, targetTitle) d.setdefault(currentParentLink, []).append([icon, ' ', link])
d.setdefault(currentParentLink, []).append((targetPath, targetTitle, iconName))
def _render_rows(self, queryResults, context, result): # From the rows returned from our SQL query, construct a # dictionary that maps from a parent hyperlink to a list # of child hyperlinks sorted by decreasing freshness. currentParentLink = None currentParentPath = None d = {} for parentPath, parentTitle, targetPath,...
def render_section(self, section, contents): """Given a heading renderable and a list of contents for that
def render_section(self, section, rows): """Given a heading renderable and a list of rows for that
def render_section(self, section, contents): """Given a heading renderable and a list of contents for that heading, render one section of the 'related' box. """ # Truncate the contents if we need to if len(contents) > self.sectionLimit: contents = contents[:self.sectionLimit] + ['(%d others)' % (len(contents) - self.se...
if len(contents) > self.sectionLimit: contents = contents[:self.sectionLimit] + ['(%d others)' % (len(contents) - self.sectionLimit)]
if len(rows) > self.sectionLimit: rows = rows[:self.sectionLimit] footer = tag('div', _class='relatedFooter')[ '(%d others)' % (len(rows) - self.sectionLimit) ] else: footer = ()
def render_section(self, section, contents): """Given a heading renderable and a list of contents for that heading, render one section of the 'related' box. """ # Truncate the contents if we need to if len(contents) > self.sectionLimit: contents = contents[:self.sectionLimit] + ['(%d others)' % (len(contents) - self.se...
tag('ul', _class='related')[[ tag('li', _class='related')[ item ] for item in contents ]], ]
Nouvelle.BaseTable(rows, self.columns, showHeading=False), footer, ]
def render_section(self, section, contents): """Given a heading renderable and a list of contents for that heading, render one section of the 'related' box. """ # Truncate the contents if we need to if len(contents) > self.sectionLimit: contents = contents[:self.sectionLimit] + ['(%d others)' % (len(contents) - self.se...
vs = [edge.v for edge in adj.query (node]
vs = [edge.v for edge in adj.query (node)]
def successor(self, graphs, nodes): immediate_successors = [] for node in nodes: # FIXME: need to find the graph which holds this node vs = [edge.v for edge in adj.query (node] immediate_successors.append(vs) return comb (items)
columnTitle = 'commits today',
columnTitle = 'events today',
def __init__(self, targetPath, title, numItems = 10, counter = 'today', counterAttrib = 'event_count', sort = 'DESC', columnTitle = 'commits today', ): self.targetPath = targetPath self.title = title self.numItems = numItems self.counter = counter self.counterAttrib = counterAttrib self.sort = sor...
columnTitle = 'first commit',
columnTitle = 'first event',
def __init__(self, targetPath, title, numItems = 10, counter = 'forever', counterAttrib = 'first_time', sort = 'DESC', columnTitle = 'first commit', ): ActivitySection.__init__(self, targetPath, title, numItems, counter, counterAttrib, sort, columnTitle)
columnTitle = 'latest commit'),
columnTitle = 'latest event'),
def render_mainColumn(self, context): return [ self.heading, Nouvelle.subcontext(component=self.statsComponent)[ Template.SectionGrid( [ ActivitySection("project", "Most active projects today"), ActivitySection("author", "Most active authors today"), ], [ TimestampSection("project", "Newest projects"), TimestampSection...
search = Interpolate.GraphSearch (cgraph, start, end)
def save(sequence, file): """Save a sequence to a file. For now, this function writes sequence out to a file manually, instead of using the save() function built in to AMC object. The AMC.save() function is only writing out 0's. """ f = open(file, "w") # Default format for all of our AMC files f.write(":FULLY-SPECIFIE...
startTime = time.time () search.run () endTime = time.time () print 'start:', startTime print 'end:', endTime runTime = endTime - startTime print 'Time:', runTime
startTime = time.clock () search = Interpolate.GraphSearch (cgraph, start, end) endTime = time.clock () print 'Time:', (endTime - startTime)
def save(sequence, file): """Save a sequence to a file. For now, this function writes sequence out to a file manually, instead of using the save() function built in to AMC object. The AMC.save() function is only writing out 0's. """ f = open(file, "w") # Default format for all of our AMC files f.write(":FULLY-SPECIFIE...
search.run ()
search = Interpolate.GraphSearch (cgraph, start, end)
def save(sequence, file): """Save a sequence to a file. For now, this function writes sequence out to a file manually, instead of using the save() function built in to AMC object. The AMC.save() function is only writing out 0's. """ f = open(file, "w") # Default format for all of our AMC files f.write(":FULLY-SPECIFIE...
name, adj = self.adjacency[names[0]]
name, adj = graphs[0]
def combine (graphs): """Recursively combine all the edges from the graphs going out from 'u'. """ name, adj = self.adjacency[names[0]] for v in adj.query(u[name]): if len(graphs) == 1: yield {name: v} continue
for v in combine (self.adjacency.keys ()):
for v in combine (self.data):
def combine (graphs): """Recursively combine all the edges from the graphs going out from 'u'. """ name, adj = self.adjacency[names[0]] for v in adj.query(u[name]): if len(graphs) == 1: yield {name: v} continue
if formattedFiles and formattedFiles[0] != '/':
if formattedFiles:
def format_moduleAndFiles(self, message): """Format the module name and files, joined together if they are both present.""" if message.xml.body.commit.files: formattedFiles = self.format_files(message.xml.body.commit.files) else: formattedFiles = ""
return formattedModule + formattedFiles
return formattedModule
def format_moduleAndFiles(self, message): """Format the module name and files, joined together if they are both present.""" if message.xml.body.commit.files: formattedFiles = self.format_files(message.xml.body.commit.files) else: formattedFiles = ""
self.date = time.mktime(data.modified_parsed)
self.date = data.modified_parsed
def __init__(self, data, feed): self.feed = feed try: self.title = data.title except AttributeError: self.title = "Untitled" self.content = xml(unicode(data.summary).encode("utf-8")) self.date = time.mktime(data.modified_parsed)
return other.date - self.date
return cmp(other.date, self.date)
def __cmp__(self, other): """Reverse-temporal sort""" return other.date - self.date
local = time.localtime(t)
t = time.localtime(calendar.timegm(t)) timeString = "%02d:%02d" % (t.tm_hour, t.tm_min)
def formatDate(t): local = time.localtime(t) now = time.localtime(time.time()) timeString = "%02d:%02d" % (local.tm_hour, local.tm_min) if local.tm_year == now.tm_year: if local.tm_yday == now.tm_yday: dateString = "Today" elif local.tm_yday == now.tm_yday - 1: dateString = "Yesterday" elif now.tm_yday - local.tm_yday ...
timeString = "%02d:%02d" % (local.tm_hour, local.tm_min) if local.tm_year == now.tm_year: if local.tm_yday == now.tm_yday:
if t.tm_year == now.tm_year: if t.tm_yday == now.tm_yday:
def formatDate(t): local = time.localtime(t) now = time.localtime(time.time()) timeString = "%02d:%02d" % (local.tm_hour, local.tm_min) if local.tm_year == now.tm_year: if local.tm_yday == now.tm_yday: dateString = "Today" elif local.tm_yday == now.tm_yday - 1: dateString = "Yesterday" elif now.tm_yday - local.tm_yday ...
elif local.tm_yday == now.tm_yday - 1:
elif t.tm_yday == now.tm_yday - 1:
def formatDate(t): local = time.localtime(t) now = time.localtime(time.time()) timeString = "%02d:%02d" % (local.tm_hour, local.tm_min) if local.tm_year == now.tm_year: if local.tm_yday == now.tm_yday: dateString = "Today" elif local.tm_yday == now.tm_yday - 1: dateString = "Yesterday" elif now.tm_yday - local.tm_yday ...
elif now.tm_yday - local.tm_yday < 7: dateString = time.strftime("%A", local)
elif now.tm_yday - t.tm_yday < 7: dateString = time.strftime("%A", t)
def formatDate(t): local = time.localtime(t) now = time.localtime(time.time()) timeString = "%02d:%02d" % (local.tm_hour, local.tm_min) if local.tm_year == now.tm_year: if local.tm_yday == now.tm_yday: dateString = "Today" elif local.tm_yday == now.tm_yday - 1: dateString = "Yesterday" elif now.tm_yday - local.tm_yday ...
dateString = time.strftime("%b %d", local)
dateString = time.strftime("%b %d", t)
def formatDate(t): local = time.localtime(t) now = time.localtime(time.time()) timeString = "%02d:%02d" % (local.tm_hour, local.tm_min) if local.tm_year == now.tm_year: if local.tm_yday == now.tm_yday: dateString = "Today" elif local.tm_yday == now.tm_yday - 1: dateString = "Yesterday" elif now.tm_yday - local.tm_yday ...
self.messages.push(str(message))
self.messages.push(str(message).encode('utf-8'))
def deliver(self, message=None): """An event has occurred which should be logged by this stats target""" if message: # FIXME: This ends up converting the message to a string, just so # the message buffer can then parse it again. If the message # buffer could directly convert DOMs back to SAX events, this ...
childEnv = dict(os.environ) del childEnv['DISPLAY']
del os.environ['DISPLAY']
def __init__(self): vte.Terminal.__init__(self) self.set_color_foreground(gtk.gdk.color_parse('Black')) self.set_color_background(gtk.gdk.color_parse('White')) editor = os.environ.get('EDITOR', 'vim') childEnv = dict(os.environ) del childEnv['DISPLAY'] self.fork_command('sh', ('sh', '-c', editor), ["=".join(i) for i in...
["=".join(i) for i in childEnv.iteritems()], os.getcwd(),
None, os.getcwd(),
def __init__(self): vte.Terminal.__init__(self) self.set_color_foreground(gtk.gdk.color_parse('Black')) self.set_color_background(gtk.gdk.color_parse('White')) editor = os.environ.get('EDITOR', 'vim') childEnv = dict(os.environ) del childEnv['DISPLAY'] self.fork_command('sh', ('sh', '-c', editor), ["=".join(i) for i in...
if segment[0] == 'x':
if not segment: results.append('\\') elif segment[0] == 'x':
def fromEscaped(s): """Properties that contain binary data are escaped using a backslash system. This converts from the escaped data back to a plain string. """ # Quickly handle all the easy ones, in order of frequency s = s.replace("\\x00", "\x00").replace("\\n", "\n") # Now we have a generic way to handle \\ and \x#...
yield os.path.join(CatalogWriter.catalogDir, catalog)
path = os.path.join(CatalogWriter.catalogDir, catalog) if os.path.isfile(path): yield path
def iterCatalogs(self): """A generator that returns the full path of all catalog files""" catalogs = os.listdir(CatalogWriter.catalogDir) catalogs.sort() for catalog in catalogs: yield os.path.join(CatalogWriter.catalogDir, catalog)
for allocator in botNet.servers.itervalues():
for server in botNet.servers.iterkeys():
def __init__(self, botNet): self.totalServers = 0 self.totalBots = 0 self.totalChannels = 0 for allocator in botNet.servers.itervalues(): self.totalServers += 1 for bot in allocator.bots.itervalues(): self.totalBots += 1 self.totalChannels += len(bot.channels)
for bot in allocator.bots.itervalues():
for bot in botNet.servers[server]:
def __init__(self, botNet): self.totalServers = 0 self.totalBots = 0 self.totalChannels = 0 for allocator in botNet.servers.itervalues(): self.totalServers += 1 for bot in allocator.bots.itervalues(): self.totalBots += 1 self.totalChannels += len(bot.channels)
def __init__(self, allocator): self.allocator = allocator
def __init__(self, botNet, server): self.botNet = botNet self.server = server
def getValue(self, bot): return len(bot.channels)
return "%s:%d" % (self.allocator.host, self.allocator.port)
return str(self.server)
def render_title(self, context): return "%s:%d" % (self.allocator.host, self.allocator.port)
tableId = self.allocator.host.replace(".", "_") + "_" + str(self.allocator.port) return [Template.Table(self.allocator.bots.values(), [
return [Template.Table(self.botNet.servers[self.server], [
def render_rows(self, context): tableId = self.allocator.host.replace(".", "_") + "_" + str(self.allocator.port) return [Template.Table(self.allocator.bots.values(), [ Nouvelle.AttributeColumn('nickname', 'nickname'), BotChannelsColumn(), ], id=tableId)]
], id=tableId)]
], id=str(self.server))]
def render_rows(self, context): tableId = self.allocator.host.replace(".", "_") + "_" + str(self.allocator.port) return [Template.Table(self.allocator.bots.values(), [ Nouvelle.AttributeColumn('nickname', 'nickname'), BotChannelsColumn(), ], id=tableId)]
allocators = self.botNet.servers.values() allocators.sort(lambda a,b: cmp(a.host, b.host)) return [ServerSection(a) for a in allocators]
servers = self.botNet.servers.keys() servers.sort(lambda a,b: cmp(str(a), str(b))) return [ServerSection(self.botNet, s) for s in servers]
def render_mainColumn(self, context): """Generate one ServerSection for each BotAllocator we have, sorted by hostname""" allocators = self.botNet.servers.values() allocators.sort(lambda a,b: cmp(a.host, b.host)) return [ServerSection(a) for a in allocators]
for i in range (len (paths['root'])):
for i in range (len (paths['root']) - 1):
def search_graphs (graphs, starts, ends, depth): paths = {} for bone in graphs.keys(): print ' searching',bone adjacency = graphs[bone].representations[AdjacencyList] edges = graphs[bone].representations[EdgeList] paths[bone] = algorithms_c.depthLimitedSearch (adjacency, edges, starts[bone], ends[bone], depth) ...