def get_centerrowcell_of_color_from_face(cube, facenum, ccolor): for rowcell in jbrik_cube.get_cross_rowcell_for_face(facenum): log_utils.log("Checking state of " + rowcell) if cube.get_cell_val_by_rowcell(rowcell) == ccolor: return rowcell return ""
def ninetydswap(startrowcell, dir, cube): solvingface = jbrik_cube.get_face_for_row(int(startrowcell.split(".")[0])) rotationface = jbrik_cube.get_adj_face_for_rowcell(startrowcell) oppositeface = jbrik_cube.OPPOSITEFACES[solvingface] targetcell = jbrik_cube.get_ninetydswap_targetcell(startrowcell, dir) destface = jbrik_cube.get_adj_face_for_rowcell(targetcell) log_utils.log("Performing 90 degree " + dir + " swap with rowcell: " + startrowcell) # 180 the starting face cube = perform_rotation_str(rotationface.__str__() + "CW2", cube) # 90 the opposite face if dir == "CW": cube = perform_rotation_str(oppositeface.__str__() + "CC1", cube) unwind2 = oppositeface.__str__() + "CW1" else: cube = perform_rotation_str(oppositeface.__str__() + "CW1", cube) unwind2 = oppositeface.__str__() + "CC1" # 180 the dest face to swap rowcells cube = perform_rotation_str(destface.__str__() + "CW2", cube) # unwind the opposite face cube = perform_rotation_str(unwind2, cube) # unwind the starting face cube = perform_rotation_str(rotationface.__str__() + "CW2", cube) return cube
def article_to_model(article_dict): """ :type article_dict: dict :rtype: model.article.Article | model.article.TrainingArticle """ try: article_id = int(article_dict.get("id")[0]) # article_categories = article_dict.get("categories") article_headline = ( article_dict.get("headline")[0]).encode(TARGET_ENCODING) # article_keywords = [keyword.encode(TARGET_ENCODING) for keyword in article_dict.get("keywords")] # article_lead = article_dict.get("lede")[0].encode(TARGET_ENCODING) if article_dict.get("text"): article_text = article_dict.get("text")[0].encode(TARGET_ENCODING) else: article_text = '' article_model = Article(id=article_id, categories=[], headline=article_headline, keywords=[], lead=u'', text=article_text) special_coverage_id = article_dict.get("specialCoverage") if special_coverage_id: return TrainingArticle(specialCoverage=int(special_coverage_id[0]), **article_model.__dict__) else: return article_model except Exception as e: log("Exception on parsing article: {}, could not create model. Context: {}" .format(e, article_dict.keys())) return None
def run(day_input: str) -> None: adapters = list(map(int, day_input.split('\n'))) adapters.sort() adapters.append(adapters[-1] + 3) last_jolt = 0 diffs = {} series_length = 0 comb = 1 for adapter in adapters: d = adapter - last_jolt log(f'checking adapter {adapter} with last adapter {last_jolt} and found diff of {d}' ) if d == 1: series_length += 1 else: if series_length in [0, 1]: pass elif series_length == 2: comb *= 2 elif series_length == 3: comb *= 4 elif series_length == 4: comb *= 7 else: raise ValueError(f'series_length is invalid {series_length}') series_length = 0 last_jolt = adapter print(comb)
def save(self): """ 用 all 方法读取文件中的所有 model 并生成一个 list 把 self 添加进去并且保存进文件 """ # log('debug save') models = self.all() # log('models', models) # 如果没有 id,说明是新添加的元素 if self.id is None: # 设置 self.id # 先看看是否是空 list if len(models) == 0: # 我们让第一个元素的 id 为 1(当然也可以为 0) self.id = 1 else: m = models[-1] # log('m', m) self.id = m.id + 1 models.append(self) else: # index = self.find(self.id) index = -1 for i, m in enumerate(models): if m.id == self.id: index = i break log('debug', index) models[index] = self l = [m.__dict__ for m in models] path = self.db_path() save(l, path)
def __repr__(self): try: return "{} <#{}, class: {} headline: {}>".format( self.__class__.__name__, self.id, self.specialCoverage, self.headline) except Exception as e: log("Could not repr training article: {}".format(e))
def is_180pos_solved_by_rowcell(facetosolve, rowcell, cube): adjrowcell = jbrik_cube.get_adjrowccell_for_rowcell(rowcell) adjrowcellcolor = cube.get_cell_val_by_rowcell(adjrowcell) # we know rowcellcolor and ccolor match because we solve that in the last phase nextpos = jbrik_cube.get_next_centerpos_for_face_rotation(facetosolve, rowcell, dir="CW") nextpos = jbrik_cube.get_next_centerpos_for_face_rotation(facetosolve, nextpos, dir="CW") nextposadjrowcell = jbrik_cube.get_adjrowccell_for_rowcell(nextpos) nextposadjrowcellccolor = cube.get_center_color_for_rowcell( nextposadjrowcell) if nextposadjrowcellccolor == adjrowcellcolor: log_utils.log( "Current rowcell: " + rowcell + " with adjcolor: " + adjrowcellcolor + " moved to 180pos: " + nextpos + " will solve 180pos by matching adjcolor to nextpos adj center color: " + nextposadjrowcellccolor) return True return False
def evaluate_operation(tokens: List[str]) -> int: log(f'evaluating {tokens}') first_char = tokens.pop() if first_char == '(': end_sub_expr = find_matching_closing_reverse(tokens) first_elem = evaluate_operation(tokens[end_sub_expr + 1:]) tokens = tokens[:end_sub_expr] else: first_elem = int(first_char) try: while True: tokens.pop() operator = tokens.pop() tokens.pop() next_char = tokens.pop() if next_char == '(': end_sub_expr = find_matching_closing_reverse(tokens) second_elem = evaluate_operation(tokens[end_sub_expr + 1:]) tokens = tokens[:end_sub_expr] else: second_elem = int(next_char) first_elem = apply_operation(first_elem, operator, second_elem) except IndexError: return first_elem
def solvecrosscorner_o2(cube, solverowcell, oppface): log_utils.log("Performing 2nd order crosscorner solve for: " + solverowcell) rotmstrset = jbrik_cube.get_oppfaceorbit_o2_trans(solverowcell) rotstr1 = rotmstrset.split(" ")[0] rotstr2 = rotmstrset.split(" ")[1] log_utils.log("Rotate face: " + rotstr1 + " to put " + solverowcell + " into position to align with solveface.") cube = jbrik_solver_move_lib.perform_rotation_str(rotstr1, cube) unwindmove1 = jbrik_solver_move_lib.reversetransition(rotstr1) log_utils.log("Rotate face: " + rotstr2 + " to put " + solverowcell + " to align with solveface.") cube = jbrik_solver_move_lib.perform_rotation_str(rotstr2, cube) unwindmove2 = jbrik_solver_move_lib.reversetransition(rotstr2) log_utils.log("Rotate face: " + unwindmove1 + " to unwind first transition") cube = jbrik_solver_move_lib.perform_rotation_str(unwindmove1, cube) log_utils.log("Rotate face: " + unwindmove2 + " to unwind second transition") cube = jbrik_solver_move_lib.perform_rotation_str(unwindmove2, cube) return cube
def resolve_colors(facerotcolormap, rotcount): adjfacemap = facerotcolormap if rotcount != 0: adjfacemap = _adjust_facevals_for_all_rotations( facerotcolormap, rotcount) bestapproxcolor = colortools.map_to_lowest_average_lab_color_distance_for_rowcell( adjfacemap) cstr = "" for tile in bestapproxcolor: log_utils.log("Tile: " + tile.__str__() + " is color: " + bestapproxcolor[tile]) if bestapproxcolor[tile] == "White": cstr += "w" if bestapproxcolor[tile] == "Green": cstr += "g" if bestapproxcolor[tile] == "Yellow": cstr += "y" if bestapproxcolor[tile] == "Blue": cstr += "b" if bestapproxcolor[tile] == "Red": cstr += "r" if bestapproxcolor[tile] == "Orange": cstr += "o" return cstr
def apply_round1(seat_map: MapGrid[str]) -> MapGrid[str]: new_seat_map = MapGrid.clone(seat_map, lambda v, pos: v) for y, row in enumerate(seat_map.grid): for x, seat in enumerate(row): # neighbors min_x = x - 1 max_x = x + 1 min_y = y - 1 max_y = y + 1 if min_x < 0: min_x = 0 if min_y < 0: min_y = 0 if max_x == seat_map.width: max_x -= 1 if max_y == seat_map.height: max_y -= 1 neighbors = 0 for ny in range(min_y, max_y + 1): for nx in range(min_x, max_x + 1): if ny == y and nx == x: continue seat_value = seat_map.value_at(Position2D(nx, ny)) if seat_value == '#': neighbors += 1 if y == 1: log(f"""x={x}, neighbors={neighbors}""") if seat == 'L' and neighbors == 0: new_seat_map.set_value_at(Position2D(x, y), '#') elif seat == '#' and neighbors > 3: new_seat_map.set_value_at(Position2D(x, y), 'L') return new_seat_map
def find_seat(seat_repr: str) -> Tuple[int, int]: # Row row_repr = seat_repr[:7] min_row = 0 max_row = 127 for instr in row_repr: log(f"""---------------- min_row: {min_row} max_row: {max_row} instr: {instr}""") if instr == 'F': max_row = int(max_row - (max_row - min_row + 1) / 2) else: min_row = int(min_row + (max_row - min_row + 1) / 2) col_repr = seat_repr[7:] min_col = 0 max_col = 7 for instr in col_repr: if instr == 'L': max_col = int(max_col - (max_col - min_col + 1) / 2) else: min_col = int(min_col + (max_col - min_col + 1) / 2) return (min_row, min_col)
def _photo_all_faces(cuber): # Photo inline cube faces for facenum in range(1, 7): log_utils.log("Flip to facenum: " + facenum.__str__()) cuber.flip_to_facenumup(facenum, True) _photo_face_rotations(facenum, cuber)
def perform_unwind_list(unwindlist, cube): unwindlist.reverse() for move in unwindlist: log_utils.log("Performing unwinding tansition: " + move) cube = perform_rotation_str(move, cube) return cube
def solvecrosscorners(cube): log_utils.log("Solving cross corners") ccolor = cube.get_cell_val_by_rowcell("2.2") facetosolve = 1 oppface = jbrik_cube.OPPOSITEFACES[facetosolve] solved = False while not solved: cube = move_oppfaceorbit_rowcells_into_o2_and_solve( cube, oppface, ccolor) cube = move_solveface_orbitcells_to_oppface(cube, facetosolve, ccolor) cube = move_oppface_corner_into_oppfaceorbit(cube, oppface, ccolor) cube = move_oppfaceorbit_rowcells_into_o2_and_solve( cube, oppface, ccolor) cube = deface_unsolved_faced_corner(cube, facetosolve, ccolor) if are_all_crosscorners_solved(cube, facetosolve): solved = True log_utils.log("All cross corners solved.") cube.finalize_solve_phase(2, ) return cube
def run(day_input: str) -> None: preamble = 25 nums = parse_input(day_input) for idx in range(preamble, len(nums)): cur_num = nums[idx] # if cur_num == 127: # import ipdb # ipdb.set_trace() found = False for left in nums[idx - preamble:idx]: num_idx = {n: True for n in nums[idx - preamble:idx]} if (cur_num - left) in num_idx: found = True break if not found: invalid_num = cur_num break print(invalid_num) for start in range(len(nums)): cumul = nums[start] for idx in range(start + 1, len(nums)): cumul += nums[idx] if cumul == invalid_num: res = nums[start:idx + 1] log(str(res)) print( f'min {min(res)}, max: {max(res)}, sum: {min(res) + max(res)}' ) elif cumul > invalid_num: break
def execute(pkgArr, filePath): for pkgName in pkgArr: pid = utils.getPid(pkgName) if len(pid) == 0: log_utils.log("process %s not run" % (pkgName)) else: recordMem(pid, pkgName, filePath)
def stop(): log_utils.log("cpu_manager stop") global startDeviceCpuInfo global pkgArr for pkg in pkgArr: getProcessAndTaskInfo(pkg)
def execute(pkgArr, filePath): cpuinfo = cpu_info.CpuInfo() cpuinfo.getCpuInfo() global lastCpuInfo time = utils.getTime() global dict if lastCpuInfo: totalCpu = cpuinfo.getTotal() - lastCpuInfo.getTotal() idle = cpuinfo.idle - lastCpuInfo.idle usr = cpuinfo.usr - lastCpuInfo.usr sys = cpuinfo.sys - lastCpuInfo.sys idlePrecent = float(idle * 100) / totalCpu usrPrecent = usr * 100 / totalCpu sysPrecent = sys * 100 / totalCpu usedPrecent = float((totalCpu - idle) * 100) / totalCpu log_utils.log( "device CPU : \t %d/usr \t %d/sys \t %.1f/idle %.1f/used" % (usrPrecent, sysPrecent, idlePrecent, usedPrecent)) cpuFile = filePath + "device_cpu.txt" content = time + "|" + str(int(usedPrecent)) file_utils.writeFileAdd(cpuFile, content + "\n") for pkg in pkgArr: if pkg not in dict.keys(): dict[str(pkg)] = cpudump.cpudump(pkg) dict[str(pkg)].dumpCpu(time, totalCpu, filePath) else: for pkg in pkgArr: if pkg not in dict.keys(): dict[str(pkg)] = cpudump.cpudump(pkg) dict[str(pkg)].initData() lastCpuInfo = cpuinfo
def apply_operation(first_elem: int, operator: str, second_elem: int) -> int: log(f'Appling operation {first_elem} { operator} {second_elem}') if operator == '+': return first_elem + second_elem elif operator == '*': return first_elem * second_elem else: raise ValueError('unknown operator')
def execute(pkgNameArr, filePath): for pkgName in pkgNameArr: pid = utils.getPid(pkgName) if len(pid) == 0: log_utils.log("process %s not run" % (pkgName)) else: content = utils.getTime() + "|" + pid + "\n" file_utils.writeFileAdd(filePath + pkgName + "_pid.txt", content)
def perform_motor_ops_for_phase(self, motoroplist): log_utils.log("Performing solver ops: " + motoroplist.__str__()) opcount = 1 for motorop in motoroplist: log_utils.log("Performing motor op " + opcount.__str__() + " of " + motoroplist.__len__().__str__() + ": " + motorop) self.perform_motor_op(motorop) opcount += 1
def print_solvemap(self): linestr = "\n\nPhase Solutions\n---------------\n" for phase in self.solveMap: linestr += "Phase " + phase.__str__( ) + " [" + self.solveMap[phase].__len__().__str__( ) + "]: " + self.solveMap[phase].__str__() + "\n" #linestr += "Phase: " + phase.__str__() + "\n" log_utils.log(linestr + "\n")
def run(day_input: str) -> None: instructions = day_input.split('\n') ship = Ship(Position(), Position(1, 10)) for instr in instructions: ship.execute_instr(instr) log(instr) log(str(ship)) print(abs(ship.ship_position.east) + abs(ship.ship_position.north))
def store_as_csv(testing_article_indexes, testing_article_categories, output_file_name=OUTPUT_CSV_FILE): start_time = datetime.utcnow() log("Storing prediction results as csv in: {}".format(output_file_name)) with open(output_file_name, 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['id', 'specialCoverage']) for index, category in zip(testing_article_indexes, testing_article_categories): spamwriter.writerow([index, category]) log("Done storing prediction csv in {}s.".format(seconds_since(start_time)))
def start(pkgArrValue, taskPathValue): log_utils.log("cpu_manager start") global pkgArr global startDeviceCpuInfo global dict global taskPath taskPath = taskPathValue pkgArr = pkgArrValue
def remove_moves_from_solvelist(startmovepos, cube): removecount = cube.get_current_solve_move_list().__len__( ) - startmovepos + 1 log_utils.log("Removing last " + removecount.__str__() + " moves from solvelist.") newlist = [] for i in range(0, startmovepos + 1): newlist.append(cube.get_current_solve_move_list()[i]) cube.currentSolveList = newlist
def get_non_oppface_adj_rowcell_for_corner(rowcell, oppface): rowcellface = get_face_for_rowcell(rowcell) log_utils.log(rowcell + " is on face: " + rowcellface.__str__()) rowcelladjs = CELLADJENCIES[rowcellface] for rowcelladj in rowcelladjs: if rowcelladj.startswith(rowcell): log_utils.log(rowcell + " is on the corner: " + rowcelladj) for adj in rowcelladj.split(" "): if adj != rowcell and get_face_for_rowcell(adj) != oppface: return adj
def _flip_1_6(self): curfaceup = self._FaceUp if curfaceup != 1: log_utils.log("flipping to face 1") self.flip_to_facenumup(1) self.rotate_cube(1, "CC") self.flip() self.rotate_cube(1, "CW") # need to manually set faceup here because rotation screws that up self._FaceUp = 6
def execute(pkgArr, filePath): time = utils.getTime() log_utils.log("------------catch fdcount------------") for pkg in pkgArr: pid = utils.getPid(pkg) fdCommand = 'adb shell ls proc/' + pid + '/fd | wc -l' fdCount = utils.excuteCmd(fdCommand) content = time + "|" + fdCount fdPath = filePath + pkg + "_fd.txt" file_utils.writeFileAdd(fdPath, content)