rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if self.dirCache and event.filename in self.dirCache:
if self.dirCache:
def onMonitorEvent(self, event): code = event.code2str()
del self.dirCache[event.filename]
try: del self.dirCache[event.filename] except KeyError: pass
def onMonitorEvent(self, event): code = event.code2str()
traceback.print_last()
traceback.print_exc()
def run(self): self.running = True self.connection = fam.open() self.monitorTypes = { 'file': self.connection.monitorFile, 'dir': self.connection.monitorDirectory, }
self.loadFromDom(xml)
self.loadFromString(toString(xml), uri)
def __init__(self, xml=None, uri=None): if type(xml) in types.StringTypes: self.loadFromString(xml, uri) elif hasattr(xml, 'read'): self.loadFromStream(xml, uri) elif hasattr(xml, 'nodeType'): self.loadFromDom(xml)
if self.name:
elif self.name:
def _getTitle(self, metadataTitle, result): if metadataTitle is not None: result.callback(metadataTitle) if self.name: result.callback(self.name) else: result.callback('Stats')
""" Checks the guess against the correct answer. If it's correct: guess
""" Checks the guess against the correct answer. If it's correct guess
def Guess(self, guess): """ Checks the guess against the correct answer. If it's correct: guess gets added to self.correct in all of the appropriate spots in the word. If it's incorrect it gets appended to self.guesses. correct and guesses are returned in a list, correct first. """ # If the answer is correct insert i...
are returned in a list, correct first.
are returned in a tuple, correct first.
def Guess(self, guess): """ Checks the guess against the correct answer. If it's correct: guess gets added to self.correct in all of the appropriate spots in the word. If it's incorrect it gets appended to self.guesses. correct and guesses are returned in a list, correct first. """ # If the answer is correct insert i...
""" A class for creating and controlling a GUI for Hangman. __init__ creates all the necessary widgets and connects them to the appropriate Hangman functions.
""" Acts as a view and controller for the Hangman class. __init__ creates all the necessary widgets for the main window. By creating an instance of HangmanGUI and starting gtk.main the game is all set up.
def TestEntry(self, index, entry): """ Provides a way to set the values in Hangman.correct with a list comprehension when the user guesses correct. TestEntry() returns the appropriate character for that index of Hangman.correct. If the letter there has been guessed correctly before, it is returned. If guess does not...
self.window.set_border_width(10) self.window.set_size_request(600, 400)
self.window.set_default_size(640, 480)
def __init__(self): # Game controller. self.controller = Hangman()
self.newGame = gtk.Button("New Game")
self.newGame = gtk.Button(stock=gtk.STOCK_NEW)
def __init__(self): # Game controller. self.controller = Hangman()
self.openButton = gtk.Button("Open File")
self.openButton = gtk.Button(stock=gtk.STOCK_OPEN)
def __init__(self): # Game controller. self.controller = Hangman()
self.quit = gtk.Button("Quit")
self.quit = gtk.Button(stock=gtk.STOCK_QUIT)
def __init__(self): # Game controller. self.controller = Hangman()
box2 = gtk.VBox(spacing=20)
box2 = gtk.VBox() box2.set_border_width(15)
def __init__(self): # Game controller. self.controller = Hangman()
self.window.add(box2)
def __init__(self): # Game controller. self.controller = Hangman()
dialog = gtk.Dialog("Quit", flags=gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR) yes = gtk.Button("Yes") yes.connect("clicked", self.destroy) yes.show() no = gtk.Button("No") no.connect("clicked", lambda w: dialog.destroy()) no.show() label = gtk.Label("Are you sure you want to quit?") label.show() dia...
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT| gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Are you sure you want to quit?") dialog.set_title("Quit") dialog.set_resizable(gtk.FALSE)
def Quit(self, widget, data=None): """ Quit. """ # Create a dialog to check if the user really wants to quit. dialog = gtk.Dialog("Quit", flags=gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR) # Yes button, they really want to quit. yes = gtk.Button("Yes") yes.connect("clicked", self.destroy) yes.show()
def destroy(self, widget, event=None):
response = dialog.run() if response == gtk.RESPONSE_YES: self.destroy() else: dialog.destroy() def destroy(self, widget=None, event=None):
def Quit(self, widget, data=None): """ Quit. """ # Create a dialog to check if the user really wants to quit. dialog = gtk.Dialog("Quit", flags=gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR) # Yes button, they really want to quit. yes = gtk.Button("Yes") yes.connect("clicked", self.destroy) yes.show()
def read(self, widget, event=None): filename = event.get_filename() if filename.find(".hmn") == -1: self.error(data="Please choose a .hmn file.")
def read(self, widget, data=None): """ Callback for file selection from openFile(). Get the file name and test it to make sure it has the right extension. """ filename = data.get_filename() if filename.find(".txt") == -1: self.error(data, "Please choose a .txt file.")
def read(self, widget, event=None): filename = event.get_filename() if filename.find(".hmn") == -1: self.error(data="Please choose a .hmn file.") return gtk.TRUE else: self.controller.words = open(filename, 'r').readlines() self.controller.words = [word.strip() for word in self.controller.words]
def error(self, widget=None, data=None):
def error(self, parent=None, data=None):
def error(self, widget=None, data=None): """ General error message generator. data is the text to be printed in the dialog box. """ # Create the dialog box. errorBox = gtk.Dialog("Error", flags=gtk.DIALOG_NO_SEPARATOR)
errorBox = gtk.Dialog("Error", flags=gtk.DIALOG_NO_SEPARATOR) message = gtk.Label(data) message.show() okButton = gtk.Button("Ok") okButton.connect("clicked", lambda w: errorBox.destroy()) okButton.show() errorBox.vbox.pack_start(message, gtk.TRUE, gtk.TRUE) errorBox.vbox.pack_end(okButton)
errorBox = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, data) errorBox.set_resizable(gtk.FALSE)
def error(self, widget=None, data=None): """ General error message generator. data is the text to be printed in the dialog box. """ # Create the dialog box. errorBox = gtk.Dialog("Error", flags=gtk.DIALOG_NO_SEPARATOR)
self.gc = self.window.new_gc(foreground=fgColor)
self.bg_gc = self.window.new_gc(foreground=fgColor) self.fg_gc = self.window.new_gc()
def gallowsRealize(self, widget, event): """ When the drawing area is realized set up a graphics context for it. """ # Get a color map and set the foreground to white in the graphics context. colormap = self.get_colormap() fgColor = colormap.alloc_color('white') self.gc = self.window.new_gc(foreground=fgColor)
for vertex in self.vertexMap.query (u): Relax (edge, self.weightf, self.estimates, self.predecessors)
for edge in self.vertexMap.query (u): if edge[0] is u: Relax (edge, self.weightf, self.estimates, self.predecessors)
def run (self): if self.valid: return self.results
return tag('a', href=uri)[ name ]
name = tag('a', href=uri)[ name ]
def format_file(self, name, fileTag=None): """Given the short name of a file, and optionally its XML tag, return a Nouvelle-serializable representation. """ if fileTag:
print "%s\t%s" % (md5sum(file), file)
print "%s\t%s" % (md5cache.get(file), file)
def cmd_md5(paths, filesPerCommand=20): pathGen = flattenPaths(paths) while 1: # At each iteration, look for files that need md5sums until we # run out of source files or we hit the filesPerCommand limit. calcFiles = [] allFiles = [] try: while len(calcFiles) < filesPerCommand: file = pathGen.next() allFiles.append(fil...
try: result = self.hub.deliver(Message(xml)) except: e = sys.exc_info()[1] return xmlrpc.Fault(e.__class__.__name__, str(e))
result = self.hub.deliver(Message(xml))
def xmlrpc_deliverMessage(self, xml): """Deliver the given message, provided as XML text. If the message generates a reply, returns that. Otherwise, returns True. """ try: result = self.hub.deliver(Message(xml)) except: e = sys.exc_info()[1] return xmlrpc.Fault(e.__class__.__name__, str(e)) if result is not None: retur...
self.sendLine("PING %f" % time.time())
self.lastPingTransmitTimestamp = time.time() self.sendLine("PING %f" % self.lastPingTransmitTimestamp)
def sendServerPing(self): """Send a ping stamped with the current time and schedule the next one""" self.sendLine("PING %f" % time.time()) reactor.callLater(self.pingInterval, self.sendServerPing)
self.lastPingTimestamp = float(params[1])
try: self.lastPingTimestamp = float(params[1]) except ValueError: self.lastPingTimestamp = self.lastPingTransmitTimestamp
def irc_PONG(self, prefix, params): """Handle the responses to pings sent with sendServerPing. This compares the timestamp in the pong (from when the ping was sent) and the current time, storing the lag and the current time. """ self.lastPingTimestamp = float(params[1]) self.lastPongTimestamp = time.time()
lag = self.lastPongTimestamp - self.lastPingTimestamp
if self.lastPingTimestamp is None: lag = None else: lag = self.lastPongTimestamp - self.lastPingTimestamp
def getLag(self): """Calculate a single figure for the lag between us and the server. If pings have been coming back on time this is just the raw lag, but if our latest ping has been particularly late, it's the average of the latest successful ping's lag and the amount of time we've been waiting for this late ping. """...
return (lag + (timeSincePong - self.pingInterval)) / 2
return ((lag or 0) + (timeSincePong - self.pingInterval)) / 2
def getLag(self): """Calculate a single figure for the lag between us and the server. If pings have been coming back on time this is just the raw lag, but if our latest ping has been particularly late, it's the average of the latest successful ping's lag and the amount of time we've been waiting for this late ping. """...
prefix = os.path.commonprefix(files)
prefix = re.sub("[^/]*$", "", os.path.commonprefix(files))
def consolidateFiles(self, xmlFiles): """Given a commit, find the directory common to all files and return a 2-tuple with that directory followed by a list of files within that directory. """ files = [] if xmlFiles: for fileTag in xmlFiles.elements(): if fileTag.name == 'file': files.append(str(fileTag))
print 'Not implemented'
for field in self.editables: field.writeOut()
def applyChanges(self, widget=None, data=None): ''' Apply the changes in all of the fields to the data file. ''' print 'Not implemented'
def writeOut(self, widget):
def writeOut(self, widget=None, data=None):
def writeOut(self, widget): ''' Save the data in text field to the XML data file. ''' self.characterData.setData(self.attributes['path'], self.text.get_text()) self.characterData.writeOut()
list.append(self.text)
list.append(self) def set_editable(self, is_editable): self.text.set_editable(is_editable)
def addEditable(self, list): ''' Add any editable fields to the list. ''' list.append(self.text)
list.append(self.menu.entry)
list.append(self) def set_editable(self, is_editable): if is_editable: self.buffer.set_text(string.join(self.items, '\n')) self.menu.hide() self.editScroller.show() else: self.items = self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter()).split('\n') self.menu.set_popdown_strings(self.items) se...
def addEditable(self, list): ''' Add the entry field to the list of editable things. ''' list.append(self.menu.entry)
__slots__ = ["bayes", "graphs", "adjacency", "order", "parents", "epsilon"]
__slots__ = ["asf", "bayes", "graphs", "adjacency", "order", "parents", "epsilon"]
def _getMatrix(data, dof): """Create the matrices A and b for a spline with 4 data points.""" # We need to be sure that we've got exactly 4 data points. assert(Numeric.shape(data)[0] == 4) A = Numeric.zeros((12, 12)) b = [Numeric.zeros((12,)) for i in range(dof)] row = 0 for t in range(1,4): # Constrain the spline to...
net = self.bayes[bone]
if bone in self.bayes: net = self.bayes[bone]
def combine(self, bones, items, position=0, current=[], current_probability=1.0): """Recusively create combinatoric successors.
parent = parents[bone] parent_pos = bones.index(parent) pbone = current[parent_pos]
parent = self.parents[bone] try: parent_pos = bones.index(parent) pbone = current[parent_pos] except ValueError: parent_pos = None
def combine(self, bones, items, position=0, current=[], current_probability=1.0): """Recusively create combinatoric successors.
(asf.bones[bone].dof or \ (parent in asf.bones and \ asf.bones[parent].dof))):
(self.asf.bones[bone].dof or \ (parent in self.asf.bones and \ self.asf.bones[parent].dof))) or \ not parent_pos:
def combine(self, bones, items, position=0, current=[], current_probability=1.0): """Recusively create combinatoric successors.
children = self.combine(bones[1:], items[1:], new_current, current_probability)
children = self.combine(bones, items, position + 1, new_current, current_probability)
def combine(self, bones, items, position=0, current=[], current_probability=1.0): """Recusively create combinatoric successors.
self.stack[-1].append(str(node))
self.stack[-1].append(node.astext())
def visit_Text(self, node): self.stack[-1].append(str(node))
self.docSubtitle = ''.join(map(str, node.children))
self.docSubtitle = node.astext()
def visit_subtitle(self, node): # We really only care about the top-level subtitle now if not self.headingLevel: self.docSubtitle = ''.join(map(str, node.children)) raise nodes.SkipNode
if self.logLinesLimit and len(lines) > self.logLinesLimit:
if self.logLinesLimit and len(lines) > self.logLinesLimit + 1:
def format_log(self, logString): # Break the log string into lines... lines = [] for line in logString.split("\n"): # Ignore blank lines if not line.strip(): continue
ioctl(self.dev, 0x3701, struct.pack("HH", address, data))
ioctl(self.dev, 0x3701, struct.pack("HB", address, data))
def poke(self, address, data): """Store the given address/data pair""" ioctl(self.dev, 0x3701, struct.pack("HH", address, data))
if len (sys.argv) < 2:
if len (sys.argv) < 3:
def load (files): amcs = [] graphs = {} # Open all the AMC files at once, so we can build entire graphs at once. for filename in files: print 'loading',filename amcs.append (AMC.from_file (filename)) # Build the actual graphs. We iterate over bones, building graphs for each. # This assumes that we have the same bone...
self.summarizeFiles(endings)
endingStr = self.summarizeFiles(endings)
def format_files(self, files): """Break up our list of files into a common prefix and a sensibly-sized list of filenames after that prefix. Prepend the module name if we have one. """ prefix, endings = self.consolidateFiles(files) endingStr = " ".join(endings) if len(endingStr) > 20: # If the full file list is too long...
title = ''.join(map(str, node.children))
title = node.astext()
def visit_title(self, node): title = ''.join(map(str, node.children)) if self.headingLevel: # Make this into a heading tag self.stack[-1].append(tag('h%d' % self.headingLevel)[title]) else: # Nope, this must be the top-level title. self.docTitle = title raise nodes.SkipNode
def expectHelloPacket(self, socket, eventLoop): hello = socket.readStruct(FromServer.HelloPacket) if hello.version != BZFlag.protocolVersion: raise Protocol.ProtocolError( "Protocol version mismatch: The server is version " + "'%s', this client is version '%s'." % ( hello.version, BZFlag.protocolVersion)) self.id = h...
def expectHelloPacket(self, socket, eventLoop): # We should have just received a Hello packet with # the server version and our client ID. hello = socket.readStruct(FromServer.HelloPacket) if hello.version != BZFlag.protocolVersion: raise Protocol.ProtocolError( "Protocol version mismatch: The server is version " + "'%...
print "calculating cost to a"
def compare(self, a, b): keyA = repr(a) keyB = repr(b)
print "calculating cost to b"
def compare(self, a, b): keyA = repr(a) keyB = repr(b)
print "Looking up costs"
def compare(self, a, b): keyA = repr(a) keyB = repr(b)
print "loop"
def pathToNode(self, node): path = [node] next = self.predecessors[repr(node)]
print "got path to node"
def pathToNode(self, node): path = [node] next = self.predecessors[repr(node)]
def __init__ (self, graph, costf, successors, source, goal): source.color = "green"
def __init__ (self, graph, costf, source, goal): source.color = "cyan"
def __init__ (self, graph, costf, successors, source, goal): source.color = "green" goal.color = "red" Heuristic.__init__ (self, graph, costf, successors, source, goal)
Heuristic.__init__ (self, graph, costf, successors, source, goal)
Heuristic.__init__ (self, graph, costf, source, goal)
def __init__ (self, graph, costf, successors, source, goal): source.color = "green" goal.color = "red" Heuristic.__init__ (self, graph, costf, successors, source, goal)
print "coloring path"
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
print "coloring..."
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
print "goal!"
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
for s in self.successors(self.graph, node):
adj = self.graph.representations[Data.AdjacencyList] for edge in adj.query (node):
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
if s not in visited:
if edge.v not in visited:
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
self.predecessors[repr(s)] = node agenda.append(s)
self.predecessors[repr(edge.v)] = node agenda.append(edge.v)
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
print "sorting..."
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
print "done"
step += 1
def run (self): """Execute a heuristic search of a graph. Returns: A list of nodes that is the path from the source to the goal or ``None`` if there is no path. """ if self.path: return self.path
subTitle = "what's that blue thing doing there?"
subTitle = "When you give a mouse a cookie, everything looks like a nail"
def render_rows(self, context): newBots = [] for server, timer in self.botNet.newBotServers.iteritems(): newBots.append((server, TimeUtil.formatDuration(timer.getTime() - time.time()))) if newBots: return [Template.Table(newBots, self.columns, id='newBots')] else: return []
class RulesetController(object): """Listens for messages used to store and query rulesets""" def __init__(self, hub, storage): self.storage = storage self.hub = hub self.addClients() def addClients(self): """Add our clients to the Message.Hub. This uses an extra level of indirection so that rebuild() can replace refer...
def flatten(self): """Return a flat list of all Ruleset objects so we can store 'em""" return [delivery.ruleset for delivery in self.rulesetMap.itervalues()]
return self.find_node (node)
n[bone] = pos return self.find_node (n)
def fixNode (node): n = {} for bone, pos in node.iteritems (): if bone == "root": pos = pos[3:6] pos = [Numeric.remainder (d, 360.0) for d in pos] pos = tuple (map (fix360, map (fixnegative, pos))) return self.find_node (node)
if vertex.inside (pos):
for bone, node in vertex.iteritems (): if node.inside (pos[bone]): break
def find_node (self, pos): """Returns a vertex from 'graph' that contains 'pos'.
version = self.message['X-Bugzilla-Version']
def parse(self): component = self.message['X-Bugzilla-Component'] module = self.message['X-Bugzilla-Product'] priority = self.message['X-Bugzilla-Severity'] severity = self.message['X-Bugzilla-Priority'] status = self.message['X-Bugzilla-Status'] version = self.message['X-Bugzilla-Version']
if cline.endswith("changed:"): self.readReporter(cline)
def parse(self): component = self.message['X-Bugzilla-Component'] module = self.message['X-Bugzilla-Product'] priority = self.message['X-Bugzilla-Severity'] severity = self.message['X-Bugzilla-Priority'] status = self.message['X-Bugzilla-Status'] version = self.message['X-Bugzilla-Version']
def readReporter(self, line): self.addReporter(' '.join(line.split(' ')[:-1]))
if state == 'new': if cline.startswith("ReportedBy:"): self.addReporter(' '.join(cline.split(' ')[1:])) else: if cline.endswith("changed:"): self.addReporter(' '.join(cline.split(' ')[:-1]))
def readReporter(self, line): self.addReporter(' '.join(line.split(' ')[:-1]))
return file
if response == gtk.RESPONSE_OK: return file return None
def _FileChooser (): ''' File selection dialog. ''' xml = gtk.glade.XML ("data/filechooser.glade") dialog = xml.get_widget ("filechooserdialog") response = dialog.run () file = dialog.get_filename () dialog.destroy () return file
msg = "<b>%s</b>\n\n%s" % (primary, secondary) xml.get_widget ("text").label = msg return xml.get_widget ("error dialog").run ()
dialog.run () dialog.destroy ()
def _ErrDialog (primary, secondary=""): ''' A generic error dialog box. ''' xml = gtk.glade.XML ("data/errordialog.glade") msg = "<b>%s</b>\n\n%s" % (primary, secondary) xml.get_widget ("text").label = msg return xml.get_widget ("error dialog").run ()
print "Changing style"
def setStyle(self, widget, data): """ Set the style from the menu check item selected, only if the newly selected style isn't the same as the current style.
return 'r' + IRC.format(str(rev), 'bold')
return 'r' + IRC.format(CommitFormatter.format_revision(self, rev), 'bold')
def format_revision(self, rev): import IRC return 'r' + IRC.format(str(rev), 'bold')
return IRC.format(module, 'aqua')
return IRC.format(CommitFormatter.format_module(self, module), 'aqua')
def format_module(self, module): import IRC return IRC.format(module, 'aqua')
return IRC.format(branch, 'orange')
return IRC.format(CommitFormatter.format_branch(self, branch), 'orange')
def format_branch(self, branch): import IRC return IRC.format(branch, 'orange')
self.adjacency = dict (graph.representations[AdjacencyList].data)
self.source = source self.goal = goal self.adjacency = dict (graph.representations[BayesAdjacency].data)
def fixNode (node): """Short helper function that fixes negative angles and insures that all angles are on the interval [0, 360). """ n = {} for bone, pos in node.iteritems (): if bone == "root": pos = pos[3:6] pos = [Numeric.remainder (d, 360.0) for d in pos] pos = tuple (map (fix360, map (fixnegative, pos))) n[bone] ...
for i in range(len(path)):
for i in range(len(self.path)):
def run (self): """Execute the graph search.""" if self.path: return self.path
rootstart = list(start["root"][0:3]) rootend = list(end["root"][0:3])
rootstart = list(self.source["root"][0:3]) rootend = list(self.goal["root"][0:3])
def run (self): """Execute the graph search.""" if self.path: return self.path
vertex_map = self.graph.representations[VertexMap]
vertex_map = self.graph.representations[Data.VertexMap]
def find_node (self, pos): """Finds the node in ``self.graph`` conataining the position ``pos``.
def poll_handler():
def update():
def poll_handler(): reading = sensor.readAverages() channel.value = [model.predict(reading) for model in models] gtk.timeout_add(10, poll_handler)
gtk.timeout_add(10, poll_handler) gtk.timeout_add(10, poll_handler)
gtk.timeout_add(10, update) update()
def poll_handler(): reading = sensor.readAverages() channel.value = [model.predict(reading) for model in models] gtk.timeout_add(10, poll_handler)
print self.storage.rulesetMap
def xmlrpc_getUriList(self): """Return a list of all URIs with non-empty rulesets""" print self.storage.rulesetMap return self.storage.rulesetMap.keys()
__slots__ = ['nodes']
def normalize (self, total): self.weight = float (self.count) / total self.dot_label = '%.2f' % self.weight
if x < 0: return x + 360
while x < 0: x = x + 360
def fixnegative (x): if x < 0: return x + 360 return x
def build_graph (key, d):
def build_graphs (key, datas): """Build a graph using the data arrays from any number of files."""
def build_graph (key, d): # if this is the root, we only want the first 3 dof, for now # FIXME - we really should do some stuff to track root orientation, # but that's a much more complicated problem. if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0] # degrees covered (angle-wise) within a singl...
if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0]
if key == 'root': datas = [d[:,0:3] for d in datas] datas = [Numeric.remainder (d, 360.0) for d in datas] dof = datas[0].shape[1]
def build_graph (key, d): # if this is the root, we only want the first 3 dof, for now # FIXME - we really should do some stuff to track root orientation, # but that's a much more complicated problem. if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0] # degrees covered (angle-wise) within a singl...
mins = [] slots = [] graph = MotionGraph ()
graph = MotionGraph ()
def build_graph (key, d): # if this is the root, we only want the first 3 dof, for now # FIXME - we really should do some stuff to track root orientation, # but that's a much more complicated problem. if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0] # degrees covered (angle-wise) within a singl...
vertex_map = VertexMap (graph) edge_list = EdgeList (graph) d = Numeric.remainder (d, 360.0)
vertex_map = VertexMap (graph) edge_list = EdgeList (graph)
def build_graph (key, d): # if this is the root, we only want the first 3 dof, for now # FIXME - we really should do some stuff to track root orientation, # but that's a much more complicated problem. if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0] # degrees covered (angle-wise) within a singl...
graph.nodes = nodes
for d in datas: build_graph (d, graph, nodes, edge_list, interval) for vertex in vertex_map: total = 0 edges = vertex_map.query (vertex) for edge in edges: if edge.u is vertex: total += edge.count for edge in edges: if edge.u is vertex: edge.normalize (total) return graph def build_graph (d, graph, nodes, edge_lis...
def build_graph (key, d): # if this is the root, we only want the first 3 dof, for now # FIXME - we really should do some stuff to track root orientation, # but that's a much more complicated problem. if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0] # degrees covered (angle-wise) within a singl...
for vertex in vertex_map: total = 0 edges = vertex_map.query (vertex) for edge in edges: if edge.u is vertex: total += edge.count for edge in edges: if edge.u is vertex: edge.normalize (total) return graph def load (filename): amc = AMC.from_file (filename) bones = {} for (key, data) in amc.bones.iteritems ():
def load (files): amcs = [] for filename in files: amcs.append (AMC.from_file (filename)) for key in amcs[0].bones.iterkeys ():
def build_graph (key, d): # if this is the root, we only want the first 3 dof, for now # FIXME - we really should do some stuff to track root orientation, # but that's a much more complicated problem. if (key == 'root'): d = d[:,0:3] dof = d.shape[1] frames = d.shape[0] # degrees covered (angle-wise) within a singl...
g = build_graph (key, data)
g = build_graphs (key, [amc.bones[key] for amc in amcs])
def load (filename): amc = AMC.from_file (filename) bones = {} for (key, data) in amc.bones.iteritems (): print 'building graph for',key g = build_graph (key, data) if g is not None: f = file ('graphs/%s.dot' % key, 'w') DotPrint (g, f) f.close ()
if len (sys.argv) != 2: print 'Usage: %s [file.amc]' % sys.argv[0]
if len (sys.argv) < 2: print 'Usage: %s [FILE]...' % sys.argv[0]
def load (filename): amc = AMC.from_file (filename) bones = {} for (key, data) in amc.bones.iteritems (): print 'building graph for',key g = build_graph (key, data) if g is not None: f = file ('graphs/%s.dot' % key, 'w') DotPrint (g, f) f.close ()
load (sys.argv[1])
load (sys.argv[1:])
def load (filename): amc = AMC.from_file (filename) bones = {} for (key, data) in amc.bones.iteritems (): print 'building graph for',key g = build_graph (key, data) if g is not None: f = file ('graphs/%s.dot' % key, 'w') DotPrint (g, f) f.close ()
def openSheet(self): self.tree.dialog = gtk.glade.XML('data/sheetselection.glade') self.tree.dialog.get_widget('SheetSelection').set_filename('CharacterSheet/data/') self.tree.dialog.signal_autoconnect({ 'on_ok_button_clicked':self.installSheet,
def openSheet(self, widget=None, data=None): self.dialog = gtk.glade.XML('data/sheetselection.glade') self.dialog.get_widget('SheetSelection').set_filename('CharacterSheet/data/') self.dialog.signal_autoconnect({ 'on_ok_button_clicked':self.installSheet,
def openSheet(self): self.tree.dialog = gtk.glade.XML('data/sheetselection.glade') self.tree.dialog.get_widget('SheetSelection').set_filename('CharacterSheet/data/') self.tree.dialog.signal_autoconnect({ 'on_ok_button_clicked':self.installSheet, 'on_cancel_button_clicked':lambda w: self.tree.dialog.get_widget('SheetSel...
self.tree.dialog.get_widget('SheetSelection').destroy()
self.dialog.get_widget('SheetSelection').destroy()
def installSheet(self, widget, data=None): ''' Open up a character sheet in the client. ''' # Store the character data. self.data = Character(self.tree.dialog.get_widget('SheetSelection').get_filename())
items.append(xml(i))
items.append(Nouvelle.xml(i))
def render_items(self, context, limit=15): """Renders the most recent commits as items in the RSS feed""" formatter = Message.AutoFormatter('rss') items = [] for m in self.target.recentMessages.getLatest(limit): i = formatter.format(Message.Message(m)) if i: items.append(xml(i)) else: # We can't find a formatter, stick...
except IndexError:
except KeyError:
def menu(title, items): while True: print title itemNumber = 0 itemMap = {} for item, value in items.iteritems(): itemNumber += 1 print "%d. %s" % (itemNumber, item) itemMap[itemNumber] = value try: choice = int(sys.stdin.readline()) return itemMap[choice] except ValueError: print "Not a number, you dork" except IndexE...
id = self.hash(self, *args) print "%r hashes to %r" % (args, id)
id = self.hash(*args)
def get(self, *args): """Retrieve the item associated with some set of arguments. If the item doesn't exist in the cache, this calls miss() with the same arguments to generate the item, and adds it to the cache.
if rows and rows[0][1] > time.time(): result.callback(rows[0][0]) Database.pool.runOperation("UPDATE cache SET atime = %s WHERE id = %s" % (Database.quote(int(time.time()), 'bigint'), Database.quote(id, 'varchar'))) else: defer.maybeDeferred(self.miss, *args).addCallback( self.returnAndStoreValue, result, id).addErr...
if rows: value, expiration = rows[0] if expiration is None or expiration > time.time(): result.callback(rows[0][0]) Database.pool.runOperation("UPDATE cache SET atime = %s WHERE id = %s" % (Database.quote(int(time.time()), 'bigint'), Database.quote(id, 'varchar'))) return defer.maybeDeferred(self.miss, *args).addCa...
def _get(self, rows, result, id, args): """This gets called after we've checked our database and either received a cached copy of the data or nothing. If we have a cached copy and it hasn't expired yet, return that. Otherwise, we can start creating the data to return. """ if rows and rows[0][1] > time.time(): # It's a ...
database's varchar(32) id field. This uses a hash() of the arguments plus our class, so each subclass of the
database's varchar(32) id field. hash() can easily become instable across multiple invocations, so this uses an md5sum of the object's repr(). The name of our class is included, so each subclass of the
def hash(self, *args): """Convert our arguments to something that will fit in the database's varchar(32) id field. This uses a hash() of the arguments plus our class, so each subclass of the abstract cache will have a different id space. """ return str(hash((self.__class__, args)))
return str(hash((self.__class__, args)))
return md5.md5(repr( (self.__class__.__name__, args) )).hexdigest()
def hash(self, *args): """Convert our arguments to something that will fit in the database's varchar(32) id field. This uses a hash() of the arguments plus our class, so each subclass of the abstract cache will have a different id space. """ return str(hash((self.__class__, args)))