rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.channelList = ChannelList(self.graph, self.channels)
self.channelList = ChannelList(self.graph, self.channels, autoColor = self.autoColor, valueUpdateInterval = self.valueUpdateInterval)
def createChannelList(self): """Create the channel list widget and a scrolling container for it""" self.channelList = ChannelList(self.graph, self.channels) self.channelList.show()
return self.joinMessage(self, metadata, self.format_log(str(log)))
return self.joinMessage(self, metadata, self.format_log(str(commit.log)))
def format(self, message, input=None): """Break the commit message up into pieces that are each formatted with one of our format_* member functions. """ commit = message.xml.body.commit metadata = [] if commit.author: metadata.append(self.format_author(str(commit.author))) if commit.revision: metadata.append(self.forma...
print "%s (%d @%d)" % (self.absPath, count, offset)
def read(self, offset, count): if not self.openedFile: self.open()
self.extractMeshes(node)
self.extractMeshes(node, ())
def __init__(self, name): self.encoding = 'utf8' self.meshes = {}
def extractMeshes(self, node, parents=()):
def extractMeshes(self, node, parents):
def extractMeshes(self, node, parents=()): """Recursively traverse a tree of parsed nodes, extracting meshes into Drawables""" newParents = (node,) + parents
This reduces the mounts to a set of unique devices, and uses self._mergeStatVfs to combine the results.
def create(self, path): """Find a home for a new file given by 'path'. This creates parent directories as necessary and returns the new absolute path where the file should go. This reduces the mounts to a set of unique devices, and uses self._mergeStatVfs to combine the results. """ raise NotImplementedError
reactor.callLater(60*60, self.run)
self.scheduledRun = reactor.callLater(60*60, self.run)
def run(self): """Triggers one maintenance cycle, and sets up the next one""" log.msg("Initiating stats maintenance...") Database.pool.runInteraction(self._run)
Sequencer.FadeIn(0.5, (1,1,1), Sequencer.FadeOut(0.25, (0,0,0), DeviceMenu))
Sequencer.FadeIn(0.5, (1,1,1), Sequencer.FadeOut(0.25, (0,0,0), lambda book: DeviceMenu(book, self.hardware)))
def getPages(self): """Return a list of pages to include in the main sequencer book""" return [ # Display the logo sequence until user interruption Sequencer.FadeOut(0.2, (1,1,1), logoInterrupter),
def __init__(self, book):
def __init__(self, book, hardware): self.hardware = hardware
def __init__(self, book): # For now this just shows all icons we have. # Construct a list of Menu.Item instances for each loaded icon. menuItems = [Menu.Item(Icon.load(name)) for name in Icon.getIconDict().keys()] Menu.RingMenu.__init__(self, book, menuItems)
def __init__(self, period, callable, name=None, runNow=True):
def __init__(self, period, callable, name=None, runNow=False):
def __init__(self, period, callable, name=None, runNow=True): if not name: name = repr(callable)
self.db.autocommit(1)
self.db.cursor().execute("SET AUTOCOMMIT=1")
def __init__(self, **params): self.db = MySQLdb.connect(**params)
db="therm", host="navi",
db="therm", host=getDatabaseHost(),
def getSource(self, name): """Look up a source by name""" for row in self.iterDictQuery("SELECT * FROM sources WHERE name = '%s'" % ( self.db.escape_string(name))): return ThermSource(self, **row) raise KeyError("No such therm source %r" % name)
Printable.__init__ (self, kwargs)
Printable.__init__ (self, **kwargs)
def __init__ (self, u, v, **kwargs): """Initialize the edge with 2 nodes and a list of attributes.
usedBots.setdefault(reqBot, {})[request.channel] = True
usedBots.setdefault(reqBot, util.InsensitiveDict())[request.channel] = True
def checkBots(self): """Search for unfulfilled requests, trying to satisfy them, then search for unused bots and channels, deleting them or scheduling them for deletion. """ # Scan through all requests, trying to satisfy those that aren't. # Make note of which bots and which channels are actually being used. # activeBo...
def __init__(self, botNet):
def __init__(self, hub, botNet): self.tupleToUriMap = {} self.hub = hub
def __init__(self, botNet): self.botNet = botNet Ruleset.RegexURIHandler.__init__(self)
self.botNet.addChannel(*self.uriToTuple(uri))
t = self.uriToTuple(uri) if self.tupleToUriMap.has_key(t) and self.tupleToUriMap[t] != uri: raise Ruleset.InvalidURIException("Another URI referring to the same server and channel already exists") self.tupleToUriMap[t] = uri self.botNet.addChannel(*t)
def assigned(self, uri, newRuleset): self.botNet.addChannel(*self.uriToTuple(uri))
self.botNet.delChannel(*self.uriToTuple(uri))
t = self.uriToTuple(uri) self.botNet.delChannel(*t) del self.tupleToUriMap[t]
def unassigned(self, uri): self.botNet.delChannel(*self.uriToTuple(uri))
self.kickCallback((self.host, self.port), channel)
self.kickCallback((self.host, self.port), channel, kicker, message)
def botKicked(self, bot, channel, kicker, message): """Apparently we aren't wanted any longer. Log the event and report to our owner""" log.msg("Bot %r on server %r was kicked from %r by %r: %r" % (bot.nickname, self.host, channel, kicker, message)) if self.kickCallback: self.kickCallback((self.host, self.port), channe...
message = string.join(messages[0])
if messages[0][1]: message = string.join(messages[0]) else: message = messages[0][0]
def ctcpReceive(self, user, channel, messages): nick = re.search('([^!]*).*', user).group(1) if 'ROLL' in messages[0]: data = re.search('(\[.*\]) ([0-9]*) ([0-9]*)', messages[0][1]) text = nick + ' rolled a ' + str(len(data.group(1).split())) + 'd' + data.group(2) + ': ' + data.group(1) + ' => ' + data.group(3) else: m...
self.factory.nick(str(nick))
self.factory.nick(self.factory.channels[0], str(nick))
def on_set_character_as_nick_activate(self, widget, data=None): ''' Looks in the name tag of the data for a character name and sets that as the user's nick.
cpu, user, nice, sys, idle = re.split("\s+", line.strip())
cpu, user, nice, sys, idle = re.split("\s+", line.strip())[:5]
def readCpuStat(self): """Reads the 'cpu' line in /proc/stat""" f = open("/proc/stat") for line in f.xreadlines(): if line.startswith("cpu "): cpu, user, nice, sys, idle = re.split("\s+", line.strip()) break f.close() return (long(user) + long(nice + sys), long(idle))
graph = graph.HScrollAreaGraph(
graph = rtgraph.HScrollAreaGraph(
def getValue(self): newStatValues = self.readCpuStat()
print "root path %r, path segments %r" % (context['statsRootPath'], self.target.pathSegments)
def getURL(self, context): print "root path %r, path segments %r" % (context['statsRootPath'], self.target.pathSegments) return context['statsRootPath'] + '/'.join(self.target.pathSegments) + '/.metadata/' + self.key
self.statsPage.preRender(context)
context['statsRootPath'] = self.statsPage.findRootPath(context['request'], 1) context['statsTarget'] = self.statsPage.target
def preRender(self, context): # We need our stats page to add its 'statsRootPath' so we can generate hyperlinks properly self.statsPage.preRender(context)
def findRootPath(self, request):
def findRootPath(self, request, additionalDepth=0):
def findRootPath(self, request): """Find the URL path referring to the root of the current stats tree The returned path begins and ends with a slash. """ pathSegments = [s for s in request.path.split('/') if s] treeDepth = len(self.target.pathSegments) if treeDepth: pathSegments = pathSegments[:-treeDepth] return '/' +...
treeDepth = len(self.target.pathSegments)
treeDepth = len(self.target.pathSegments) + additionalDepth print "pathsegments %r, treeDepth %r" % (pathSegments, treeDepth)
def findRootPath(self, request): """Find the URL path referring to the root of the current stats tree The returned path begins and ends with a slash. """ pathSegments = [s for s in request.path.split('/') if s] treeDepth = len(self.target.pathSegments) if treeDepth: pathSegments = pathSegments[:-treeDepth] return '/' +...
context['statsTarget'] = self.target
def preRender(self, context): context['statsRootPath'] = self.findRootPath(context['request']) context['statsTarget'] = self.target
return s.replace("\\", "\\\\").replace("=", "\\")
return s.replace("\\", "\\\\").replace("=", "\\=")
def _graftEscape(self, s): """Escape a path for use with mkisofs graft points""" return s.replace("\\", "\\\\").replace("=", "\\")
for disc, fs in pathMap.iteritems(): subproc.tochild.write(self._graftEscape(disc) + "=" + self._graftEscape(fs) + "\n") subproc.tochild.close()
try: for disc, fs in pathMap.iteritems(): subproc.tochild.write(self._graftEscape(disc) + "=" + self._graftEscape(fs) + "\n") subproc.tochild.close() except IOError: self.readBurnOutput(subproc) raise self.readBurnOutput(subproc) retval = subproc.wait() if retval != 0: raise BurnFailure("%r failed with error code %r"...
def burn(self, pathMap): """Burn a new session to the current disc, with the given dict mapping paths on the disc to paths in our filesystem.
retval = subproc.wait() if retval != 0: raise BurnFailure("%r failed with error code %r" % (cmd, retval))
def burn(self, pathMap): """Burn a new session to the current disc, with the given dict mapping paths on the disc to paths in our filesystem.
c = tuple (int (n / interval) * interval for n in tuple (map (fixnegative, c))) c = tuple (map (fix360, c)) if ((), c) in net: net[((), c)] = net[((), c)] + 1 else: net[((), c)] = 1
for frame in range(len(cbone)): c = cbone[frame,:] c = tuple (int (n / interval) * interval for n in tuple (map (fixnegative, c))) c = tuple (map (fix360, c)) if ((), c) in net: net[((), c)] = net[((), c)] + 1 else: net[((), c)] = 1
def load(asf, files): amcs = [] nets = {} for filename in files: print 'loading %s' % filename amcs.append(AMC.from_file(filename)) relationships = {} for rel in asf.hierarchy: parent = rel[0] children = rel[1:] if len(parent): relationships[parent] = children for child in children: if child in amcs[0].bones: nets[ch...
nets[(parent, child)] = float(count) / float(total)
net[(parent, child)] = float(count) / float(total) nets[bone] = net
def load(asf, files): amcs = [] nets = {} for filename in files: print 'loading %s' % filename amcs.append(AMC.from_file(filename)) relationships = {} for rel in asf.hierarchy: parent = rel[0] children = rel[1:] if len(parent): relationships[parent] = children for child in children: if child in amcs[0].bones: nets[ch...
def __init__(self, fs, path, type, size=0, blocks=0):
def __init__(self, fs, path, type, size=0):
def __init__(self, fs, path, type, size=0, blocks=0): self.path = path self.fs = fs self.type = type self.dir = dir self.size = size self.blocks = blocks
self.blocks = blocks
self.blocks = (size-1)/self.blocksize+1
def __init__(self, fs, path, type, size=0, blocks=0): self.path = path self.fs = fs self.type = type self.dir = dir self.size = size self.blocks = blocks
size=self.fileStat.st_size, blocks=self.fileStat.st_blocks)
size=self.fileStat.st_size)
def __init__(self, fs, path=''):
commandByte = sd | (channel << 4) | (powerMode << 2)
commandByte = sd | (self.channelTable[channel] << 4) | (powerMode << 2)
def read(self, channel, returnType=float, powerMode=0, differential=False): """Sample the given channel number, blocking until it is complete.
if os.path.isdir(self.path): return dirlist.DirectoryLister(self.path).render(request)
path = self.path if os.path.isdir(path): if os.path.isfile(os.path.join(path, 'index')): path = os.path.join(path, 'index') else: return dirlist.DirectoryLister(path).render(request) elif not os.path.isfile(path): return error.NoResource("File not found.").render(request)
def render(self, request): """Overrides the default render() function for pages. This checks whether our path is really a file or a directory- if it's a directory, we show a directory listing page. If it's a file, this formats our document and passes control on to the usual rendering processes. """ # Is this actually a...
self.leftColumn = self.formatDocument(self.findSidebarPath()).output
self.leftColumn = self.formatDocument(self.findSidebarPath(path)).output
def render(self, request): """Overrides the default render() function for pages. This checks whether our path is really a file or a directory- if it's a directory, we show a directory listing page. If it's a file, this formats our document and passes control on to the usual rendering processes. """ # Is this actually a...
mainDoc = self.formatDocument(self.path)
mainDoc = self.formatDocument(path)
def render(self, request): """Overrides the default render() function for pages. This checks whether our path is really a file or a directory- if it's a directory, we show a directory listing page. If it's a file, this formats our document and passes control on to the usual rendering processes. """ # Is this actually a...
def findSidebarPath(self): if os.path.isfile(self.path + '.sidebar'): return self.path + '.sidebar' else: return os.path.join(os.path.split(self.path)[0], 'default.sidebar')
def findSidebarPath(self, path): if os.path.isfile(path + '.sidebar'): return path + '.sidebar' else: return os.path.join(os.path.split(path)[0], 'default.sidebar')
def findSidebarPath(self): if os.path.isfile(self.path + '.sidebar'): return self.path + '.sidebar' else: return os.path.join(os.path.split(self.path)[0], 'default.sidebar')
return ''.join([self.parse(e) for e in element.children])
return ''.join([s for s in self.childParser(element) if s])
def unknownElement(self, element): return ''.join([self.parse(e) for e in element.children])
test = Graph([
testEdges = [
def runLayout(hlGraph): """Given a high-level Graph instance, run layout and write an SVG file""" # Make a force_directed graph from that fdGraph = force_directed.Graph(hlGraph.edgeTuples, len(hlGraph.vertexList)) print fdGraph fdGraph.randomize(0, 0, 100, 100) try: while 1: print "energy: %f" % fdGraph.iteration() ex...
])
Edge(1, 0), ] for i in xrange(40): testEdges.append(Edge(0, 100+i)) test = Graph(testEdges)
def runLayout(hlGraph): """Given a high-level Graph instance, run layout and write an SVG file""" # Make a force_directed graph from that fdGraph = force_directed.Graph(hlGraph.edgeTuples, len(hlGraph.vertexList)) print fdGraph fdGraph.randomize(0, 0, 100, 100) try: while 1: print "energy: %f" % fdGraph.iteration() ex...
nodes[angle] = node
nodes[tuple(angle)] = node
def build_graphs (key, datas, interval): """Build a graph using the data arrays from any number of files. Arguments: - `key` The key for which the graph should be built - `datas` A dictionary of motion data, the values in the dictionary are Numeric arrays """ # If this is the root, we only want the last 3 dof,...
self.setNick("CIA-temp%03d" % random.randint(0, 999))
tempNick = "CIA-temp%03d" % random.randint(0, 999) self.nicknames.append(tempNick) self.setNick(tempNick)
def irc_ERR_NICKNAMEINUSE(self, prefix, params): """An alternate nickname-in-use error handler that generates a random temporary nick. This will let us at least connect to the server and issue WHOIS queries to efficiently find a better nick.
version = '1.18'
version = '1.19'
def makeTag(self, config): """Return an XML tag for this file, using the given config""" attrs = {}
(command, self.revision, self.repository)).read(), 'utf-8')
(command, self.revision, self.repository)).read(), 'utf-8', 'replace')
def svnlook(self, command): """Run the given svnlook command on our current repository and revision, returning all output""" # We have to set LC_ALL to force svnlook to give us UTF-8 output, # then we explicitly slurp that into a unicode object. return unicode(os.popen( 'LC_ALL="en_US.UTF-8" svnlook %s -r "%s" "%s"' % ...
if uri is not None and delivery.ruleset.uri == uri:
if uri is None or delivery.ruleset.uri == uri:
def queryRulesets(self, message): """Handles messages containing a <queryRulesets> tag in its body. If queryRulesets includes a 'uri' attribute, the ruleset for that URI is returned in a 1-item list, or an empty list if that URI has no ruleset. Without the 'uri' attribute, returns a list of strings representing all rul...
node = node[1].setdefault(segment, [None, {}])
if segment: node = node[1].setdefault(segment, [None, {}])
def component_files(self, element, args): """Format the contents of our <files> tag as a tree with nested lists""" from LibCIA.Web import Template
mntRpc.stop()
mountRpc.stop()
def NFSPROC_STATFS(self, fh): """Use the DiskSet's statvfs() implementation""" vfstat = self.fs.diskSet.statvfs() stat = rfc1094.statfsres () stat.status = rfc1094.NFS_OK stat._data = stat.info ( tsize = 1024 * 16, # Optimum transfer size bsize = vfstat[statvfs.F_BSIZE], blocks = vfstat[statvfs.F_BLOCKS], bfree = v...
while self.thread.isAlive():
while self.isAlive():
def waitForCompletion(self): self.stop = True
def __init__(self, graph, costf, successors, source, goal):
def __init__(self, graph, costf, source, goal):
def __init__(self, graph, costf, successors, source, goal): self.costf = costf self.successors = successors self.source = source self.goal = goal Algorithm.__init__ (self, graph) self.run ()
self.successors = successors
def __init__(self, graph, costf, successors, source, goal): self.costf = costf self.successors = successors self.source = source self.goal = goal Algorithm.__init__ (self, graph) self.run ()
agenda.sort(cmp=self.compare) return self.path def __hash__ (self): """The hash value for this algorithm is the hash of the graph, source, goal, and cost function. """ return hash ((self.graph, self.source, self.goal, self.costf)) def identity (self): """Identify runs of this algorithm by its hash value.""" return h...
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 'accepting all neighbors'
def filter (order, current={}, prob=1.0): """Generator function used for creating filtered successors of ``u``. """ # If there are no bones left in ``order``, yield the current node if len (order) == 0: yield current.copy () return
spot = (tuple (ppos.mins), tuple (node.mins))
spot = (tuple (ppos.mins), tuple (edge.v.mins))
def filter (order, current={}, prob=1.0): """Generator function used for creating filtered successors of ``u``. """ # If there are no bones left in ``order``, yield the current node if len (order) == 0: yield current.copy () return
if newProb > self.eps:
if newProb > self.epsilon:
def filter (order, current={}, prob=1.0): """Generator function used for creating filtered successors of ``u``. """ # If there are no bones left in ``order``, yield the current node if len (order) == 0: yield current.copy () return
raise KeyError ('(%f, %f) not in bayes net for %s' %
raise KeyError ('(%s, %s) not in bayes net for %s' %
def filter (order, current={}, prob=1.0): """Generator function used for creating filtered successors of ``u``. """ # If there are no bones left in ``order``, yield the current node if len (order) == 0: yield current.copy () return
print "Dataset:" for i in dataset: print "\t%s" % i
def build_fid(dataset, fd): dataset.sort() print "Dataset:" for i in dataset: print "\t%s" % i _fidtool.append_samples(fd, dataset)
dataset = map(int, open("cia-commits.dataset"))[2000:2020] dataset = [x * 5 for x in range(65)]
dataset = map(int, open("cia-commits.dataset"))[:1000]
def test_fid(dataset, fd): query = [int(random.uniform(dataset[0] - 100, dataset[-1] + 200) + 0.5) for i in xrange(1000)] query.sort() while 1: r1 = _fidtool.query_samples(fd, query) r2 = [reference_query(dataset, q) for q in query] if r1 == r2: print "Success" elif len(r1) != len(r2): print "Failure, len(r1)=%d, len(...
return MetadataLink(context['target'], item[0])
return Link.MetadataLink(context['target'], item[0])
def render_data(self, context, item): return MetadataLink(context['target'], item[0])
return tag('img', src=MetadataLink(context['target'], name).getURL(context))
return tag('img', src=Link.MetadataLink(context['target'], name).getURL(context))
def renderData_image(self, context, name, value, mime): """Return an <img> tag linking to the key's value""" return tag('img', src=MetadataLink(context['target'], name).getURL(context))
graph = rtgraph.HScrollLineGraph(range=(0,255))
graph = rtgraph.HScrollLineGraph(range=(0.0, 255.0))
def main(): channels = [AdcChannel(name="Analog channel %d" % i) for i in xrange(8)] graph = rtgraph.HScrollLineGraph(range=(0,255)) win = rtgraph.GraphUIWindow(channels, graph, valueUpdateInterval=500) win.connect("destroy", gtk.mainquit) analogThread = AnalogUpdaterThread(channels) try: gtk.threads_init() gtk.main()...
build_order(asf)
self.build_order(asf)
def __init__(self, graphs, bayes, asf, epsilon=0.3**29): """Create the GraphSearch object with the graphs.""" self.graphs = graphs self.bayes = bayes self.epsilon = epsilon
while pos < len(order):
while pos < len(self.order):
def build_order(self, asf): """Set the build order for the successor function.""" # Build order always starts at the root self.order = ["root"] pos = 0
def combine(bones, items, position=0, current=[], current_probability=1.0):
def combine(self, bones, items, position=0, current=[], current_probability=1.0):
def combine(bones, items, position=0, current=[], current_probability=1.0): """Recusively create combinatoric successors.
def find_node (graph, pos):
def find_node (self, graph, pos):
def find_node (graph, pos): vertex_map = graph.representations[VertexMap] for vertex in vertex_map: if vertex.inside (pos): return vertex
def linear_interp(start, end, pos, length):
def linear_interp(self, start, end, pos, length):
def linear_interp(start, end, pos, length): result = [] for i in range(len(start)): compstart = start[i] compend = end[i]
reply = self.bridge.write(struct.pack(">BH", 2, addrEncode(address)), 32)[1] return reply
reply = self.bridge.write(struct.pack(">BH", 2, addrEncode(address)), 33)[1]
def read(self, address): """Read a 32-byte block from the given (non-coded) address""" reply = self.bridge.write(struct.pack(">BH", 2, addrEncode(address)), 32)[1] return reply
return context['args']
def render_dataTable(self, context): return context['args'] return MyTable(self.data, [ Nouvelle.IndexedColumn('name', 0), Nouvelle.IndexedColumn('absorbency', 1), Nouvelle.IndexedColumn('conductivity', 2), Nouvelle.IndexedColumn('luminance', 3), ], id='widgets')
yield self.graph.edgeClass (Node (u), Node (v))
nodeU = cached.setdefault (repr (u), Node (u)) nodeV = cached.setdefault (repr (v), Node (v) yield self.graph.edgeClass (nodeU, nodeV)
def combine (graphs): """Recursive function for combining the edges in the adjacency lists of all graphs. """ name, adj = graphs[0] for edge in adj: if len(graphs) == 1: u = {name: edge.u} v = {name: edge.v} yield (u, v) continue
yield self.graph.edgeClass (Node (u), node)
nodeU = cached.setdefault (repr(u), Node (u)) yield self.graph.edgeClass (nodeU, node)
def combineV (graphs): """Yield all edges leaving this node including self-loops.""" name, map = graphs[0] for edge in map.query (node[name]): if edge.u == node[name]: if len (graphs) == 1: yield {name: edge.v} continue
yield self.graph.edgeClass (node, Node (v))
nodeV = cached.setdefault (repr(v), Node (v)) yield self.graph.edgeClass (node, nodeV)
def combineV (graphs): """Yield all edges leaving this node including self-loops.""" name, map = graphs[0] for edge in map.query (node[name]): if edge.u == node[name]: if len (graphs) == 1: yield {name: edge.v} continue
l = data.length
l = data.length * 0.1
def importObjects(reader): scene = Blender.Scene.getCurrent() armObj = Blender.Object.New('Armature', reader.name) armData = Blender.Armature.New() bones = {} # import each bone. for now, just position it at the origin for name, data in reader.bones.iteritems(): bone = Blender.Armature.Bone.New(name) bone.setHead(0....
bone.setTail(float(d[0]) * l, float(d[1]) * l, float(d[2]) * l)
bone.setTail(float(d[0]) * l, float(d[2]) * l, float(d[1]) * l)
def importObjects(reader): scene = Blender.Scene.getCurrent() armObj = Blender.Object.New('Armature', reader.name) armData = Blender.Armature.New() bones = {} # import each bone. for now, just position it at the origin for name, data in reader.bones.iteritems(): bone = Blender.Armature.Bone.New(name) bone.setHead(0....
serverTuple = server.split(":")
serverParts = server.split(":") serverTuple = serverParts[0], int(serverParts[1])
def parseIrcRulesetAttribs(self, element): """Given an ircRuleset or queryIrcRulesets element, returns a (serverTuple, channel) representing the server and channel it refers to. Either may be None if it was not included in the element. """ channel = element.getAttribute('channel') if channel and channel[0] != '#': chan...
oldRuleset = self.rulesets[(server, channel)]
oldRuleset = self.rulesets[tuple(server), channel]
def setIrcRuleset(self, message): """Handle messages instructing us to add, modify, or remove the IRCRuleset instance for a particular channel. These messages are of the form:
total_frames = 0 for amc in amcs: total_frames += len(amc.bones['root'])
def load(asf, files): amcs = [] nets = {} for filename in files: print 'loading %s' % filename amcs.append(AMC.from_file(filename)) relationships = {} for rel in asf.hierarchy: parent = rel[0] children = rel[1:] if len(parent): relationships[parent] = children for child in children: if child in amcs[0].bones: nets[ch...
newnet[pose] = float(count) / float(total_frames) newnets[bone] = newnet
ppose = pose[0] cpose = pose[1] if ppose not in parents: parents[ppose] = {} parents[ppose][cpose] = count newnets[bone] = parents
def load(asf, files): amcs = [] nets = {} for filename in files: print 'loading %s' % filename amcs.append(AMC.from_file(filename)) relationships = {} for rel in asf.hierarchy: parent = rel[0] children = rel[1:] if len(parent): relationships[parent] = children for child in children: if child in amcs[0].bones: nets[ch...
return newnets
del nets nets = {} for bone, parents in newnets.iteritems(): for parent, children in parents.iteritems(): total = 0 for count in children.itervalues(): total += count for child, count in children.iteritems(): nets[(parent, child)] = float(count) / float(total) return nets
def load(asf, files): amcs = [] nets = {} for filename in files: print 'loading %s' % filename amcs.append(AMC.from_file(filename)) relationships = {} for rel in asf.hierarchy: parent = rel[0] children = rel[1:] if len(parent): relationships[parent] = children for child in children: if child in amcs[0].bones: nets[ch...
self.dock = Icon.Dock(overlay, self.trackFunction, [icon] * 10)
self.dock = Icon.Dock(overlay, self.trackFunction, [icon] * 2)
def __init__(self, book): Sequencer.Page.__init__(self, book)
theta = -x * 2*pi - pi/2
theta = -x * 2*pi + pi/2
def trackFunction(self, x): """An example track function that moves the icons along a circle in the middle of the screen. The bottom of the circle is at 0, increasing parameters move clockwise. The icon at 0 is the largest. """ radius = self.viewport.size[1] * 0.04 theta = -x * 2*pi - pi/2 size = pow(sin(theta)*0.5+0.5...
traj = self.ode (ic, t)
self.t = t
def __init__ (self, system, ic, t, data): """Each Sequence object requires an ordinary differential equation solver and some motion capture data (data). """ self.mapping = {} self.ode = RK4 (system)
traj = self.ode (ic, Time (start, iterations, step))
self.t = Time (start, iterations, step) traj = self.ode (ic, self.t)
def __init__ (self, system, ic, t, data): """Each Sequence object requires an ordinary differential equation solver and some motion capture data (data). """ self.mapping = {} self.ode = RK4 (system)
def shuffle (self, ics):
def shuffle (self, ics, time=None):
def shuffle (self, ics): """ Takes a set of initial conditions (ics) and returns a new dance sequence. """ shuffled = [] traj = self.ode (ics) step = len (traj) / len (self.mapping.keys ()) length = len (traj) * step
traj = self.ode (ics)
traj = self.ode (ics, time or self.t)
def shuffle (self, ics): """ Takes a set of initial conditions (ics) and returns a new dance sequence. """ shuffled = [] traj = self.ode (ics) step = len (traj) / len (self.mapping.keys ()) length = len (traj) * step
shuffled.append (self._findNearest (traj[i * step]))
shuffled.append (self._findNearest (traj[i]))
def shuffle (self, ics): """ Takes a set of initial conditions (ics) and returns a new dance sequence. """ shuffled = [] traj = self.ode (ics) step = len (traj) / len (self.mapping.keys ()) length = len (traj) * step
def read(self, repeats=1):
def readChannel(self, channel): """Read one ADC channel, return a value in the range [0,1]""" self.pic.ADCON0 = 0x81 | (channel << 3) self.pic.ADCON0 = 0x85 | (channel << 3) return self.pic.ADRES / 255.0 def readAll(self, repeats=1, channels=xrange(8)):
def read(self, repeats=1): """Read all ADC channels, return a list of floats. In order to provide more stable readings with high impedance inputs, this can optionally repeat each channel's reading several times to let the ADC's holding capacitor charge over a longer period of time. """ results = [0] * 8 for channel in ...
results = [0] * 8
results = []
def read(self, repeats=1): """Read all ADC channels, return a list of floats. In order to provide more stable readings with high impedance inputs, this can optionally repeat each channel's reading several times to let the ADC's holding capacitor charge over a longer period of time. """ results = [0] * 8 for channel in ...
self.pic.ADCON0 = 0x85 | (channel << 3) results[channel] = self.pic.ADRES / 255.0
v = self.readChannel(channel) results.append(v)
def read(self, repeats=1): """Read all ADC channels, return a list of floats. In order to provide more stable readings with high impedance inputs, this can optionally repeat each channel's reading several times to let the ADC's holding capacitor charge over a longer period of time. """ results = [0] * 8 for channel in ...
self.drawChannels(sampler.read())
self.drawChannels(sampler.readAll())
def run(self, sampler): """Run until our window is closed, drawing data from the given sampler""" while 1: for event in pygame.event.get(): if event.type == QUIT: return self.drawChannels(sampler.read()) pygame.display.flip()
adjacency = graph.representations[AdjacencyList]
def f (path, goal): """Calculate the f-cost of a path""" # cost of current path g = len (path) h = 0 # cost to goal h = len (algorithms_c.dijkstraSearch (adjacency, path[-1], goal)) return g + h
[edge for edge in adjacency.query (actualPath[bone][-1])]).v)
[edge for edge in adjacency.query (actualPath[-1][bone])]).v)
def f (path, goal): """Calculate the f-cost of a path""" # cost of current path g = len (path) h = 0 # cost to goal h = len (algorithms_c.dijkstraSearch (adjacency, path[-1], goal)) return g + h
return context['table'].reduceColumn(TargetCounterColumn(None, 'forever'), max) > 0
return context['table'].reduceColumn(self.visibilityColumn, max) > 0
def isVisible(self, context): # Hide this column if none of the targets have had any messages return context['table'].reduceColumn(TargetCounterColumn(None, 'forever'), max) > 0
(1, 60*60*24*2 / stepSize), (7, 60*60*24*2 / stepSize / 7), (31, 60*60*24*2 / stepSize / 31), (365, 60*60*24*2 / stepSize / 365),
(1, nSamples), (7, nSamples), (31, nSamples), (365, nSamples),
def rrdInit(self): """Create a blank RRD for this therm""" stepSize = 60
def xmlrpc_rebuild(self, key=None):
def xmlrpc_rebuild(self, key):
def xmlrpc_rebuild(self, key=None): """Use twisted.python.rebuild to reload all applicable modules""" self.caps.faultIfMissing(key, 'universe', 'sys', 'sys.rebuild') import LibCIA rebuildPackage(LibCIA) return True
print bones
for key,val in bones.iteritems (): print key, val
def randomWalk (graph, len): """Find a path in graph of langth len by following a random edge.""" adjacency = graph.representations[AdjacencyList] edgeList = graph.representations[EdgeList]
formattedModule = self.format_module(XML.shallowText(module).strip())
formattedModule = self.format_module(module)
def format_moduleAndFiles(self, message): """Format the module name and files, joined together if they are both present.""" files = XML.dig(message.xml, "message", "body", "commit", "files") if files: formattedFiles = self.format_files(files) else: formattedFiles = ""
if msg.find(self.factory.nickname) is not -1:
if msg.find(self.factory.nickname) is not -1 and nick != self.factory.nickname:
def messageReceive(self, user, channel, msg): ''' This handles the formatting of regular conversation. Gets the nick of the person who said it, encloses it in <>, if timestamps are visible it grabs
gotPassword, host, port).addErrback( connectionError, host, port, usn)
gotPassword, host, port, usn).addErrback( result.errback)
def foundService((usn, (host, port))): keychain.lookup(usn).addCallback( gotPassword, host, port).addErrback( connectionError, host, port, usn)