def cwd_service(self, req, user): last_dir = user.dir if len(req["args"]) == 0: user.dir = "." return Res(212, msg="Successful change.", sid=user.sid) # #check if address is local # if req["args"][0][0] == '/': # norm_path = os.path.join(".", req["args"][0][1:]) # else: # norm_path = os.path.join(user.dir, req["args"][0]) # # Normalizes the path -> ../.. # norm_path = os.path.normpath(norm_path) dirpath = Path().join(self.base, req["args"][0], user.dir) #final destination norm_path = Path().join_user_dir(req["args"][0], user.dir) user.dir = norm_path mypath = os.path.join(self.base, user.dir) # check if it is a valid dir if os.path.exists(mypath) == 0: user.dir = last_dir return Res(214, msg="Dir doesnt exist") # elif user.dir[:2] == "..": # user.dir = "." # mypath = os.path.join(self.base, user.dir) # return Res(214) elif os.path.isdir(mypath) == 0: user.dir = last_dir return Res(214, msg="is not a Dir") # print("This dir contains:",[f for f in listdir(mypath)]) return Res(212, msg="Successful change.", sid=user.sid)
def generate_slot_line(n, slot_position, slot_height, slot_width, base_height, base_width): if slot_height == 0 and slot_width == 0: return [] slot_height = min(slot_height, base_height) slot_width = min(slot_width, base_width) rect = [(0, 0), (0, slot_height), (slot_width, slot_height), (slot_width, 0)] dx = (base_width - slot_width) / 2 if slot_position == -1: dy = 0 elif slot_position == 0: dy = (base_height - slot_height) / 2 elif slot_position == +1: dy = base_height - slot_height slot = Path(rect, 'c', closed=True) + (dx, dy) slots = [slot + (base_width * i, 0) for i in range(n)] divider = Path([(base_width, 0), (base_width, base_height)], style='m') dividers = [divider + (base_width * i, 0) for i in range(n - 1)] return slots + dividers
def gbfs(self, problem): q = [Path([problem.getInitial()])] visited = [] i = 0 while q: i = i + 1 currentPath = q.pop(0) currentState = currentPath.getLast() if currentState == problem.getFinal(): return currentPath, i visited.append(currentState) aux = [] for child in currentState.allNextStates(): if child not in visited: aux.append(child) aux = self.orderStates(aux) for state in aux: p = Path(deepcopy(currentPath.getValues())) p.add(State(deepcopy(state.getValues()))) q.append(p) return None, i
def test_Join(self): p = Path() self.assertEqual('/', p.Join()) p = Path('/tmp', 'A') self.assertEqual('/tmp/B', p.Join('B')) p = Path('/tmp', 'A') self.assertEqual('/tmp/B/C.d', p.Join('B','C.d'))
def test_add(self): t1 = Task(foo=1) t2 = Task(bar=2) p1 = Path([t1]) p2 = Path([t2]) self.assertEqual((p1 + p2).get_tasks(), [t1, t2]) self.assertEqual((p2 + p1).get_tasks(), [t2, t1])
def generate_cell(self): """ Generate the the origami cell """ # retrieve conversion factor for selected unit unit_factor = self.calc_unit_factor() rows = self.options.rows sides = self.options.sides cols = self.options.cols radius = self.options.radius * unit_factor width = self.options.width * unit_factor # vertex_radius = self.options.vertex_radius * unit_factor angle_ratio = self.options.angle_ratio mirror_cells = self.options.mirror_cells theta = (pi / 2.) * (1 - 2. / sides) l = 2. * radius * cos(theta * (1. - angle_ratio)) dy = l * sin(theta * angle_ratio) dx = l * cos(theta * angle_ratio) - width # init dict that holds everything cell_data = {} # divider (supposed to be the same) cell_data['divider'] = Path([(0, 0), (width * cols, 0)], style='m') # IMPORTANT: left edges from TOP to BOTTOM edge_left = [Path([(0, 0), (dx, dy)], style='e')] if mirror_cells: edge_left.append(Path([(0, 0), (-dx, dy)], style='e')) cell_data['edge_left'] = [ edge_left[i % (1 + mirror_cells)] for i in range(rows) ] # IMPORTANT: right edges from BOTTOM to TOP edge_right = [ Path([(cols * width + dx, dy), (cols * width, 0)], style='e') ] if mirror_cells: edge_right.append( Path([(cols * width - dx, dy), (cols * width, 0)], style='e')) cell_data['edge_right'] = [ edge_right[i % (1 + mirror_cells)] for i in range(rows) ] # rest of cell zigzags = [ Kresling.generate_kresling_zigzag(sides, cols, radius, angle_ratio) ] if mirror_cells: zigzags.append( Path.list_reflect(zigzags[0], (0, dy / 2), (dx, dy / 2))) zigzags[1] = Path.list_add(zigzags[1], (-dx, 0)) cell_data['interior'] = [ zigzags[i % (1 + mirror_cells)] for i in range(rows) ] return cell_data
def hamiltonCycleAllPath(self): minPath = Path() for top in self.__tops: path = Path() path.addTop(top) self.__allPath(top, path, minPath) return minPath
def generate_path_tree(self): """ Specialized path generation for your origami pattern """ # retrieve conversion factor for selected unit unit_factor = self.calc_unit_factor() # retrieve saved parameters, and apply unit factor where needed width = self.options.width * unit_factor height = self.options.height * unit_factor if self.options.width_delta_bool: width_delta = self.options.width_delta * unit_factor width += width_delta height -= width_delta / 2 length = math.sqrt(2) * (width + 2 * height) half_fold = 90 if self.options.simulation_mode else 180 # bottom of box ring_inner = Path.generate_square(width, width, center=[0, 0], style='m', fold_angle=half_fold) # ring making the corners lengths = [height, width, height] points = Path.get_square_points(sum(lengths), sum(lengths), [0, 0]) styles = ['vmv', 'mmm'] ring_middle = [ Path([points[i], points[(i + 1) % 4]], 'm').break_path(lengths, styles[i % 2]) for i in range(4) ] # arms along width and length points = [(-width / 2, -(width / 2 + 0 * height)), (-width / 2, -(width / 2 + 1 * height)), (-width / 2, -(width / 2 + 2 * height)), (+width / 2, -(width / 2 + 2 * height)), (+width / 2, -(width / 2 + 1 * height)), (+width / 2, -(width / 2 + 0 * height))] arms_ = [ Path.list_create_from_points( points, 'mmvmm', fold_angles=[180, 180, half_fold, 180, 180]), Path.list_create_from_points(points, 'mvvvm', half_fold) ] arms = [Path.list_rotate(arms_[i % 2], i * pi / 2) for i in range(4)] # tiny corner diagonals diag = Path([(width / 2, width / 2), (width / 2 + height, width / 2 + height)], 'v') corner_diagonals = [diag * (1, i * pi / 2) for i in range(4)] self.edge_points = Path.get_square_points(length, length) self.path_tree = [ring_inner, ring_middle, arms, corner_diagonals] self.path_tree = recenter(self.path_tree, length / 2)
def test_IsExpand_NotBool(self): v = 'TRUE' p = Path() with self.assertRaises(TypeError) as e: p.IsExpand = v self.assertEqual('IsExpandの値にはbool型の値を渡してください。型={}, 値={}'.format(type(v), v), e.exception.args[0]) with self.assertRaises(TypeError) as e: p = Path(is_expand=v) self.assertEqual('IsExpandの値にはbool型の値を渡してください。型={}, 値={}'.format(type(v), v), e.exception.args[0])
def __load(self): try: with open(str(Path("src\\WordEmbeddings.txt")), "r") as f: data = json.load(f) return data except json.decoder.JSONDecodeError: data = {} return data except: raise IOError(str(Path("src\\WordEmbeddings.txt")))
def __load(self): try: with open(str(Path("src\\known_devices.txt")), "r") as f: self.devices = json.load(f) return data except json.decoder.JSONDecodeError: self.devices = {} return data except: raise IOError(str(Path("src\\known_devices.txt")))
def test_Child(self): v = 'A' p = Path() self.assertEqual('', p.Child) p.Child= v self.assertEqual(v, p.Child) p.Child = pathlib.Path(v) self.assertEqual(v, p.Child) p = Path('/', v) self.assertEqual(v, p.Child) p = Path(child=v) self.assertEqual(v, p.Child)
def main(): # Straight Path Test, set up your path x_start = 0 y_start = 0 straight_path_file = 'path_SRC\straight_path.csv' straight_line = load_file(straight_path_file) straight_path = Path(straight_line, x_start, y_start) # Test against simulated movement print('----------- Actual vs. Expected Straight Line-------------------') actual_line_file = 'path_SRC\straight_error_path.csv' actual_line = load_file(actual_line_file) line_error = [] line_index = [] for i in range(0, len(actual_line[0][:]) - 1): actual = [actual_line[0][i], actual_line[1][i]] error, index = straight_path.find_error(actual) line_error.append(error) line_index.append(index) # print("Error:", error) # print("Index: ", index) # Curve Path Test, set up your path circle_path_file = 'path_SRC\circle_path.csv' circle = load_file(circle_path_file) circle_path = Path(circle, x_start, y_start) curve_error = [] curve_index = [] # arbitrary test points print('----------- Actual vs. Expected Circle Path-------------------') actual_circle_file = 'path_SRC\circle_error_path.csv' actual_circle = load_file(actual_circle_file) for i in range(0, len(actual_circle[0][:]) - 1): actual = [actual_circle[0][i], actual_circle[1][i]] error, index = circle_path.find_error(actual) curve_error.append(error) curve_index.append(index) # plot errors # There is a plotting artifact on the last position, I need to figure out to solve the last position if you go beyond the last position. circle = plt.figure(1) plt.plot(curve_index, curve_error) plt.show() line = plt.figure(2) plt.plot(line_index, line_error) plt.show()
def get_solution(self, override=False): if len(self.customers) > self.MAX_LEN_BRUTE_FORCE and not override: return None min = -1 best_path = Path(self.customers) for cs in itertools.permutations(self.customers): p = Path(cs) dist = p.distance if min == -1 or dist < min: min = dist best_path = p return best_path
def _crossover(self, p1, p2): g1, g2 = [], [] for i in range(self.nCities): g1.append(p1.getGenes()[i].getIndex()) g2.append(p2.getGenes()[i].getIndex()) c1, c2 = CX2(g1,g2).getResult() genesC1, genesC2 = [], [] for i in range(self.nCities): genesC1.append(self.cities[c1[i]]) genesC2.append(self.cities[c2[i]]) c1 = Path(genesC1, self.matrix) c2 = Path(genesC2, self.matrix) return c1, c2
def test_Root(self): p = Path() self.assertEqual('/', p.Root) v = '/tmp' p.Root = v self.assertEqual(v, p.Root) p.Root = pathlib.Path(v) self.assertEqual(v, p.Root) p = Path(v) self.assertEqual(v, p.Root) p = Path(root=v) self.assertEqual(v, p.Root)
def test_Child_NotRelative(self): v = '/tmp' p = Path() with self.assertRaises(ValueError) as e: p.Child= v self.assertEqual('Childの値にはRootからの相対パスを指定してください。値={}'.format(v), e.exception.args[0]) with self.assertRaises(ValueError) as e: p = Path('/', v) self.assertEqual('Childの値にはRootからの相対パスを指定してください。値={}'.format(v), e.exception.args[0]) with self.assertRaises(ValueError) as e: p = Path(child=v) self.assertEqual('Childの値にはRootからの相対パスを指定してください。値={}'.format(v), e.exception.args[0])
def test_workflow(self): basepath = "/tmp/{}/metis".format(os.getenv("USER")) # Clean up before running do_cmd("rm {}/*.root".format(basepath)) # Set up 4 layers of input->output files step0, step1, step2, step3 = [], [], [], [] do_cmd("mkdir -p {}".format(basepath)) for i in range(3): step0.append( File(basepath=basepath, name="step0_{}.root".format(i)) ) step1.append( File(basepath=basepath, name="step1_{}.root".format(i)) ) step2.append( File(basepath=basepath, name="step2_{}.root".format(i)) ) step3.append( File(basepath=basepath, name="step3_{}.root".format(i)) ) # Make a DummyMoveTask with previous inputs, outputs # each input will be moved to the corresponding output file # by default, completion fraction must be 1.0, but can be specified # create_inputs = True will touch the input files for this task only t1 = DummyMoveTask( inputs = step0, outputs = step1, # min_completion_fraction = 0.6, create_inputs=True, ) # Clone first task for subsequent steps t2 = t1.clone(inputs = step1, outputs = step2, create_inputs=False) t3 = t1.clone(inputs = step2, outputs = step3, create_inputs=False) # Make a path, which will run tasks in sequence provided previous tasks # finish. Default dependency graph ("scheduled mode") will make it so # that t2 depends on t1 and t3 depends on t1 pa = Path([t1,t2]) pb = Path([t3]) # Yes, it was silly to make two paths, but that was done to showcase # the following concatenation ability (note that "addition" here is not # commutative) p1 = pa+pb while not p1.complete(): p1.run() time.sleep(1.0) # print "Sleeping for 1s before next path iteration" self.assertEqual(p1.complete(), True)
def hc_expand(heap): path = heap.pop() nodes = path.get_vertexes() # nodes.reverse() # must reverse for the new path to work node_to_be_expanded = path.get_end() connections = node_to_be_expanded.get_connection() connections = list(connections) connections.sort(key=lambda x: x.id, reverse=False) for c in connections: if c not in nodes: # because node in 'nodes' are 'visited' new_path = Path() for n in nodes: # print("adding to new path: " + n.id) new_path.add_vertex(n) new_path.add_vertex(c) heap.push_hc(new_path) heap.hc_sort( ) # find whether path to explore next after pushing all children
def five_section_swap(paths): children = [] for j in range(len(paths)): path = paths[j] new_route = copy.deepcopy(path.route) section_to_swap = [] cs = [] index = randint(0, len(new_route) - 6) for i in range(index, index + 5): section_to_swap.append(path.route[i]) new_route.remove(new_route[i]) #@FIXME cs.append(path.route[i].number) for n in range(len(cs) - 1): for a in range(len(new_route) - 1): if n == new_route[a].number: new_route.remove(new_route[a]) to_insert = randint(0, len(new_route) - 1) for k in range(to_insert, to_insert + 5): new_route.insert(k, path.route[to_insert]) new_paths = copy.deepcopy(paths) new_paths[j] = Path(new_route) children.append(new_paths) return children
def sort_paths(paths): children = [] pathnum = 0 for path in paths: i = 0 p = copy.deepcopy(path) prevtime = 0 new_paths = copy.deepcopy(paths) new_paths[pathnum] = Path( sorted(p.route, key=lambda customer: customer.close_time)) is_sorted = True for i in range(min(len(new_paths[pathnum].route), len(p.route))): if not (new_paths[pathnum].route[i].x == p.route[i].x and new_paths[pathnum].route[i].y == p.route[i].y): is_sorted = False if not is_sorted: children.append(new_paths) pathnum += 1 return children
def make_control(argv): 'return a Bunch' print argv parser = argparse.ArgumentParser() parser.add_argument('--test', action='store_true') parser.add_argument('--trace', action='store_true') arg = parser.parse_args(argv[1:]) arg.me = parser.prog.split('.')[0] if arg.trace: pdb.set_trace() random_seed = 123 random.seed(random_seed) dir_working = Path().dir_working() dir_out = os.path.join(dir_working, arg.me) dirutility.assure_exists(dir_out) return Bunch( arg=arg, path_in_dir=os.path.join(dir_working, 'fit-predict-v2'), path_out_no_data=os.path.join(dir_out, 'no_data.pickle'), path_out_reduction=os.path.join(dir_out, 'reduction.pickle'), path_out_reduction_2007=os.path.join(dir_out, 'reduction_2007.pickle'), path_out_reduction_200701=os.path.join(dir_out, 'reduction_200701.pickle'), path_out_log=os.path.join(dir_out, '0log.txt'), random_seed=random_seed, timer=Timer(), )
def make_control(argv): 'return a Bunch' print argv parser = argparse.ArgumentParser() parser.add_argument('invocation') parser.add_argument('--test', action='store_true') parser.add_argument('--trace', action='store_true') arg = parser.parse_args(argv) arg.me = arg.invocation.split('.')[0] if arg.trace: pdb.set_trace() random_seed = 123 random.seed(random_seed) dir_working = Path().dir_working() dir_out = os.path.join(dir_working, arg.me + ('-test' if arg.test else '')) dirutility.assure_exists(dir_out) return Bunch( arg=arg, path_in_samples=os.path.join(dir_working, 'samples2', 'train.csv'), # path_out_csv=os.path.join(dir_out, 'reduction.csv'), path_out_report_by_price=os.path.join(dir_out, 'report-by-price.txt'), path_out_report_by_n_trades=os.path.join(dir_out, 'report-by-n-trades.txt'), path_out_log=os.path.join(dir_out, '0log.txt'), random_seed=random_seed, timer=Timer(), )
def pruning_test(): # Setup Team Object team_edm = Team() lines = list() lines.append(Line(0, 1.701)) lines.append(Line(1, 0.658)) lines.append(Line(2, 0.299)) lines.append(Line(3, 0.433)) team_edm.set_team("EDM", lines=lines, start_line_index=0) # Edmonton Oilers path = Path() path.team = team_edm values_best = [] for i in range(30): temp_path = path.copy() optimal_path, num_visited = process(team_edm[team_edm.curr_line_index], temp_path, 1, i) values_best.append(num_visited) path.team[path.team.curr_line_index].toi = 0 values_worst = [] for i in range(30): temp_path = path.copy() optimal_path, num_visited = process(team_edm[team_edm.curr_line_index], temp_path, 1, i) values_worst.append(num_visited) theoretical_values = [theoretical_nodes(i) for i in range(30)] print(theoretical_values) print(values_best) print(values_worst)
def bms_expand(heap, beam_width, visited): if heap.size() > beam_width: # print("Before trimming: "+ heap.str_heuristic()) # heap.heuristic_sort() heap.trim(beam_width) # print("After trimming: " + heap.str_heuristic()) path = heap.pop() nodes = path.get_vertexes() # nodes.reverse() # must reverse for the new path to work node_to_be_expanded = path.get_end() connections = node_to_be_expanded.get_connection() connections = list(connections) connections.sort(key=lambda x: x.id, reverse=False) for c in connections: if c not in nodes and c not in visited: # because node in 'nodes' are 'visited' new_path = Path() for n in nodes: # print("adding to new path: " + n.id) new_path.add_vertex(n) new_path.add_vertex(c) heap.push_bms( new_path) # use the same push as HC (simple insertion)
def __auto_save(self): while (1): for i in range(0, 60): sleep(self.thread_sleep / 60) with open(str(Path("src\\WordEmbeddings.txt")), "w") as f: json.dump(self.dict, f)
def mkd_service(self, req, user): mypath = os.path.join(self.base, user.dir) if len(req["args"]) == 0: return Res(501) # #check if address is local # if req["args"][0][0] == '/': # dirpath = os.path.join(self.base, req["args"][0][1:]) # else: # dirpath = os.path.join(mypath, req["args"][0]) dirpath = Path().join(self.base, req["args"][0], user.dir) if req["flags"] == ['-i']: # make file try: os.mknod(dirpath) print("File ", dirpath, " Created ") except FileExistsError: print("File ", dirpath, " already exists") return Res(500, msg="File already exists") else: #make dir try: os.mkdir(dirpath) print("Directory ", dirpath, " Created ") except FileExistsError: print("Directory ", dirpath, " already exists") return Res(500, msg="Dir already exists") # print("This dir contains:",[f for f in listdir(mypath)]) return Res(257, dirpath, user.sid)
def choose_path(self,req:Request)->Path: k_paths = dict() # 元素为<路径向量,传播时延> for node in manager.nodes.values(): node: DataCenter _,pre_half, pre_delay = Graph().get_shortest_path(req.src, node.id) pre_half = pre_half[::-1] _,second_half, second_delay = Graph().get_shortest_path(node.id, req.dst) second_half = second_half[::-1] path_vec = pre_half + second_half[1:] path_vec = tuple(path_vec) if self.has_circle(path_vec) or pre_delay+second_delay>=req.maxDelay: continue # print("src = " + str(req.src) + " dst = "+ str(req.dst)) k_paths[path_vec] = pre_delay+second_delay paths = list() for p in k_paths: path:Path = Path(p, k_paths[p]) if self.check_constraints(req, path): paths.append(path) if len(paths) == 0: return None for p in paths: self.path_weight(req, p) target_path:Path = paths[0] for p in paths: p:Path if p.weight > target_path.weight: target_path = p req.path_vec = target_path.vec return target_path
def __init__(self, taxi_id, cur_lon, cur_lat, init_last_update_time, partition_id_belongto, seat_left, mobility_vector=None): self.seat_left = (3 if seat_left == None else seat_left) self.taxi_id = taxi_id self.cur_lon = cur_lon self.cur_lat = cur_lat self.schedule_list = [{ 'request_id': -1, 'schedule_type': 'NO_ORDER', 'lon': cur_lon, 'lat': cur_lat, 'arrival_time': init_last_update_time }] # schedule list中保存的是字典, 里面的内容包括: request_id: request_id, schedule_type: shedule的类型(出发或到达), lon: 经度, lat: 纬度, arrival_time: 计算出来的预期到达时间 self.__last_update_time = init_last_update_time self.partition_id_belongto = partition_id_belongto self.mobility_vector = mobility_vector self.path = Path(init_last_update_time) self.cur_total_cost = 0 self.seat_left = seat_left self.capability = self.seat_left
def placePaths(self): ids = np.unique(self.tree.getVector()) seedAmt = len(ids) pathAmt = 2 * seedAmt - 1 print("%d seedpoints, resulting in %d paths" % (seedAmt, pathAmt)) print("Seeding paths") paths = np.empty(pathAmt, dtype=object) self.ui.PathProgress.setMaximum(seedAmt) for i in range(seedAmt): path = self.tree.getPath(ids[i]) paths[i] = Path(self, i, ids[i], path) self.ui.PathProgress.setValue(i + 1) print("%d / %d" % (i, seedAmt)) self.paths = paths self.seedAmt = seedAmt self.pathAmt = pathAmt self.pathsDone()