def recmerge(*objs, merge_sequences=False): """Recursively merge an arbitrary number of collections. For conflicting values, later collections to the right are given priority. By default (merge_sequences=False), sequences are treated as a normal value and not merged. Args: *objs: collections to merge merge_sequences: whether to merge values that are sequences Returns: merged collection """ if isinstance(objs, tuple) and len(objs) == 1: # A squeeze operation since merge_with generates tuple(list_of_objs,) objs = objs[0] if all([isinstance(obj, Mapping) for obj in objs]): # Merges all the collections, recursively applies merging to the combined values return tz.merge_with( partial(recmerge, merge_sequences=merge_sequences), *objs) elif all([isinstance(obj, Sequence) for obj in objs]) and merge_sequences: # Merges sequence values by concatenation return list(tz.concat(objs)) else: # If colls does not contain mappings, simply pick the last one return tz.last(objs)
def update_credit_hrs(self): active_students: List[Student] = [ student for student in self.schedule.agents if student.is_active ] n_active_students = len(active_students) earned_hrs = [ round(earned_hr) for earned_hr in gen_credit_hrs(self.semester, n_active_students) ] attempted_hrs = [ round(attempted_hr) for attempted_hr in gen_credit_hrs( self.semester, n_active_students, False) ] for i, student in enumerate(active_students): curr_major = tlz.last(student.majors) new_earned_hrs = student.earned_hrs new_attempted_hrs = student.attempted_hrs # Check if earned & attempted credit hours exists for current semester if earned_hrs: new_earned_hrs = 0 if curr_major == "E" else earned_hrs[i] new_attempted_hrs = 0 if curr_major == "E" else attempted_hrs[i] student.earnedhrs_history.append(new_earned_hrs) student.attemptedhrs_history.append(new_attempted_hrs)
def set_agent_params(agent: Student) -> Dict: curr_major = tlz.last(agent.majors) base_params: Dict[str, Any] = { "Layer": 1, "Filled": "true", "text": agent.gender, "text_color": "white", "CurrentMajor": curr_major, "Majors": tuple(tlz.unique(agent.majors)), } if agent.is_active: color = "grey" if curr_major == "E" else Color(pick_for=curr_major).hex base_params["Earned Credit Hours"] = agent.earned_hrs base_params["Attempted Credit Hours"] = agent.attempted_hrs base_params["GPA"] = agent.gpa base_params["Shape"] = "circle" base_params["Color"] = color base_params["r"] = 1 else: base_params["Shape"] = "rect" base_params["Color"] = "grey" base_params["w"] = 1 base_params["h"] = 1 return base_params
def from_data(cls, data): keys = my_dict( (v, rc) for rc, v in data.items() if v in ascii_lowercase) doors = my_dict( (v, rc) for rc, v in data.items() if v in ascii_uppercase) walls = frozenset(rc for rc, v in data.items() if v == '#') start = first(rc for rc, v in data.items() if v == '@') return cls(keys, doors, walls, start, last(data.keys()))
def test_construct_lanczos_tridiag_beta_breakdown(self, bsz): a = rand_herm(8) alpha, beta, scaling = last(construct_lanczos_tridiag(a, bsz=bsz, K=9)) assert alpha.shape == (8,) assert beta.shape == (8,) el, ev = lanczos_tridiag_eig(alpha, beta) assert el.shape == (8,) assert el.dtype == float assert ev.shape == (8, 8) assert ev.dtype == float
def get_all_paths(coll, prefix_path=(), stop_at=None, stop_below=None): """Given a collection, by default returns paths to all the leaf nodes. Use stop_at to truncate paths at the given key. Use stop_below to truncate paths one level below the given key. """ assert ( stop_at is None or stop_below is None ), "Only one of stop_at or stop_below can be used." if stop_below is not None and stop_below in str( tz.last(tz.take(len(prefix_path) - 1, prefix_path)) ): return [[]] if stop_at is not None and stop_at in str(tz.last(prefix_path)): return [[]] if isinstance(coll, Mapping) or isinstance(coll, list): if isinstance(coll, Mapping): items = coll.items() else: items = enumerate(coll) return list( tz.concat( map( lambda t: list( map( lambda p: [t[0]] + p, get_all_paths( t[1], prefix_path=list(prefix_path) + [t[0]], stop_at=stop_at, stop_below=stop_below, ), ) ), items, ) ) ) else: return [[]]
def test_construct_lanczos_tridiag(self, bsz): a = rand_herm(2**5) alpha, beta, scaling = last( construct_lanczos_tridiag(a, bsz=bsz, K=20)) assert alpha.shape == (20,) assert beta.shape == (20,) el, ev = lanczos_tridiag_eig(alpha, beta) assert el.shape == (20,) assert el.dtype == float assert ev.shape == (20, 20) assert ev.dtype == float
def step(self) -> None: match = re.search(r"(F1SEQ1)|(SEQ2)", self.model.semester) if match is None: return self.sem_queue.appendleft(f"{self.model.semester}_MAJOR") prev_semester = (tlz.first(self.sem_queue) if len(self.sem_queue) == 1 else self.sem_queue.pop()) new_semester = f"{self.model.semester}_MAJOR" if new_semester != prev_semester: prev_major = tlz.last(self.majors) self._new_major = self.model.major_switcher.get_major( prev_semester, new_semester, prev_major)
def update_gpa(self): active_students: List[Student] = [ student for student in self.schedule.agents if student.is_active ] n_active_students = len(active_students) gpa_distr = [ round(earned_hr) for earned_hr in gen_credit_hrs(self.semester, n_active_students) ] for i, student in enumerate(active_students): curr_major = tlz.last(student.majors) new_gpa = student.gpa # Check if gpa exists for current semester if gpa_distr: new_gpa = 0 if curr_major == "E" else gpa_distr[i] student.gpa_history.append(new_gpa)
def latest_id(self) -> uuid.UUID: """ Returns the id of the latest changeset """ return last(self.journal_data.keys())
def _generate_vm_configuration( *fork_start_blocks: ForkStartBlocks, dao_start_block: Union[int, bool] = None ) -> Generator[VMStartBlock, None, None]: # noqa: E501 """ fork_start_blocks should be 2-tuples of (start_block, fork_name_or_vm_class) dao_start_block determines whether the Homestead fork will support the DAO fork and if so, at what block. - dao_start_block = None: perform the DAO fork at the same block as the Homestead start block. - dao_start_block = False: do not perform the DAO fork. - dao_start_block = <int>: perform the DAO fork at the given block number. """ # if no configuration was passed in, initialize the chain with the *latest* # Mainnet VM rules active at block 0. if not fork_start_blocks: yield (0, last(MAINNET_VMS.values())) return # Validate that there are no fork names which are not represented in the # mainnet chain. fork_names = set(fork_name for _, fork_name in fork_start_blocks if isinstance(fork_name, str)) unknown_forks = sorted(fork_names.difference(MAINNET_VMS.keys())) if unknown_forks: raise ValidationError( "Configuration contains unknown forks: {0}".format(unknown_forks)) # Validate that *if* an explicit value was passed in for dao_start_block # that the Homestead fork rules are part of the VM configuration. if dao_start_block is not None and 'homestead' not in fork_names: raise ValidationError( "The `dao_start_block` parameter is only valid for the 'homestead' " "fork rules. The 'homestead' VM was not included in the provided " "fork configuration") # If no VM is set to start at block 0, default to the frontier VM start_blocks = set(start_block for start_block, _ in fork_start_blocks) if 0 not in start_blocks: yield 0, MAINNET_VMS['frontier'] ordered_fork_start_blocks = sorted(fork_start_blocks, key=operator.itemgetter(0)) # Iterate over the parameters, generating a tuple of 2-tuples in the form: # (start_block, vm_class) for start_block, fork in ordered_fork_start_blocks: if isinstance(fork, type) and issubclass(fork, BaseVM): vm_class = fork elif isinstance(fork, str): vm_class = MAINNET_VMS[fork] else: raise Exception("Invariant: unreachable code path") if issubclass(vm_class, HomesteadVM): if dao_start_block is False: yield (start_block, vm_class.configure(support_dao_fork=False)) elif dao_start_block is None: yield (start_block, vm_class.configure(dao_fork_block_number=start_block)) elif isinstance(dao_start_block, int): validate_gte(dao_start_block, start_block) yield (start_block, vm_class.configure( dao_fork_block_number=dao_start_block)) else: raise Exception("Invariant: unreachable code path") else: yield (start_block, vm_class)
def run(found_keys: FrozenSet[str] = frozenset(), cur_pos: RC = maze.start ): next_paths = get_paths(maze.key_pos - found_keys, cur_pos) return min((len(v) - 1 + run(found_keys | {k}, last(v)) for k, v in next_paths.items()), default=0)
def last(self): return cytoolz.last(self)
def curr_major(self) -> str: return tlz.last(self.majors)
def attempted_hrs(self) -> int: return tlz.last(self.attemptedhrs_history)
def earned_hrs(self) -> int: return tlz.last(self.earnedhrs_history)
def gpa(self) -> int: return tlz.last(self.gpa_history)