rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if not self.registryValue('bugSnarfer', msg.args[0]): | if msg.args[0][0] == ' | def turlSnarfer(self, irc, msg, match): "(?P<tracker>https?://.*?)(show_bug.cgi\?id=|bugreport.cgi\?bug=|(bugs|\+bug)/|/ticket/|tracker/.*aid=)(?P<bug>\d+)(?P<sfurl>&group_id=\d+&at_id=\d+)?" if not self.registryValue('bugSnarfer', msg.args[0]): return try: tracker = self.get_tracker(match.group(0),match.group('sfurl')... |
severities = ['Wishlist', 'Minor', 'Normal', 'Major', 'Critical'] | severities = ['Untriaged', 'Wishlist', 'Minor', 'Low', 'Normal', 'Medium', 'Major', 'High', 'Critical'] | def _sort(self, task1, task2): # Status sort: try: statuses = ['Rejected', 'Fix Committed', 'Fix Released', 'Confirmed', 'In Progress', 'Needs Info', 'Unconfirmed'] severities = ['Wishlist', 'Minor', 'Normal', 'Major', 'Critical'] if task1['status'] not in statuses and task2['status'] in statuses: return 1 if task1['... |
if task1['severity'] not in severities and task2['severity'] in severities: return 1 if task1['severity'] in severities and task2['severity'] not in severities: return -1 | if task1['importance'] not in severities and task2['importance'] in severities: return 1 if task1['importance'] in severities and task2['importance'] not in severities: return -1 | def _sort(self, task1, task2): # Status sort: try: statuses = ['Rejected', 'Fix Committed', 'Fix Released', 'Confirmed', 'In Progress', 'Needs Info', 'Unconfirmed'] severities = ['Wishlist', 'Minor', 'Normal', 'Major', 'Critical'] if task1['status'] not in statuses and task2['status'] in statuses: return 1 if task1['... |
if not (task1['severity'] == task2['severity']): if severities.index(task1['severity']) < severities.index(task2['severity']): | if not (task1['importance'] == task2['importance']): if severities.index(task1['importance']) < severities.index(task2['importance']): | def _sort(self, task1, task2): # Status sort: try: statuses = ['Rejected', 'Fix Committed', 'Fix Released', 'Confirmed', 'In Progress', 'Needs Info', 'Unconfirmed'] severities = ['Wishlist', 'Minor', 'Normal', 'Major', 'Critical'] if task1['status'] not in statuses and task2['status'] in statuses: return 1 if task1['... |
irc.reply("https://chinstrap.ubuntu.com/~jamesh/oops.cgi/%s" % oopsid, prefixNick=False) | irc.reply("https://devpad.canonical.com/~jamesh/oops.cgi/%s" % oopsid, prefixNick=False) | def oopsSnarfer(self, irc, msg, match): r"OOPS-(?P<oopsid>\d*[A-Z]\d+)" oopsid = match.group(1) irc.reply("https://chinstrap.ubuntu.com/~jamesh/oops.cgi/%s" % oopsid, prefixNick=False) |
raise | def reportnewbugs(self,irc): # Compile list of bugs print "Reporting new bugs" tracker = self.db['malone'] bugs = {} fixed = {} for c in irc.state.channels: dir = self.registryValue('bugReporter', channel=c) if not dir: continue print "Reporting in %s (%s)" % (c, dir) if dir not in bugs: print "Reloading info from %s" ... | |
- labeleduri -- unicode string to convert | - ustr -- unicode string to convert | def camelcase(ustr, maxlen=None): """Convert a unicode string into CamelCase. When maxlen is not None, each word is truncated to the length maxlen. Arguments ========= - labeleduri -- unicode string to convert - maxlen -- maximum length of each word (default: None) Examples ======== >>> camelcase(u"Abc") u'Abc' >>... |
self.__class__.__counter += 1 self.__key = self.__class__.__counter | OrderedByCreation.__counter += 1 self.__key = OrderedByCreation.__counter | def __init__(self, *args, **kwargs): """Create a new OrderedByCreation object.""" super(OrderedByCreation, self).__init__(*args, **kwargs) self.__class__.__counter += 1 self.__key = self.__class__.__counter |
_exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers[-1] apply(func, targs, kargs) _exithandlers.remove(_exithandlers[-1]) | _exithandlers = atexit._exithandlers atexit._exithandlers = [] | def _run_exitfuncs(): """run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers[-1] apply(func, targs, kargs) _exithandlers.remove(_exithandlers[-1]) |
def register(func, *targs, **kargs): """register a function to be executed upon normal program termination | atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") | def register(func, *targs, **kargs): """register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs)) |
func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs)) | atexit._run_exitfuncs() | def register(func, *targs, **kargs): """register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs)) |
import sys try: x = sys.exitfunc except AttributeError: sys.exitfunc = _run_exitfuncs else: if x != _run_exitfuncs: register(x) del sys if __name__ == "__main__": def x1(): print "running x1" def x2(n): print "running x2(%s)" % `n` def x3(n, kwd=None): print "running x3(%s, kwd=%s)" % (`n`, `kwd`) register(x1) regi... | atexit._exithandlers = _exithandlers | def register(func, *targs, **kargs): """register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs)) |
def passtothink(list): target = AE.AECreateDesc(typeApplSignature, 'KAHL') event = AE.AECreateAppleEvent(kCoreEventClass, kAEOpenDocuments, target, kAutoGenerateReturnID, kAnyTransactionID) aetools.packevent(event, {keyDirectObject: list}) reply = event.AESend(kAENoReply | kAEAlwaysInteract | kAECanSwitchLayer, kAENorm... | main() | def passtothink(list): target = AE.AECreateDesc(typeApplSignature, 'KAHL') event = AE.AECreateAppleEvent(kCoreEventClass, kAEOpenDocuments, target, kAutoGenerateReturnID, kAnyTransactionID) aetools.packevent(event, {keyDirectObject: list}) reply = event.AESend(kAENoReply | kAEAlwaysInteract | kAECanSwitchLayer, kAENorm... |
if result is None: | if (result is None) and isinstance(index, str): | def __getitem__(self, index): result = self.atoms_by_number.get(index) if result is None: return self.atoms_by_symbol.get(index.lower()) else: return result |
ATOMARY = measure_counter() | ATOMARY = unit_counter() | def __call__(self): self.counter += 1 return self.counter |
reference = MolecularDescriptorsTV1(coordinates, masses) | reference = MolecularDescriptorTV1(coordinates, masses) | def do_test(self, coordinates, masses, expected_is): reference = MolecularDescriptorsTV1(coordinates, masses) self.assert_(reference.inversion_symmetric == expected_is) |
new_descriptor = MolecularDescriptorsTV1(new_coordinates, masses) | new_descriptor = MolecularDescriptorTV1(new_coordinates, masses) | def do_test(self, coordinates, masses, expected_is): reference = MolecularDescriptorsTV1(coordinates, masses) self.assert_(reference.inversion_symmetric == expected_is) |
self.memory = None | self.memory = memory | def __init__(self, filename, title, input_molecule, memory=None): self.filename = filename self.title = title self.input_molecule = input_molecule self.memory = None self.ran = False self.summary = {} |
print result = self.file_parser_groups.values() for file_parser_group in result: print file_parser_group.filename print "---------" | def sort_groups(self): for file_parser_group in self.file_parser_groups.itervalues(): file_parser_group.depends_on = [] file_parser_group.works_for = [] for file_parser_group in self.file_parser_groups.itervalues(): for file_parser in file_parser_group.items: for dependency in file_parser.depends_on: file_parser_group... | |
for file_parser_group in result: print file_parser_group.filename print "=========" | def sort_groups(self): for file_parser_group in self.file_parser_groups.itervalues(): file_parser_group.depends_on = [] file_parser_group.works_for = [] for file_parser_group in self.file_parser_groups.itervalues(): for file_parser in file_parser_group.items: for dependency in file_parser.depends_on: file_parser_group... | |
self.particular = Numeric.dot(self.W[:,:self.rank], Numeric.transpose(Numeric.transpose(Numeric.dot(self.gradient, self.V))/self.S)) | self.particular = Numeric.dot(particular_transform, self.gradient) self.gradient_error = Numeric.ones(self.gradient.shape, Numeric.Float)*job.gradient_accuracy self.particular_error = Numeric.sqrt(Numeric.dot(particular_transform**2, self.gradient_error**2)) | def __init__(self, internal_coordinates, molecule, job): JacobianAnalysis.__init__(self, internal_coordinates, molecule) self.job = job self.energy = job.energy |
self.particular -= Numeric.dot(self.nullspace, Numeric.dot(self.particular, self.nullspace)) | def __init__(self, internal_coordinates, molecule, job): JacobianAnalysis.__init__(self, internal_coordinates, molecule) self.job = job self.energy = job.energy | |
def add_bend_spans(self, criteria_sets): | def add_bending_spans(self, criteria_sets): | def add_bend_spans(self, criteria_sets): """ Adds the distances that span the bend angles described in criteria_sets to the collection. """ match_generator = MatchGenerator(BendingAngleMatchDefinition(criteria_sets)) for match in match_generator(self.molecular_graph): id = tuple([match.get_destination(source) for sourc... |
self.internal_coordinates.append(similar.internal_coordinates) | self.internal_coordinates.extend(similar.internal_coordinates) | def __init__(self, items): self.items = items self.dict_items = dict((item.name, item) for item in items) counter = 0 self.internal_coordinates = [] for similar in self.items: self.internal_coordinates.append(similar.internal_coordinates) similar.indices = [] for internal_coordinate in similar.internal_coordinates: int... |
assert sum(len(similar.internal_coordinates) for similar in similars) >= num_atoms*3-6, "Specify more internal coordinates" | def __init__(self, internal_coordinates, num_atoms): self.internal_coordinates = internal_coordinates # internal coordinates mask: This masks out the non-independant # carthesian coordinates in the center of mass frame. It is assumed # that the molecule is transformed into it's normalized frame. # (see ffaudit.molecule... | |
print self.W[:,:self.rank].shape, Numeric.transpose(self.V/self.S).shape | def __init__(self, internal_coordinates, molecule, job): JacobianAnalysis.__init__(self, internal_coordinates, molecule) self.job = job self.energy = job.energy self.energy_error = job.energy_accuracy | |
print >> stream | def write_xyz_to_stream(self, stream): print >> stream, "%5i" % len(self.numbers) print >> stream self.write_atoms_to_stream(stream) print >> stream | |
delta = numpy.dot(unit_cell.cell, [index_a, index_b, index_c]) for result in self.call_delta(numpy.dot(unit_cell.cell, delta)): | delta = numpy.dot(unit_cell.cell, numpy.array([index_a, index_b, index_c])) for result in self.call_delta(delta): | def __call__(self, unit_cell=None): if unit_cell is None: for result in self.call_delta(numpy.zeros(3, float)): yield result else: active_a, active_b, active_c = unit_cell.cell_active.astype(int) for index_a in xrange(-active_a, active_a+1): for index_b in xrange(-active_b, active_b+1): for index_c in xrange(-active_c,... |
self.re = re.compile(r"\d+\s+\S+\s+(?P<x>\S+)\s+(?P<y>\S+)\s+(?P<z>\S+)\s+(?P<gx>\S+)\s+(?P<gy>\S+)\s+(?P<gz>\S+)") | self.re = re.compile(r"\d+\s+\S+(?P<x>.{8})(?P<y>.{8})(?P<z>.{8}) (?P<gx>.{11})(?P<gy>.{11})(?P<gz>.{11})") | def __init__(self, num_steps_parser, num_every_parser, elements_parser, label='coor_grad', condition=None): EveryParserMixin.__init__(self, num_steps_parser, num_every_parser) MultiLineParser.__init__( self, label, re.compile(r"ATOM\s+COORDINATES\s+GRADIENTS"), re.compile(r"^$"), condition, [num_steps_parser, num_every... |
keyval = create_single_point_kv( | keyval = create_single_point( | def validate(): energy = job.molecular_energies[-1] gradient = job.gradients[-1] self.assert_(job.completed) self.assert_(isinstance(job.gradient_accuracy, float)) self.assert_(isinstance(job.energy_accuracy, float)) self.assertAlmostEqual(energy, -75.9734488121, 8) self.assertAlmostEqual(gradient[0,0], 0.01174361, 6)... |
keyval['mpqc']['do_gradient'] = 'yes' | keyval.mpqc.do_gradient = 'yes' | def validate(): energy = job.molecular_energies[-1] gradient = job.gradients[-1] self.assert_(job.completed) self.assert_(isinstance(job.gradient_accuracy, float)) self.assert_(isinstance(job.energy_accuracy, float)) self.assertAlmostEqual(energy, -75.9734488121, 8) self.assertAlmostEqual(gradient[0,0], 0.01174361, 6)... |
keyval = create_optimize_kv( | keyval = create_optimize( | def validate(): #self.assert_(job.completed) self.assertAlmostEqual(job.energies[-1], -75.973963163199997, 8) coordinates = job.output_molecules[-1].coordinates delta = coordinates[0]-coordinates[1] self.assertAlmostEqual(math.sqrt(numpy.dot(delta, delta)), 1.88335259871, 3) delta = coordinates[0]-coordinates[2] self.a... |
keyval['mpqc']['freq'] = KeyValObject('MolecularFrequencies', named_items=[ ('molecule', keyval['molecule']) | keyval.mpqc.freq = KeyValObject('MolecularFrequencies', [ ('molecule', keyval.molecule) | def validate(): #self.assert_(job.completed) self.assertAlmostEqual(job.energies[-1], -75.973963163199997, 8) coordinates = job.output_molecules[-1].coordinates delta = coordinates[0]-coordinates[1] self.assertAlmostEqual(math.sqrt(numpy.dot(delta, delta)), 1.88335259871, 3) delta = coordinates[0]-coordinates[2] self.a... |
class MpqcRawGridInterface(unittest.TestCase): def test_grid(self): output_parser = OutputParser([ RawGridParser(), ]) result = output_parser.parse("input", "mpqc_raw.grid") | def validate(): #self.assert_(job.completed) self.assertAlmostEqual(job.energies[-1], -75.973963163199997, 8) coordinates = job.output_molecules[-1].coordinates delta = coordinates[0]-coordinates[1] self.assertAlmostEqual(math.sqrt(numpy.dot(delta, delta)), 1.88335259871, 3) delta = coordinates[0]-coordinates[2] self.a... | |
if isfile(path): | if os.path.isfile(path): | def parse(self, prefix): sorted_groups = self.sort_groups() directory = os.path.dirname(prefix) basename = os.path.basename(prefix) result = {} for file_parser_group in sorted_groups: for file_parser in file_parser_group.items: file_parser.reset() if file_parser_group.extension: path = "%s/%s%s" % (directory, basenam... |
print descriptor.label | def static_fields(ordered_descriptors, parameters, internal, label, format): adresses = {} begin = 0 for descriptor in ordered_descriptors: if descriptor.internal == internal: end = begin + reduce(lambda x,y: x*y, descriptor.shape(parameters), 1) adresses[descriptor.label] = (begin, end) end = begin size = end labels ... | |
filename = "" extension = True def __init__(self, label='grid', condition=None): FileParser.__init__(self, label, condition) def reset(self): self.grid = None self.counter = 0 def parse(self, line): if self.grid is None: if line[:21] == " num = int(line[21:]) self.grid = numpy.zeros((num, 4), float) else: | filename = ".out" extension = True def __init__(self, label='grid', trigger=None, condition=None): self.trigger = trigger FileParser.__init__(self, label, condition) def reset(self): self.grid = [] self.active = (self.trigger == None) def parse(self, line): if self.active: | def result(self): if self.num_atoms != None: result = numpy.zeros((self.num_atoms*3, self.num_atoms*3), float) counter = 0 for i in xrange(self.num_atoms*3): for j in xrange(0, i): result[i,j] = self.hessian_elements[counter] result[j,i] = self.hessian_elements[counter] counter += 1 result[i,i] = self.hessian_elements[... |
self.grid[self.counter, 0] = float(words[0]) self.grid[self.counter, 1] = float(words[1]) self.grid[self.counter, 2] = float(words[2]) self.grid[self.counter, 3] = float(words[3]) self.counter += 1 def result(self): return self.grid | if len(words) == 4: try: self.grid.append([ float(words[0]), float(words[1]), float(words[2]), float(words[3]) ]) except ValueError: self.active = False else: self.active = False elif len(self.grid) == 0: if line == self.trigger: self.active = True def result(self): return numpy.array(self.grid, float) | def parse(self, line): if self.grid is None: if line[:21] == "# Number of records: ": num = int(line[21:]) self.grid = numpy.zeros((num, 4), float) else: words = line.split() self.grid[self.counter, 0] = float(words[0]) self.grid[self.counter, 1] = float(words[1]) self.grid[self.counter, 2] = float(words[2]) self.grid[... |
name="long range distance %i-%i (%s)" % (id + (tag,)), | name="long range distance %i-%i" % id, | def distance(id, tag): s0 = self.add(Select, id[0]) s1 = self.add(Select, id[1]) e = self.add(Delta, s1, s0) d = self.add( Distance, e, name="long range distance %i-%i (%s)" % (id + (tag,)), id=id ) return d |
name="bond length %i-%i (%s)" % (id + (tag,)), | name="bond length %i-%i" % id, | def add_bond_lengths(self, criteria_sets): """ Adds the bond lengths described in criteria_sets to the collection. Arguments criteria_sets -- see pychem.molecular_graphs """ result = dict((tag, []) for tag in criteria_sets.yield_tags()) for tag, match in self.molecular_graph.yield_subgraphs(criteria_sets): id = tuple(... |
name="bend cos %i-%i-%i (%s)" % (id + (tag,)), | name="bend cos %i-%i-%i" % id, | def add_bend_cosines(self, criteria_sets): """ Adds the cosines of the bend angles described in criteria_sets to the collection. """ result = dict((tag, []) for tag in criteria_sets.yield_tags()) for tag, match in self.molecular_graph.yield_subgraphs(criteria_sets): id = tuple([match.get_destination(source) for source ... |
name="bend span %i-%i-%i (%s)" % (id + (tag,)), | name="bend span %i-%i-%i" % id, | def add_bend_spans(self, criteria_sets): """ Adds the distances that span the bend angles described in criteria_sets to the collection. """ result = dict((tag, []) for tag in criteria_sets.yield_tags()) for tag, match in self.molecular_graph.yield_subgraphs(criteria_sets): id = tuple([match.get_destination(source) for ... |
name="dihedral cos %i-%i-%i-%i (%s)" % (id + (tag,)), | name="dihedral cos %i-%i-%i-%i" % id, | def add_dihedral_cosines(self, criteria_sets): """ Adds the dihedral angles described in criteria_sets to the collection. """ result = dict((tag, []) for tag in criteria_sets.yield_tags()) for tag, match in self.molecular_graph.yield_subgraphs(criteria_sets): id = tuple([match.get_destination(source) for source in [0, ... |
name="dihedral span %i-%i-%i-%i (%s)" % (id + (tag,)), | name="dihedral span %i-%i-%i-%i" % id, | def add_dihedral_spans(self, criteria_sets): """ Adds the distances that span the dihedral angles described in criteria_sets to the collection. """ result = dict((tag, []) for tag in criteria_sets.yield_tags()) for tag, match in self.molecular_graph.yield_subgraphs(criteria_sets): id = tuple([match.get_destination(sour... |
name="out of plane cos %i-%i (%i,%i) (%s)" % (id + (tag,)), | name="out of plane cos %i-%i (%i,%i)" % id, | def add_out_of_plane_cosines(self, criteria_sets): """ Adds the out of plane cosines described in criteria_sets to the collection. """ result = dict((tag, []) for tag in criteria_sets.yield_tags()) for tag, match in self.molecular_graph.yield_subgraphs(criteria_sets): id = tuple([match.get_destination(source) for sourc... |
name="%s x %s (%s)" % (ic1.name, ic2.name, tag) | name="%s x %s" % (ic1.name, ic2.name) | def add_related_products(self, tag, tag1, tag2, order_related=2): result = [] for ic1, ic2 in self.yield_related_internal_coordinates(tag1, tag2, order_related): product = self.add( Mul, ic1, ic2, name="%s x %s (%s)" % (ic1.name, ic2.name, tag) ) self.add_internal_coordinate(tag, product) |
class OneToOne(unittest.TestCase): | class GraphHelpers(unittest.TestCase): | def message(): return ("-- Graphs %s ---\n" % name) + \ ("common (%i): %s\n" % (len(common), common)) + \ ("unexpected (%i): %s\n" % (len(unexpected), unexpected)) + \ ("unsatisfied (%i): %s\n" % (len(unsatisfied), unsatisfied)) |
value, tangent = internal_coordinate(configuration.carthesian_values) | value, tangent = internal_coordinate.value_tangent(configuration.carthesian_values) | def jacobian_analysis(configuration, internal_coordinates): configuration.internal_coordinates = internal_coordinates jacobian = [] values = [] for internal_coordinate in internal_coordinates: value, tangent = internal_coordinate(configuration.carthesian_values) values.append(value) jacobian.append(Numeric.ravel(tange... |
self.re = re.compile("Atom\s+\d+\s+has atomic number\s+\d+\s+and mass\s+(?P<mass>\S+)") | self.re = re.compile("Atom\s*\d+\s+has atomic number\s+\d+\s+and mass\s+(?P<mass>\S+)") | def __init__(self, label="masses", condition=None): ThermoChemParser.__init__(self, label, activator=re.compile("Temperature\s+\S+\s+Kelvin.\s+Pressure\s+\S+\s+Atm."), deactivator=re.compile("Molecular mass:\s+\S+\s+amu."), condition=condition ) self.re = re.compile("Atom\s+\d+\s+has atomic number\s+\d+\s+and mass\s+(?... |
re.compile("Standard orientation:"), re.compile("Distance matrix \(angstroms\):"), | re.compile("Standard orientation"), re.compile("Rotational constants"), | def __init__(self, label="so_coordinates_list", condition=None): CoordinatesParser.__init__(self, label, re.compile("Standard orientation:"), re.compile("Distance matrix \(angstroms\):"), condition ) |
re.compile("Input orientation:"), re.compile("Distance matrix \(angstroms\):"), | re.compile("Input orientation"), re.compile("Standard orientation"), | def __init__(self, label="io_coordinates_list", condition=None): CoordinatesParser.__init__(self, label, re.compile("Input orientation:"), re.compile("Distance matrix \(angstroms\):"), condition ) |
float(match.group("x")), float(match.group("y")), float(match.group("z")) | from_angstrom(float(match.group("x"))), from_angstrom(float(match.group("y"))), from_angstrom(float(match.group("z"))) | def collect(self, line): match = self.re.search(line) if match != None: self.current_coordinates.append([ float(match.group("x")), float(match.group("y")), float(match.group("z")) ]) |
print self.fields.keys() | def analyze(self): print self.fields.keys() self.molecule = Molecule() self.molecule.numbers = self.fields["Atomic numbers"] self.molecule.coordinates = numpy.reshape(self.fields["Current cartesian coordinates"], (-1,3)) | |
(-1, 1, 1), (-1, 1, 0), (-1, 1, 1), | (-1, 1, -1), (-1, 1, 0), (-1, 1, 1), | def __init__(self, binned_objects1, binned_objects2, compare_function): AnalyseNeighboringObjects.__init__(self, compare_function) assert binned_objects1.gridsize==binned_objects2.gridsize self.compare_indices = numpy.array([ (-1, -1, -1), (-1, -1, 0), (-1, -1, 1), (-1, 0, -1), (-1, 0, 0), (-1, 0, 1), (-1, 1, ... |
( 0, 1, 1), ( 0, 1, 0), ( 0, 1, 1), | ( 0, 1, -1), ( 0, 1, 0), ( 0, 1, 1), | def __init__(self, binned_objects1, binned_objects2, compare_function): AnalyseNeighboringObjects.__init__(self, compare_function) assert binned_objects1.gridsize==binned_objects2.gridsize self.compare_indices = numpy.array([ (-1, -1, -1), (-1, -1, 0), (-1, -1, 1), (-1, 0, -1), (-1, 0, 0), (-1, 0, 1), (-1, 1, ... |
( 1, 1, 1), ( 1, 1, 0), ( 1, 1, 1), | ( 1, 1, -1), ( 1, 1, 0), ( 1, 1, 1), | def __init__(self, binned_objects1, binned_objects2, compare_function): AnalyseNeighboringObjects.__init__(self, compare_function) assert binned_objects1.gridsize==binned_objects2.gridsize self.compare_indices = numpy.array([ (-1, -1, -1), (-1, -1, 0), (-1, -1, 1), (-1, 0, -1), (-1, 0, 0), (-1, 0, 1), (-1, 1, ... |
self.init_trajectory_vars(["states", "potential_energies"]) | self.init_trajectory_vars(["states", "potential_energies", "gradients"]) | def __init__(self, calculate_energy, calculate_gradient, dof, log): self.initialized = False |
def make_arrays(self): for var in self.trajectory_vars: self.__dict__[var] = numpy.array(self.__dict__[var], float) | def make_arrays(self): for var in self.trajectory_vars: self.__dict__[var] = numpy.array(self.__dict__[var], float) | |
pickle.dump(dict((var, self.__dict__[var]) for var in self.trajectory_vars), f) | pickle.dump(dict((var, numpy.array(self.__dict__[var])) for var in self.trajectory_vars), f) | def dump_trajectory(self, filename): f = file(filename, "w") pickle.dump(dict((var, self.__dict__[var]) for var in self.trajectory_vars), f) f.close() |
def __init__(self, calculate_energy, calculate_gradient, log, masses, time_step): | def __init__(self, calculate_energy, calculate_gradient, log, masses, time_step, fixes=[]): | def __init__(self, calculate_energy, calculate_gradient, log, masses, time_step): TrajectoryMaker.__init__(self, calculate_energy, calculate_gradient, len(masses), log) |
self.velocities = [] self.energies = [] self.kinetic_energies = [] self.times = [] self.temperatures = [] | def __init__(self, calculate_energy, calculate_gradient, log, masses, time_step): TrajectoryMaker.__init__(self, calculate_energy, calculate_gradient, len(masses), log) | |
self.current_velocities[:] = initial_velocities[:] self.accelerations[:] = -self.calculate_gradient(self.current_state)/self.masses | self.current_velocities[:] = initial_velocities self.gradient[:] = self.calculate_gradient(self.current_state) self.accelerations[:] = -self.gradient/self.masses | def initialize_state(self, initial_state, initial_velocities=0): self.current_state[:] = initial_state self.current_velocities[:] = initial_velocities[:] self.accelerations[:] = -self.calculate_gradient(self.current_state)/self.masses self.tmp[:] = self.current_velocities + 0.5*self.accelerations*self.time_step self.cl... |
self.clear_trajectory_vars() | def initialize_state(self, initial_state, initial_velocities=0): self.current_state[:] = initial_state self.current_velocities[:] = initial_velocities[:] self.accelerations[:] = -self.calculate_gradient(self.current_state)/self.masses self.tmp[:] = self.current_velocities + 0.5*self.accelerations*self.time_step self.cl... | |
for step in xrange(steps): self.current_state[:] += self.tmp*self.time_step self.accelerations[:] = -self.calculate_gradient(self.current_state)/self.masses self.current_velocities[:] = self.tmp + 0.5*self.accelerations[:]*self.time_step self.tmp[:] = self.current_velocities + 0.5*self.accelerations[:]*self.time_step ... | try: for step in xrange(steps): self.current_state[:] += self.tmp*self.time_step self.gradient[:] = self.calculate_gradient(self.current_state) self.accelerations[:] = -self.gradient/self.masses self.current_velocities[:] = self.tmp + 0.5*self.accelerations[:]*self.time_step self.tmp[:] = self.current_velocities + 0.5*... | def run(self, steps): TrajectoryMaker.run(self) for step in xrange(steps): self.current_state[:] += self.tmp*self.time_step self.accelerations[:] = -self.calculate_gradient(self.current_state)/self.masses self.current_velocities[:] = self.tmp + 0.5*self.accelerations[:]*self.time_step self.tmp[:] = self.current_velocit... |
self.clear_trajectory_vars() | self.states.append(initial_state) | def initialize_state(self, initial_state): self.current_state[:] = initial_state self.clear_trajectory_vars() self.initialized = True |
for step in xrange(steps): state_delta = self.current_state + self.epsilon*direction/gradient_norm gradient_delta = self.calculate_gradient(state_delta) hessian_applied = (gradient_delta - gradient)/self.epsilon second_order_deriv_in_direction = numpy.dot(hessian_applied, direction) if second_order_deriv_in_direction >... | try: for step in xrange(steps): state_delta = self.current_state + self.epsilon*direction/gradient_norm gradient_delta = self.calculate_gradient(state_delta) hessian_applied = (gradient_delta - gradient)/self.epsilon second_order_deriv_in_direction = numpy.dot(hessian_applied, direction) if second_order_deriv_in_direct... | def run(self, steps, gradient_norm_threshold): TrajectoryMaker.run(self) gradient = self.calculate_gradient(self.current_state) direction = -gradient.copy() gradient_norm = numpy.sqrt(numpy.dot(gradient, gradient)) for step in xrange(steps): state_delta = self.current_state + self.epsilon*direction/gradient_norm gradie... |
filename = job.filename job = reload_job(filename + ".job") | prefix = job.prefix job = reload_job(prefix + ".job") | def validate(): self.assert_(job.completed) self.assertAlmostEqual(job.energy, -75.9734488121, 8) self.assertAlmostEqual(job.gradient[0,0], 0.01174361, 6) self.assertAlmostEqual(job.gradient[0,1], 0.0, 6) self.assertAlmostEqual(job.gradient[0,2], 0.0, 6) self.assertAlmostEqual(job.gradient[1,0], -0.005... |
filename = job.filename job = reload_job(filename + ".job") | prefix = job.prefix job = reload_job(prefix + ".job") | def validate(): self.assert_(job.completed) self.assertAlmostEqual(job.energies[-1], -75.973963163199997, 8) coordinates = job.output_molecule.coordinates delta = coordinates[0]-coordinates[1] self.assertAlmostEqual(math.sqrt(Numeric.dot(delta, delta)), 1.88335259871, 6) delta = coordinates[0]-coordinates[2] self.asser... |
self.r[:] = (2*invert-1) * numpy.array([ | self.r[:] = (1-2*invert) * numpy.array([ | def set_rotation_properties(self, angle, axis, invert): norm = math.sqrt(numpy.dot(axis, axis)) if norm > 0: x = axis[0] / norm y = axis[1] / norm z = axis[2] / norm c = math.cos(angle) s = math.sin(angle) self.r[:] = (2*invert-1) * numpy.array([ [x*x*(1-c)+c , x*y*(1-c)-z*s, x*z*(1-c)+y*s], [x*y*(1-c)+z*s, y*y*(1-c)+... |
self.r[:] = numpy.identity(3) * (2*invert-1) | self.r[:] = numpy.identity(3) * (1-2*invert) | def set_rotation_properties(self, angle, axis, invert): norm = math.sqrt(numpy.dot(axis, axis)) if norm > 0: x = axis[0] / norm y = axis[1] / norm z = axis[2] / norm c = math.cos(angle) s = math.sin(angle) self.r[:] = (2*invert-1) * numpy.array([ [x*x*(1-c)+c , x*y*(1-c)-z*s, x*z*(1-c)+y*s], [x*y*(1-c)+z*s, y*y*(1-c)+... |
self.t = 0 | self.t[:] = 0 | def clear(self): self.t = 0 |
self.r = 0 | self.r[:] = 0 | def clear(self): self.r = 0 self.r.ravel()[::4] = 1 |
>>> map(k('::'), ('abc', kp('abc'))) | >>> map(k('{x}'), ('abc', kp('abc'))) | def __call__(self, *args): """call the k object |
return q(".", self, K._knk(len(args), *map(K, args))) | if args: return self._dot(self._knk(len(args), *map(K, args))) else: return q("@", self, k('::')) | def __call__(self, *args): """call the k object |
('mod', 'mod')]: | ('mod', 'mod'), ('pos', '+:'), ('neg', '-:')]: | def __get__(self, client, cls): """allow K objects use as descriptors""" if client is None: return self else: return self(client) |
if abs(x) > 2**32-1: | try: return K._ki(x) except OverflowError: | def inttok(x): if abs(x) > 2**32-1: return K._kj(x) else: return K._ki(x) |
else: return K._ki(x) | def inttok(x): if abs(x) > 2**32-1: return K._kj(x) else: return K._ki(x) | |
try: c = converters[tx] except KeyError: pass | c = converters[tx] | def __new__(self, x): tx = type(x) if tx is K: return x try: array_struct = x.__array_struct__ except AttributeError: pass else: return K._from_array_interface(array_struct) try: c = converters[tx] except KeyError: pass return c(x) |
"""table columns and dict values can be accessed via dot notation | """table columns can be accessed via dot notation | def __getattr__(self, a): """table columns and dict values can be accessed via dot notation >>> q("([]a:1 2 3; b:10 20 30)").a k('1 2 3') >>> q("(`a`b`c!10 20 30)").a k('10') """ if self.inspect('t') in (98,99): return self._k(0, '{x`%s}'%a, self) raise AttributeError |
>>> q("(`a`b`c!10 20 30)").a k('10') """ if self.inspect('t') in (98,99): | >>> q("([a:1 2 3]b:10 20 30)").b k('10 20 30') """ t = self.inspect('t') if t == 98: | def __getattr__(self, a): """table columns and dict values can be accessed via dot notation >>> q("([]a:1 2 3; b:10 20 30)").a k('1 2 3') >>> q("(`a`b`c!10 20 30)").a k('10') """ if self.inspect('t') in (98,99): return self._k(0, '{x`%s}'%a, self) raise AttributeError |
return 'k(%r)' % str(self) | return 'k(%r)' % self._k(0, "-3!", self).inspect('s') | def __repr__(self): return 'k(%r)' % str(self) |
if 0 < t < 98: | if 0 <= t < 98: | def __len__(self): """ >>> len(q("1 2 3")) 3 """ t = self.inspect('t') if 0 < t < 98: return self.inspect('n') raise NotImplementedError |
try: from MA import array as ma_array except ImportError: pass else: null = {'l': int(q("0N")), 'f': float(q("0n")), 'O': "",} converters[ma_array] = lambda(a): K(a.filled(null[a.typecode()])) | def timetok(x): """converts python time to k >>> timetok(time(12,30,0,999000)) k('12:30:00.999') """ return K._kt(x.microsecond//1000 + 1000*(x.second + 60*(x.minute + 60*x.hour))) | |
return self._run_monotone(["log", rev] + last_arg) | return self._run_monotone(["log", "-r", rev] + last_arg) | def log(self, rev, xlast=None): if xlast is not None: last_arg = ["--last=%i" % (xlast,)] else: last_arg = [] return self._run_monotone(["log", rev] + last_arg) |
links = [] | preservation_links = [] | def try_draw(curr_row, next_row, curr_loc, parents): curr_items = len(curr_row) next_items = len(next_row) curr_ghosts = [] for i in xrange(curr_items): if curr_row[i] is None: curr_ghosts.append(i) links = [] have_shift = False for rev in curr_row: if rev is not None and rev in next_row: i = curr_row.index(rev) j = ne... |
links.append((i, j)) | preservation_links.append((i, j)) parent_links = [] | def try_draw(curr_row, next_row, curr_loc, parents): curr_items = len(curr_row) next_items = len(next_row) curr_ghosts = [] for i in xrange(curr_items): if curr_row[i] is None: curr_ghosts.append(i) links = [] have_shift = False for rev in curr_row: if rev is not None and rev in next_row: i = curr_row.index(rev) j = ne... |
links.append((i, j)) | parent_links.append((i, j)) preservation_crosses = links_cross(preservation_links) parent_crosses = links_cross(parent_links) if preservation_crosses.intersection(parent_crosses): return False links = preservation_links + parent_links | def try_draw(curr_row, next_row, curr_loc, parents): curr_items = len(curr_row) next_items = len(next_row) curr_ghosts = [] for i in xrange(curr_items): if curr_row[i] is None: curr_ghosts.append(i) links = [] have_shift = False for rev in curr_row: if rev is not None and rev in next_row: i = curr_row.index(rev) j = ne... |
line[dot] = "." | dots.add(dot) | def draw(curr_items, next_items, curr_loc, links, curr_ghosts, annotation): line = [" "] * (curr_items * 2 - 1) interline = [" "] * (max(curr_items, next_items) * 2 - 1) # first draw the flow-through bars in the line for i in xrange(curr_items): line[i * 2] = "|" # but then erase it for ghosts for i in curr_ghosts: li... |
for dot in dots: line[dot] = "." | def draw(curr_items, next_items, curr_loc, links, curr_ghosts, annotation): line = [" "] * (curr_items * 2 - 1) interline = [" "] * (max(curr_items, next_items) * 2 - 1) # first draw the flow-through bars in the line for i in xrange(curr_items): line[i * 2] = "|" # but then erase it for ghosts for i in curr_ghosts: li... | |
watch_list = { } | watch_list = [ ] | def project_for_branch(self, branchname): # Customize this if you are watching multiple different projects. # Return None if changes to the given branch are uninteresting. #if branchname.startswith("net.venge.monotone-viz"): # return "monotone-viz" #elif branchname.startswith("net.venge.monotone.contrib.monotree"): ... |
for server, collection in c.watch_list.items(): | for server, collection in c.watch_list: | def main(progname, args): if len(args) != 1: sys.exit("Usage: %s STATE-DIR" % (progname,)) (state_dir,) = args if not os.path.isdir(state_dir): os.makedirs(state_dir) lockfile = os.path.join(state_dir, "lock") # Small race condition, oh well. if os.path.exists(lockfile): sys.exit("script already running, exiting") try:... |
try: module.poly_line_links[lpoly_id].append( tlid ) except: module.poly_line_links[lpoly_id] = [ tlid ] try: module.poly_line_links[rpoly_id].append( tlid ) except: module.poly_line_links[rpoly_id] = [ tlid ] link_count = link_count + 1 | if lpoly_id != rpoly_id : try: module.poly_line_links[lpoly_id].append( tlid ) except: module.poly_line_links[lpoly_id] = [ tlid ] try: module.poly_line_links[rpoly_id].append( tlid ) except: module.poly_line_links[rpoly_id] = [ tlid ] link_count = link_count + 1 | def Usage(): print 'Usage: tigerpoly.py infile [outfile].shp' print sys.exit(1) |
if self.param.val('answer_mode')=="list": answer = event.widget["text"].lower() else: answer = self.answerButt.get().lower() | if self.param.val('answer_mode')=="list": answer = event.widget["text"].lower().encode('utf8') else: answer = self.answerButt.get().lower().encode('utf8') | def checkAnswer(self,event=None): """Checking the given answer, updating the score and displaying the result.""" if self.param.val('answer_mode')=="list": answer = event.widget["text"].lower() else: answer = self.answerButt.get().lower() |
'rand_answer_sel_range':opt_conv["rand_answer_sel_range"][option11.get()], | 'rand_answer_sel_range':opt_conv["rand_answer_sel_range"][option11.get().encode('utf8')], | def save(): self.param.write({ 'basic_hiragana':opt_conv["boolean"][option1.get()], 'basic_hiragana_portions':kanaPortions[0], 'modified_hiragana':opt_conv["boolean"][option2.get()], 'modified_hiragana_portions':kanaPortions[1], 'contracted_hiragana':opt_conv["boolean"][option3.get()], 'contracted_hiragana_portions':ka... |
left_frame.pack(fill="both",expand=1,side="left",pady=4,padx=4) | left_frame.pack(fill="both",expand=1,side="left",pady=4) | def validedChanges(): """Check for a least one selected kana portion (display of a message if not the case), catch parameters, then close the window.""" if not 1 in temp_list: tkMessageBox.showinfo(str(65),str(66)) |
frame2.pack(fill="both",expand=1) label = tk.Label(frame2,text=str(21),justify="left",anchor="w") label.pack() | frame2.pack(fill="both",expand=1,pady=4) label = tk.Label(frame2,text=str(21)) label.pack(fill="both",expand=1) | def validedChanges(): """Check for a least one selected kana portion (display of a message if not the case), catch parameters, then close the window.""" if not 1 in temp_list: tkMessageBox.showinfo(str(65),str(66)) |
table.pack(fill="both",expand=1) | table.pack(fill="both",expand=1,padx=4) | def validedChanges(): """Check for a least one selected kana portion (display of a message if not the case), catch parameters, then close the window.""" if not 1 in temp_list: tkMessageBox.showinfo(str(65),str(66)) |
frame2.pack(fill="both",expand=1) label = tk.Label(frame2,text=str(22),justify="left",anchor="w") label.pack() | frame2.pack(fill="both",expand=1,pady=6) label = tk.Label(frame2,text=str(22)) label.pack(fill="both",expand=1) | def validedChanges(): """Check for a least one selected kana portion (display of a message if not the case), catch parameters, then close the window.""" if not 1 in temp_list: tkMessageBox.showinfo(str(65),str(66)) |
right_frame.pack(fill="both",expand=1,pady=6,padx=6) | right_frame.pack(fill="both",expand=1,padx=4) | def validedChanges(): """Check for a least one selected kana portion (display of a message if not the case), catch parameters, then close the window.""" if not 1 in temp_list: tkMessageBox.showinfo(str(65),str(66)) |
o = tk.OptionMenu(right_frame,option8,str(62),str(63),str(64),str(80)) | o = tk.OptionMenu(right_frame,option8,str(62),str(63),str(64),str(79)) | def validedChanges(): """Check for a least one selected kana portion (display of a message if not the case), catch parameters, then close the window.""" if not 1 in temp_list: tkMessageBox.showinfo(str(65),str(66)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.