def corrected_size(self, program): sizes = defaultdict(list) for sub in self.sub_programs[program]: sizes[self.size(sub)].append(sub) unbalanced_size = first(s for s, p in sizes.iteritems() if len(p) == 1) or 0 balanced_size, = set(sizes.keys()) - {unbalanced_size} unbalanced_by = first(sizes[unbalanced_size]) diff = balanced_size - unbalanced_size return unbalanced_by, self.sizes[unbalanced_by] + diff
def rt_equiv(self, obj): if not UT.is_satisfies(RT.Sequential, obj): return false ms = UT.seq(obj) s = UT.seq(self) while s is not nil: if ms is nil or UT.equiv(UT.first(s), UT.first(ms)) is false: return false ms = UT.next(ms) s = UT.next(s) return true if ms is nil else false
def process_g1(line: str, params: PrintParams): if "Z" in line: x = Line(line) g1: GCodeLinearMove = first(x.gcodes, condition=find_linear_move) fr: GCodeFeedRate = first(x.gcodes, condition=find_feed_rate, default=None) z_value = g1.params["Z"].value - params.width + 0.001 f_value = fr.word.value if fr and fr.word else 900 return f"G1 Z{z_value:.3f} F{f_value:.3f}\n" return line
def grade2Canvas(self): hwNum = self.args.hw assignment = first(self.assignments, lambda x: x.name.startswith(f"h{hwNum}")) for submission in assignment.get_submissions(): currentUser = first(self.users, lambda user: user.id == submission.user_id) if currentUser is None: continue name = currentUser.name.strip() if name not in self.names: continue if not self.scores[name]: continue data = self.generateHomeworkData(self.scores[name]) self.logger.debug(f"{name} {data.__repr__()}") submission.edit(**data)
def __init__(self, connectionstring, electiondate): self.electiondate = electiondate self.engine = create_engine(connectionstring) self.conn = self.engine.connect() self.session = Session(self.engine) self.Base = automap_base() self.Base.prepare(self.engine, reflect=True) self.Election = self.Base.classes.election self.Constituency = self.Base.classes.constituency self.District = self.Base.classes.district self.JudicalDistrict = self.Base.classes.judicaldistrict self.Party = self.Base.classes.party self.Candidacy = self.Base.classes.candidacy self.Votes = self.Base.classes.votes self.TotalVotes = self.Base.classes.totalvotes self.Projection = self.Base.classes.projection self.ProjectionResult = self.Base.classes.projectionresult self.enr = first( self.session.query(self.Election.nr).filter( self.Election.dt == self.electiondate).all()) if self.enr is None: raise Exception("Invalid election date") else: self.enr = self.enr[0]
def rt_equiv(self, other): if UT.is_satisfies(RT.IPersistentVector, other): if UT.equiv(RT.count.invoke1(self), UT.count(other)) is false: return false for x in range(self._cnt): i = wrap_int(x) if RT.equiv(RT.nth.invoke1(self, i), UT.nth(self, i)) is false: return false return true else: if RT.is_satisfies.invoke1(RT.Sequential, other) is false: return false ms = RT.seq.invoke1(other) for x in range(self._cnt): if ms is nil or UT.equiv(UT.nth(x, wrap_int(x)), UT.first(ms)) is false: return false ms = UT.next(ms) if ms is not nil: return false return true
def erodeAndDilate(cls, im, eadPre, eadPost): """ `ead` = erodeAndDilate Erode et Dilate l'image plusieurs fois. :param: np.array im: ensemble de trames :param: eadPre: paramètres de configuration de l'érosion et dilatation avant l'application du ET logique :param: eadPost: paramètres de configuration de l'érosion et dilatation après l'application du ET logique :return: le résultat de la trame après passer par les plusieurs processus d'érosion et dilatation, un ET logique et un processus de dilatation """ mask = im["bitwise_fgMask_and"] for m, ead in enumerate([eadPre, eadPost]): for i, op in enumerate(ead): key, val = first(op.items()) assert key in "erode dilate".split() erodeOrDilate = getattr(cv2, key) mask = erodeOrDilate(mask, cls.easyKernel(val)) im[f"{key}{'' if m else 'Mask'}{'ABCDEFGHI'[i + 2 * m]}"] = mask if m: break mask = cv2.bitwise_and(mask, im["fgMask"]) im["bitwise_fgMask_second_and"] = mask im["dilateC"] = mask # cv2.cvtColor(im["dilateMaskB"], cv2.COLOR_GRAY2BGR) return mask
def __deploy(self, name, params, removePromptFunc): dep_dir = os.path.join(DEPLOYMENT_PATH, self.name, name) if os.path.isdir(dep_dir): result = removePromptFunc("Directory " + name + " exists. Remove it? (y/n) ") if result == "y": shutil.rmtree(dep_dir) elif result == "n": return None else: print("Invalid option entered. Exiting.") return None logging.debug("Creating deployment directory %s", dep_dir) os.makedirs(dep_dir) for f in self.files: toWrite = self.files[f] for v in params: toWrite = toWrite.replace("%%" + str(v).upper() + "%%", str(params[v])) with open(os.path.join(dep_dir, f), 'w') as dest: dest.write(toWrite) # find the proper deploy script # if file "deploy" exists, execute it with bash # if file "deploy.py" exists, execute it with python scripts = [] scripts.append(['bash', str(os.path.join(dep_dir, "deploy"))]) scripts.append(['python', str(os.path.join(dep_dir, "deploy.py"))]) from util import first toR = first(lambda x: os.path.exists(x[1]), scripts) return toR
def test_cells_get_new_caddr(self): fm = FARGModel() canvas1 = SeqCanvas(Numble((4, 5, 6), 15)) got = fm.paint(None, canvas1) self.assertEqual(caddr_of(canvas1), (fm.ws, Top)) self.assertEqual(id(canvas1), id(got)) canvas2 = SeqCanvas(SeqState('bogus_avails', 'bogus_lastop')) got = fm.paint((canvas1, 'cdr'), canvas2) self.assertEqual(caddr_of(canvas2), (canvas1, 'cdr')) # Put in a second instance of canvas2: this must create a new, # identical Canvas, with a different caddr. canvas3 = fm.paint((canvas2, 'cdr'), canvas2) self.assertNotEqual(canvas2, canvas3) # Different canvases self.assertEqual(canvas2.car, canvas3.car) # Identical 'car' states self.assertEqual(canvas2.canvas, canvas1) self.assertEqual(canvas3.canvas, canvas2) self.assertEqual(fm.get((canvas2, 'car')), fm.get((canvas3, 'car'))) # The caddrs of the Values and Cells must be different self.assertEqual(canvas2.car.canvas, canvas2) self.assertEqual(canvas3.car.canvas, canvas3) self.assertEqual(canvas2.cdr.canvas, canvas2) self.assertEqual(canvas2.cdr.values, {canvas3}) self.assertEqual(first(canvas2.cdr.values).canvas, canvas2) self.assertEqual(canvas3.cdr.canvas, canvas3) self.assertEqual(canvas3.cdr.values, set())
def run( # type: ignore[override] self, fm: FARGModel, taggee: Node, tag: Node, sources: Sources ) -> CodeletResults: if not fm.has_node(taggee): if isinstance(taggee, CellRef): # HACKish and needs UT sources = fm.run_codelet_and_follow_ups( Build(to_build=taggee), sources ) if fm.has_node(taggee): if isclass(tag): # TODO Supply arguments to tag ctor tag = tag() # type: ignore[operator] sources = fm.run_codelet_and_follow_ups( Build(to_build=tag), sources ) tag = first(fm.look_up_by_name('built', sources)) # TODO What if tag is None now? fm.add_tag(taggee, tag) else: raise TaggeeDoesNotExist(taggee=taggee) return None
def test_variant_maker(self) -> None: fm = FARGModel() ca = fm.build(self.pons_start_canvas()) cr0 = fm.build(CellRef(ca, 0)) ag1 = fm.build(Consumer( operator=plus, operands=(4, 4), source=cr0 )) ag2 = fm.build(VariantMakerFromAvails( agent=ag1, cellref=cr0, avails=(4, None), unavails=(None, 4) )) # The VariantMakerFromAvails should make a new Consumer, one whose # operands include 4 and another real avail, i.e. 5 or 6. #lenable(Agent, Codelet, Fizzle) #pr(fm) fm.run_agent(ag2) new_consumer = first(fm.nodes((Consumer, Exclude(ag1)))) #ldisable_all() self.assertTrue( match_wo_none(new_consumer, Consumer.make(plus, (4, 5))) or match_wo_none(new_consumer, Consumer.make(plus, (4, 6))) )
def first_arg_is_fargmodel(o: Callable) -> bool: p0 = first(inspect.signature(o).parameters.values()) #print('FIRARG', o, p0, p0.annotation, type(p0.annotation)) try: # TODO What if annotation is a string? return issubclass(p0.annotation, FARGModel) except TypeError: return False
def is_blocked(self, elem: Hashable) -> bool: '''Does elem have a Blocked tag?''' # TODO INEFFICIENT (False result will check entire ws) def pred(fm: 'FARGModel', x: Elem) -> bool: return ( isinstance(x, Blocked) and x.taggee == elem ) return first(self.ws_query(pred))
def jump_or_fizzle(self, addr: Addr, relation: Value) -> Addr: '''Same as .jump(), but returns a single Addr or raises Not1AddrThere if there is not exactly one Addr in the Canvas 'relation' away from 'addr'.''' result = self.jump(addr, relation) if len(result) != 1: raise Not1AddrThere(canvas=self, addr=addr, relation=relation) else: return first(result)
def sort_node(node): c = [] # Module statement for mod in node.module_declarations(): c.append(mod) c.append(refpolicy.Comment()) # Requires for require in node.requires(): c.append(require) c.append(refpolicy.Comment()) # Rules # # We are going to group output by source type (which # we assume is the first argument for interfaces). rules = [] rules.extend(node.avrules()) rules.extend(node.interface_calls()) rules.sort(rule_cmp) cur = None sep_rules = [] for rule in rules: if isinstance(rule, refpolicy.InterfaceCall): x = rule.args[0] else: x = util.first(rule.src_types) if cur != x: if cur: sep_rules.append(refpolicy.Comment()) cur = x comment = refpolicy.Comment() comment.lines.append("============= %s ==============" % cur) sep_rules.append(comment) sep_rules.append(rule) c.extend(sep_rules) ras = [] ras.extend(node.role_types()) ras.sort(role_type_cmp) if len(ras): comment = refpolicy.Comment() comment.lines.append("============= ROLES ==============") c.append(comment) c.extend(ras) # Everything else for child in node.children: if child not in c: c.append(child) node.children = c
def actions(self, state): """Return a list of applicable actions: nonconflicting assignments to an unassigned variable.""" if len(state) == len(self.variables): return [] else: assignment = dict(state) var = first([v for v in self.variables if v not in assignment]) return [(var, val) for val in self.domains[var] if self.nconflicts(var, val, assignment) == 0]
def __init__(self, channel_id, api_key, pin): self.channel_id = channel_id self.api_key = api_key self.ds = DS18X20(OneWire(pin)) self.sensor = first(self.ds.scan()) if self.sensor is None: raise BrewtrackerError("No temperature sensor available!") # Last read sensor value in degrees celsius self.value = 0
def test_inner_polygon_points(simple_region_with_hole): poly = first(inner_polygons(simple_region_with_hole)) expected = ( (8, 5), (8, 2), (2, 2), (2, 8), (8, 8), (8, 5), ) assert poly == expected
def rt_hash(self): if self._hash is None: n = r_uint32(0) hash = r_uint32(1) x = RT.seq.invoke1(self) while x is not nil: hash = r_uint32(31) * hash + UT.hash(UT.first(x))._int_value n += 1 x = RT.next.invoke1(x) self._hash = wrap_int(int(mix_col_hash(hash, n))) return self._hash
def has_incomplete_journeys(self): result = self.session_requests.get( self.VIEW_CARD_ENDPOINT, params={self.CARD_ID_PARAM: self.mondo_card_id}, headers=dict(referer=self.MYCARDS_ENDPOINT)) incomplete_journey_xpath = ( '//div[@data-pageobject="card-notification"]/h5[@class=' '"text-warning" and contains(., "Incomplete Journey")]') tree = html.fromstring(result.content) incomplete_journey = first(tree.xpath(incomplete_journey_xpath)) return incomplete_journey is not None
def look(self, fm: FARGModel): # TODO Exclude nodes already tagged GettingCloser found = first(fm.search_ws(ImCell)) #print('GettingCloser.Tagger FOUND', found) if found: weight = GettingCloser.calc_weight(found, self.target) if weight > 0.001: # TODO Indicate the Want node? The target? # TODO Indicate builder tag = fm.build( GettingCloser(taggee=found, target=self.target, weight=weight)) fm.add_mut_support(tag, found)
def test_make_variant_from_avails(self) -> None: fm = FARGModel() ca = fm.build(self.pons_start_canvas()) cr0 = fm.build(CellRef(ca, 0)) ag = fm.build(Consumer(operator=plus, operands=(4, 4), source=cr0)) codelet = MakeVariantFromAvails(cellref=cr0, agent=ag, avails=(4, None), unavails=(None, 4)) fm.run_codelet(codelet) new_consumer = first(fm.nodes((Consumer, Exclude(ag)))) self.assertTrue( match_wo_none(new_consumer, Consumer.make(plus, (4, 5))) or match_wo_none(new_consumer, Consumer.make(plus, (4, 6))))
def _find_mondo_card(self): result = self.session_requests.get(self.MYCARDS_ENDPOINT, headers=dict(referer=self.BASE_URL)) tree = html.fromstring(result.content) mondo_card_xpath = ('//a[@data-pageobject="mycards-card-cardlink" ' 'and .//span[@class="view-card-nickname" and ' 'contains(.,"' + self.MONDO_CARD_NICKNAME + '")]]/@href') mondo_card = first(tree.xpath(mondo_card_xpath)) if mondo_card is None: raise ValueError('Cannot find card with nickname ' + self.MONDO_CARD_NICKNAME) self.mondo_card_id = mondo_card.split(self.CARD_ID_PARAM + "=")[1]
def _find_mondo_card(self): result = self.session_requests.get( self.MYCARDS_ENDPOINT, headers=dict(referer=self.BASE_URL)) tree = html.fromstring(result.content) mondo_card_xpath = ( '//a[@data-pageobject="mycards-card-cardlink" ' 'and .//span[@class="view-card-nickname" and ' 'contains(.,"' + self.MONDO_CARD_NICKNAME + '")]]/@href') mondo_card = first(tree.xpath(mondo_card_xpath)) if mondo_card is None: raise ValueError( 'Cannot find card with nickname ' + self.MONDO_CARD_NICKNAME) self.mondo_card_id = mondo_card.split(self.CARD_ID_PARAM + "=")[1]
def proposed_kwargs(self) -> Dict[PortLabel, NodeId]: '''Strips leading 'proposed_' from port labels and returns a dictionary mapping the resulting names to this node's neighbors at the corresponding ports.''' result = {} for pk in self.g.port_labels_of(self): if not pk.startswith('proposed_'): continue k = pk[9:] v = self.g.neighbors(self, port_label=pk) if not v: v = None elif len(v) == 1: v = first(v) result[k] = v return result
def _get_statements(self): # get statements result = self.session_requests.get( self.STATEMENTS_ENDPOINT, params={self.CARD_ID_PARAM: self.mondo_card_id}, headers=dict(referer=self.MYCARDS_ENDPOINT)) tree = html.fromstring(result.content) refresh_token_xpath = ('//form[@id="filters"]/input[@name="' '__RequestVerificationToken"]/@value') filter_token = first(tree.xpath(refresh_token_xpath)) periods_xpath = ('//select[@id="SelectedStatementPeriod"]' '/option/@value[not(.="7")]') periods = tree.xpath(periods_xpath) return periods, filter_token
def get_coefficient_term(R, f): """ """ terms = f.terms(R.order) syms = R.symbols LM, _ = terms[0] # get the first non-zero index - this is the "leading variable". leading_idx = first(nonzeros(LM)) # Then, scan the rest of the terms for any thing other than this, # and add it to the polynomial. u = 0 for monom, coeff in terms: if monom[leading_idx] != LM[leading_idx]: continue monom = monom[:leading_idx] + (0,) + monom[leading_idx+1:] u += coeff * prod(syms[var]**exp for (var, exp) in zip(xrange(len(monom)), monom)) return R(u)
def unique_mate(self, env): '''Returns unique PortLabel that is the mate to this PortLabel or raises a NoUniqueMateError.''' #TODO There must be a way to deduce an appropriate mate when there #is more than one possibility. mates = self.links_to if len(mates) == 0: mates = self.unique_ancestor_mate(self) if len(mates) == 0: raise NoUniqueMateError( f"There is no mate defined for port label '{self.name}'.") elif len(mates) == 1: return first(mates) else: mates = ', '.join(f"'{m.name}'" for m in mates) raise NoUniqueMateError( f"Port label '{self.name}' has multiple mates defined: {mates}." )
def _get_statements(self): # get statements result = self.session_requests.get( self.STATEMENTS_ENDPOINT, params={self.CARD_ID_PARAM: self.mondo_card_id}, headers=dict(referer=self.MYCARDS_ENDPOINT)) tree = html.fromstring(result.content) refresh_token_xpath = ( '//form[@id="filters"]/input[@name="' '__RequestVerificationToken"]/@value') filter_token = first(tree.xpath(refresh_token_xpath)) periods_xpath = ('//select[@id="SelectedStatementPeriod"]' '/option/@value[not(.="7")]') periods = tree.xpath(periods_xpath) return periods, filter_token
def test_noticer(self): g = NumboGraph(Numble([4, 5, 6], 15)) noticer = g.add_node(AdHocAcNode, [ All(OfClass(Brick), focal_point=g.ws), AllAre(CTagged(Avail)), TagWith(AllBricksAvail, taggees='nodes') ], member_of=g.ws) self.assertEqual(noticer.state, Start) self.assertTrue(noticer.can_go()) self.assertIn(noticer.id, g.as_nodeids(g.active_nodes())) g.do_timestep(actor=noticer) tag = g.as_node(first(g.new_nodes)) self.assertEqual(tag.__class__, AllBricksAvail) self.assertEqual(noticer.state, Completed) self.assertFalse(noticer.can_go()) self.assertNotIn(noticer.id, g.as_nodeids(g.active_nodes()))
def find_hop(self, from_node: NodeId, from_port_label: PortLabel, to_node: NodeId, to_port_label: PortLabel) -> Union[Hop, None]: '''Returns the Hop if it exists, else None.''' if not from_port_label or not to_port_label: return None if not is_iter(from_port_label): from_port_label = {from_port_label} if not is_iter(to_port_label): to_port_label = {to_port_label} # return first(hop for hop in self._hops_to_neighbor(from_node, to_node) # if hop.from_port_label == from_port_label # and # hop.to_port_label == to_port_label) return first(hop for hop in self._hops_to_neighbor(from_node, to_node) if hop.from_port_label in from_port_label and hop.to_port_label in to_port_label)
def get_coefficient_term(R, f): """ """ terms = f.terms(R.order) syms = R.symbols LM, _ = terms[0] # get the first non-zero index - this is the "leading variable". leading_idx = first(nonzeros(LM)) # Then, scan the rest of the terms for any thing other than this, # and add it to the polynomial. u = 0 for monom, coeff in terms: if monom[leading_idx] != LM[leading_idx]: continue monom = monom[:leading_idx] + (0, ) + monom[leading_idx + 1:] u += coeff * prod(syms[var]**exp for (var, exp) in zip(xrange(len(monom)), monom)) return R(u)
def load_recipe(name: str, values: Dict[str, str]): if not name.endswith(".json"): name += ".json" def match_name(x: Path): i_str = str(x.absolute()) print(i_str) return i_str.casefold().endswith(name.casefold()) files = list(load_all_files()) recipe = first(files, condition=match_name, default=None) if not recipe: logger.info(list(load_all_files())) logger.warning(f"unable to find recipe {name}") return logger.info(f"loading recipe {recipe}") with open(recipe, "r") as fp: data = json.load(fp) return set_values(values, data)
def _login(self): result = self.session_requests.get(self.BASE_URL) tree = html.fromstring(result.text) self.auth_token = tree.xpath("//input[@name='AppId']/@value")[0] payload = { "UserName": self.username, "Password": self.password, "AppId": self.auth_token } result = self.session_requests.post( self.LOGIN_ENDPOINT, data=payload, headers=dict(referer=self.BASE_URL)) tree = html.fromstring(result.content) # bad password password_xpath = '//div[@class="field-validation-error"]' error = first(tree.xpath(password_xpath)) if error is not None: raise ValueError(error.text_content().strip()) self._find_mondo_card()
def __init__(self, connectionstring, electiondate): self.electiondate = electiondate self.engine = create_engine(connectionstring) self.conn = self.engine.connect() self.session = Session(self.engine) self.Base = automap_base() self.Base.prepare(self.engine, reflect=True) self.Election = self.Base.classes.election self.Constituency = self.Base.classes.constituency self.District = self.Base.classes.district self.JudicalDistrict = self.Base.classes.judicaldistrict self.Party = self.Base.classes.party self.Candidacy = self.Base.classes.candidacy self.Votes = self.Base.classes.votes self.TotalVotes = self.Base.classes.totalvotes self.Projection = self.Base.classes.projection self.ProjectionResult = self.Base.classes.projectionresult self.enr = first(self.session.query(self.Election.nr).filter(self.Election.dt == self.electiondate).all()) if self.enr is None: raise Exception("Invalid election date") else: self.enr = self.enr[0]
def has_element(d, xpath_str): return first(d.xpath(xpath_str)) is not None