def __init__( self, max_distance=5, search_area_increment=750, rate=50 ): # max distance in meters, search area increment in sq. meters self.max_distance = max_distance self.search_area_increment = search_area_increment self.rate = rospy.Rate(rate) self.rate_raw = rate # init pub and subscriber # self.cmd_pub = rospy.Publisher('/posesequence', PoseStamped, queue_size=0) self.map_sub = rospy.Subscriber('/robot_0/map', OccupancyGrid, self.map_callback) # init map info self.occupancy_grid = [] self.map_width = 0 self.map_height = 0 self.map_resolution = 0 self.map_origin = False self.start = (0, 0) self.goal = (0, 0) self.map_initialized = False # init rendezvous transients self.executing_rendezvous = False self.rendezvous_target = (0, 0) self.master_node = Explorer('/robot_0', is_master=True, rate=rate) self.drone_node = Explorer('/robot_1', rate=rate) self.tf_listener = tf.TransformListener()
def explore_sample(): exp_result = "../explorations/%s" % (SNAME) print("[+] Exploration result in %s" % exp_result) sample = Sample(exp_result) L = Loader(KDIR) worklist = L.WORKLIST global_structs_addr = set( [gdb_value_to_int(v.address) for (_, v, _) in worklist.worklist]) explorer = Explorer(L.NODE_INFO, L.POINTER_INFO, global_structs_addr) global_heads = L.GLOBAL_HEADS global_percpus = L.PERCPU_GLOBALS for s in L.GLOBAL_CONTAINERS: sample.dump_struct(s) explore_global_percpus(sample, explorer, worklist, global_percpus) for i in global_heads: struct_type, field_name = global_heads[i] for name, v in explorer.handle_global_head(i, struct_type, field_name): worklist.append(name, v) print("[+] Ready to start the exploration") do_analysis(worklist, sample, explorer) logging.info("[+] We found %d structs" % sample.counter) return
def onDoubleClick(self, event): itemName = event.widget.master.name log.writeEvent('DoubleClick on ' + itemName + ' Folder') top = Explorer(self) self.root.topwindows.add(top) self.explorerList.add(top) top.mainloop()
class GUI(Tk): "represents GUI" def __init__(self): super().__init__() self.title("CM Manager " + ".".join(version())) self.option_add("*tearOff", FALSE) self.resizable(FALSE, FALSE) ''' # used when size of the window is changed for placeWindow arguments self.after(250, lambda: print(self.winfo_width())) self.after(250, lambda: print(self.winfo_height())) ''' placeWindow(self, 1010, 834) # notebook self.selectFunction = ttk.Notebook(self) self.selectFunction.grid() # FileStorage is associated with the Notebook self.selectFunction.fileStorage = FileStorage() self.processor = Processor(self.selectFunction) self.explorer = Explorer(self.selectFunction) self.controller = Controller(self.selectFunction) notepageWidth = 20 self.selectFunction.add(self.processor, text = "{:^{}}".format("Process", notepageWidth)) self.selectFunction.add(self.explorer, text = "{:^{}}".format("Explore", notepageWidth)) self.selectFunction.add(self.controller, text = "{:^{}}".format("Control", notepageWidth)) self.selectFunction.bind("<<NotebookTabChanged>>", lambda e: self.checkProcessing(e)) # menu self["menu"] = MenuCM(self) if not optionGet("Developer", False, 'bool'): self.protocol("WM_DELETE_WINDOW", self.closeFun) self.mainloop() def closeFun(self): "ask for saving files on exit" if doesFileStorageRequiresSave(self): answ = messagebox.askyesno(message = "Do you want to save files before leaving?", icon = "question", title = "Save files?") if answ: saveFileStorage(self) self.destroy() def checkProcessing(self, event): """checks whether it is possible for processor and controller to process files and change states of buttons accordingly""" self.processor.checkProcessing() self.controller.checkProcessing() self.explorer.checkProcessing()
def __init__(self, arduino=None, android=None, fakeRun=False, fakeMap=None, stepsPerSec=1, **kwargs): """ Constructor. Accepts attributes as kwargs. Args: fakeRun: set True if running simulation. Remember to give fake map as input. I.e: fakeMap = fakemap fakeMap: set simulation map. If left empty, creates an empty arena. pos: a 15x20 array. Contains None, 0 or 1 as values. orientation: Centre of 3x3 start area. Default = [1,1] map: Map object. Refer to Map.py sensors: Sensors object. Refer to sensors.py coordinator: Coordinator object. Refer to coordinator.py """ if fakeRun: self.fakeRun = True from sensors_fake import Sensors self.sensors = Sensors(self, fakeMap) #fake sensors for simulation self.coordinator.fakeRun = True self.coordinator.stepsPerSec = stepsPerSec self.imagefinder = Imagefinder(fakeRun=True) elif arduino is None: raise Exception("Real run requires arduino to be present") elif android is None: raise Exception("Real run requires arduino to be present") else: from sensors import Sensors self.android = android self.sensors = Sensors(self, arduino) self.coordinator.arduino = arduino self.imagefinder = Imagefinder() #update map self.updatemap() goalTiles = [ #set goal as explored [12, 19], [13, 19], [14, 19], [12, 18], [13, 18], [14, 18], [12, 17], [13, 17], [14, 17], ] valuelist = [0] * len(goalTiles) self.map.setTiles(goalTiles, valuelist) #initialise pathfinder self.pathfinder = Pathfinder(self.map) #initialise explorer self.explorer = Explorer(self)
def __init__(self, model_file, query_file, template_name, args): self.model_file = model_file # file name self.query_file = query_file # file name self.template_name = template_name self.args = args # self.model stores the network of ta from model_file # template is the TA of interest for which the constraint analysis is performed. # template in self.model is modified during the computation. A modified TA is set for each # verification step (verifyta is called). # self.location is the target location if template_name == 'All': self.model, templates = ta_helper.get_templates(self.model_file) self.TA = timed_automata.TimedAutomata() self.TA.initialize_from_templates(templates) else: self.model, template, self.location = ta_helper.get_template(self.model_file, self.query_file, template_name) self.TA = timed_automata.TimedAutomata() self.TA.initialize_from_template(template) # Constraint lists for all simple paths. # clist, paths = self.TA.constraint_lists_for_all_paths(self.location) # Identifiers for constraints over the whole TA/ self.clist = self.TA.constraint_keys_for_ta() assert len(self.clist) > 0 self.dimension = len(self.clist) self.explorer = Explorer(self.dimension) self.msres = [] self.mgs = [] self.traces = [] self.verbosity = 0 self.task = "mmsr" #statistics related data-structures and functionality self.stats = {} self.stats["checks"] = 0 self.stats["checks_insufficient"] = 0 self.stats["checks_sufficient"] = 0 self.stats["checks_insufficient_time"] = 0 self.stats["checks_sufficient_time"] = 0 self.stats["shrinks"] = 0 self.stats["shrinks_time"] = 0 self.stats["grows"] = 0 self.stats["grows_time"] = 0 self.stats["timeout"] = False self.stats["shrinksPaths"] = 0 self.stats["shrinksPaths_time"] = 0 self.timelimit = 1000000 #time limit for the MSR enumeration self.start_time = time.clock()
def main(): init() db_manager = DBManager() db_manager.run(False) explorer = Explorer(parse_args()) try: explorer.search() except psycopg2.DatabaseError as error: print('Database error. Running database manager...') db_manager.run(True)
def get_route(ID=None, traverse=None): # if 'id' in request.args: # ID = request.args['id'] if not ID or not traverse: return ( "Error. Please, specify ID and traverse on the API, <b>/api/route/ID/traverse</b>", 400) prefix = 'energy/temp/' if ID not in os.listdir('traverse/temp/'): return ("Error. Subject with ID: <b>" + ID + "</b> is not registered", 400) if traverse + '.csv' not in os.listdir('energy/temp/' + ID): prefix = 'traverse/temp/' if traverse + '.csv' not in os.listdir('traverse/temp/' + ID): return ("Error. Traverse does not exist", 400) return ("Error. Traverse has no energy", 400) astronaut = Explorer(ID=ID) df = astronaut.read_temp(ALL=False, traverse_name=traverse)[0] TIME = df['TIME'] weight = df['Weight'] load = df['Load'] velocity = df['Velocity'] slope = df['Slope'] eta = df['Eta'] rate = df['Rate'] fatigue = df['Fatigue'] dict_return = { 'ID': ID, 'Traverse': traverse, 'elements': [ 'TIME', 'Weight', 'Load', 'Velocity', 'Slope', 'Eta', 'Rate', 'Fatigue' ] } dict_return['traverse type'] = 'energy' # Not final yet dict_return['data'] = {} for i in range(len(TIME)): dict_return['data'][int(TIME[i])] = { 'Weight': float(weight[i]), 'Load': float(load[i]), 'Velocity': float(velocity[i]), 'Slope': float(slope[i]), 'Eta': float(eta[i]), 'Rate': float(rate[i]), 'Fatigue': float(fatigue[i]) } return jsonify(dict_return)
def TBA(self, N, trace, msr): exp = Explorer(self.dimension) exp.block_up(msr) seed = exp.get_unex_subset(N) while seed is not None: if self.explorer.is_shadow_insufficient(seed): exp.block_down(seed) elif path_analysis.is_realizable(self.TA, trace, [self.clist[d] for d in seed]): msr, trace = self.shrinkShadow(N, trace) self.markMSR(msr, trace) else: exp.block_down(seed) seed = exp.get_unex_subset(N)
def saveFileAs(self, event=None): self.root.wm_attributes('-topmost', False) f_name_s = ex.getFileNameSave(title='Guardar Como Archivo Tipo ZioN', file_types=[['Archivos ZioN', '*.zion']]) if f_name_s: if not f_name_s.endswith('.zion'): if f_name_s.endswith('.') or f_name_s.endswith('.z')\ or f_name_s.endswith('.zi') or f_name_s.endswith('.zio'): f_name_s = '.'.join(f_name_s.split('.')[:-1]) f_name_s += '.zion' if os.path.exists(f_name_s): resp = askyesno('Confirmar Guardar Como', os.path.basename(f_name_s)+\ ' ya existe.\n¿Desea Reemplazarlo?') if resp == False: return self._file = f_name_s with open(self._file, 'wb') as f: text = encode(self.thisTextArea.get(1.0, END).encode()) f.write(text) f.close() self.title = os.path.basename(self._file) self.root.title(self.title + self.save + self.script) self.b_unsave = False self.guardado = self.thisTextArea.get(1.0, END) self.root.wm_attributes('-topmost', self.encima_state) self.chkStatusFile()
def create_world(mp: MasParams): world = World(w=mp.G, h=mp.G, torus_enabled=True) n_ores = round(mp.G**2 * mp.D) for _ in range(n_ores): world.add_agent(Ore()) positions = [] for x in range(mp.G): for y in range(mp.G): positions.append(Vec2D(x, y)) base_positions = random.sample(positions, mp.N) if mp.M == 1: # cooperation company_ids = [0] * mp.N else: # competitive company_ids = list(range(mp.N)) for base_pos, comp_id in zip(base_positions, company_ids): base = Base(mp, comp_id) world.add_agent(base, base_pos) for _ in range(mp.X): world.add_agent(Explorer(base, mp, comp_id), pos=base_pos) for _ in range(mp.Y): world.add_agent(Transporter(base, mp, comp_id), pos=base_pos) return world
def test_uninstall_with_value_error(self): bc = Explorer('e', data=self.valid_data) bc.api = MagicMock() sp = MagicMock() fs = MagicMock() fs.path = 'mypath' fs.side_effect = ValueError() sp.get.return_value = fs bc._node_sal.storagepools.get = MagicMock(return_value=sp) bc.state.set("actions", "install", "ok") bc.uninstall() assert fs.delete.called with pytest.raises(StateCheckError): bc.state.check('status', 'running', 'ok') bc.state.check('actions', 'intsall', 'ok')
def get_apps(provider, query): """ Get all apps from bucket. """ workdir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(workdir, '..', 'config.yml')) as f: config = yaml.load(f) ex = Explorer() logging.info('Read bucket: %s', config['SCOOP_BUCKET']) apps = ex.get_apps(os.path.expandvars(config['SCOOP_BUCKET']), query) logging.info("Apps count = %d", len(apps)) installed = provider.get_installed() # check if already installed for app in apps: app['installed'] = app['name'] in installed return apps
def main(): if len(sys.argv) != 2: print "Usage: verify.py systems.json" print "Where systems.json is a file in the format of systems.json " \ "from https://github.com/SteveHodge/ed-systems" j = json.loads(open(sys.argv[1], "r").read()) stars = {} for star in j: stars[star["name"]] = star for star in sorted(stars.values(), key=lambda x: x["name"]): if not star.get("calculated") or not star.get("distances"): continue connections = [] for distance_item in star["distances"]: system = distance_item["system"] distance = float(distance_item["distance"]) other_star = stars.get(system) if not other_star: continue connections.append((system, numpy.array([float(other_star["x"]), float(other_star["y"]), float(other_star["z"])]), distance)) original_location = numpy.array([float(star["x"]), float(star["y"]), float(star["z"])]) explorer = Explorer(connections, 5000) try: explorer.explore(original_location) except TooManyIterationsException: failure("Failure: %s: Took too many iterations" % star["name"]) continue if len(explorer.correct_locations) == 0: failure("Failure: %s: Couldn't find a correct location" % star["name"]) elif len(explorer.correct_locations) > 1: failure("Failure: %s: Found multiple correct locations" % star["name"]) elif not numpy.array_equal(explorer.correct_locations[0], original_location): failure("Failure: %s: Found location %s, but doesn't match original location %s" % (star["name"], explorer.correct_locations[0], original_location)) else: print "Success: %s: Verified location after evaluating %d points" % (star["name"], len(explorer.values))
def test_stop(self): bc = Explorer('e', data=self.valid_data) bc.state.set('actions', 'start', 'ok') bc.state.set('status', 'running', 'ok') bc.api = MagicMock() bc._container_sal.stop = MagicMock() bc._block_creator.schedule_action = MagicMock() bc.stop() bc._container_sal.stop.assert_called_once() bc._block_creator.schedule_action.assert_called_once_with("stop") with pytest.raises(StateCheckError): bc.state.check('status', 'running', 'ok') bc.state.check('actions', 'start', 'ok')
def test_node_sal(self): get_node = patch('jumpscale.j.clients.zos.get', MagicMock(return_value='node')).start() bc = Explorer('e', data=self.valid_data) node_sal = bc._node_sal assert get_node.called assert node_sal == 'node'
def predict(): json = request.json if type(json) != dict: return ("Error. JSON of the traverse is required", 400) if "ID" not in json or "data" not in json: return ("Error. Submission incomplete", 400) ID = json["ID"] data = json["data"] if ID not in os.listdir('traverse/temp/'): return ("Error. Subject with ID: <b>" + ID + "</b> is not registered", 400) refresh = False if 'refresh' in request.args: refresh = request.args['refresh'] epochs = 100 if 'epochs' in request.args: epochs = request.args['epochs'] TIME = list(map(int, data.keys())) TIME.sort() TIME = list(map(str, TIME)) weight, load, velocity, slope, eta, gravity = [], [], [], [], [], [] for t in TIME: weight.append(data[t]['Weight']) load.append(data[t]['Load']) velocity.append(data[t]['Velocity']) slope.append(data[t]['Slope']) # eta.append(data[t]['Eta']) E = Explorer(ID=ID) input_names = ['Weight', 'Load', 'Velocity', 'Slope'] # input_names = ['Load', 'Velocity', 'Slope'] if 'input_names' in request.args: input_names = request.args['input_names'].split(',') if refresh or E.ID + '.h5' not in os.listdir('trained_models/'): find_nn(E, epochs=epochs) new_model = load_nn_model(E.ID, input_names=input_names) else: new_model = load_nn_model(E.ID, input_names=input_names) X = np.array([weight, load, velocity, slope]).transpose() y = new_model.predict(X) print(X.shape) print(y.shape) # conda install m2w64-toolchain dict_return = json dict_return['Rate Predicted'] = [] for i in range(len(TIME)): dict_return['data'][TIME[i]]['Rate Predicted'] = float(y[i, 0]) dict_return['Rate Predicted'].append(float(y[i, 0])) return jsonify(dict_return)
def openFile(self, event=None): self.chkStatusFile() self.root.wm_attributes('-topmost', False) if self.b_unsave: resp = '' if self._file: resp = askyesno('Confirmar Guardar Cambios', 'Desea Guardar los Cambios en el Archivo '+\ os.path.basename(self._file)) else: resp = askyesno('Confirmar Guardar Cambios', 'Desea Guardar el Archivo?') if resp: self.saveFile() text = '' f_name = ex.getFileName(title='Abrir Archivo Tipo ZioN', file_types=[['Archivos ZioN', '*.zion']]) if f_name: with open(f_name, 'rb') as f: text = f.read() try: text = decode(text).decode() except base64.binascii.Error: showwarning('No se pudo Abrir el Documento', 'Documento: '+os.path.basename(f_name)+\ '\nTiene una Codificacion Desconocida o esta Dañado') return while text.endswith('\n'): text = text[:-1] text += '\n' f.close() self._file = f_name self.title = os.path.basename(self._file) self.root.title(self.title + self.save + self.script) self.thisTextArea.delete(1.0, END) self.b_unsave = False self.thisTextArea.insert(1.0, text) self.guardado = self.thisTextArea.get(1.0, END) self._cache_y = [] self._cache_z = [] else: self._file = None self.root.wm_attributes('-topmost', self.encima_state) self.chkStatusFile()
def test_uninstall(self): bc = Explorer('e', data=self.valid_data) sp = MagicMock() fs = MagicMock() fs.path = 'mypath' sp.get.return_value = fs bc.api = MagicMock() bc._node_sal.storagepools.get = MagicMock(return_value=sp) bc._block_creator.schedule_action = MagicMock() bc.state.set("actions", "install", "ok") bc.uninstall() fs.delete.assert_called_once() bc._block_creator.schedule_action.assert_called_once() with pytest.raises(StateCheckError): bc.state.check('status', 'running', 'ok') bc.state.check('actions', 'intsall', 'ok')
def __init__(self): super().__init__() self.title("CM Manager " + ".".join(version())) self.option_add("*tearOff", FALSE) self.resizable(FALSE, FALSE) ''' used when size of the window is changed for placeWindow arguments self.after(50, lambda: print(self.winfo_width())) self.after(50, lambda: print(self.winfo_height())) ''' placeWindow(self, 1010, 786) # notebook self.selectFunction = ttk.Notebook(self) self.selectFunction.grid() # FileStorage is associated with the Notebook self.selectFunction.fileStorage = FileStorage() self.processor = Processor(self.selectFunction) self.explorer = Explorer(self.selectFunction) self.controller = Controller(self.selectFunction) notepageWidth = 20 self.selectFunction.add(self.processor, text="{:^{}}".format("Process", notepageWidth)) self.selectFunction.add(self.explorer, text="{:^{}}".format("Explore", notepageWidth)) self.selectFunction.add(self.controller, text="{:^{}}".format("Control", notepageWidth)) self.selectFunction.bind("<<NotebookTabChanged>>", lambda e: self.checkProcessing(e)) # menu self["menu"] = MenuCM(self) # checks for new messages and versions on the web if optionGet("CheckMessages", True, "bool"): self.onStart() self.mainloop()
def test_install(self): bc = Explorer('e', data=self.valid_data) # sp = MagicMock() # fs = MagicMock() # fs.path = 'mypath' # sp.get.return_value = fs # bc._node_sal.storagepools.get = MagicMock(return_value=sp) bc.api = MagicMock() waitf = MagicMock() bc._block_creator.schedule_action = MagicMock(return_value=waitf) bc.install() assert bc.api.services.find_or_create.called bc._block_creator.schedule_action.assert_called_once_with("install") # FIXME CHECK FOR WAITF # assert waitf.called bc.state.check('actions', 'install', 'ok')
def test_start_not_install(self): bc = Explorer('e', data=self.valid_data) bc._get_container = MagicMock() bc.api = MagicMock() bc._block_creator.schedule_action = MagicMock() bc._write_caddyfile = MagicMock() with pytest.raises(StateCheckError): bc.start()
async def main(): this_dir = os.path.dirname(os.path.abspath(__file__)) input_path = os.path.join(this_dir, "input.txt") with open(input_path) as f: raw_code = f.readline() print("Part 1") explorer = Explorer(raw_code) paths, oxygen, walls = await explorer.explore() print(f"Steps = {find_shortest_path_to_oxygen(paths, oxygen)}") print("Part 2") print(f"Minutes = {find_minutes_to_fill(walls, oxygen)}")
def __init__(self, sess, is_train, dim_state, dim_action, num_paths, actor_learn_rate, critic_learn_rate, tau, buffer_size, mini_batch, ep_begin, epsilon_end, gamma, max_epoch, seed=66): self.__is_train = is_train self.__dim_state = dim_state self.__dim_action = dim_action self.__mini_batch = mini_batch self.__ep_begin = ep_begin self.__gamma = gamma self.__max_epoch = max_epoch self.__actor = ActorNetwork(sess, dim_state, dim_action, 1.0, actor_learn_rate, tau, num_paths) self.__critic = CriticNetwork(sess, dim_state, dim_action, critic_learn_rate, tau) self.__replay = ReplayBuffer(buffer_size, seed) self.__explorer = Explorer(ep_begin, epsilon_end, max_epoch, dim_action, num_paths, seed) self.__state_curt = np.zeros(dim_state) self.__action_curt = self.__explorer.convert_action( np.ones(dim_action)) self.__episode = 0 self.__step = 0
def deleteData(): finput = ex.getFileName( title='Abrir Archivo para Eliminar los Datos Guardados', file_types=[['Todos los Archivos', '.*']]) if not finput: print( '\n---------------------------------------------------------------' ) print('\n Debes Abrir un Archivo.') print( '\n---------------------------------------------------------------' ) return print( '\n---------------------------------------------------------------' ) print('\n Leyendo el Archivo.') print(' Archivo:', finput) try: f = open(finput, 'rb') except: print('\n No Existe el Archivo:', finput) print( '\n---------------------------------------------------------------' ) return datas = f.read() datas = datas.split(header_INIT.encode()) ldata = len(datas) if ldata == 1: print('\n No hay Datos por Eliminar.') print( '\n---------------------------------------------------------------' ) return print('\n ' + str(ldata - 1) + ' Archivos A Eliminar.') print('\n Eliminando los Datos del Archivo.') data = datas.pop(0) fo = open(finput, 'wb') fo.write(data) fo.close() print( '\n---------------------------------------------------------------' )
def extractData(): finput = ex.getFileName(title='Abrir Archivo para Observar', file_types=[['Todos los Archivos', '.*']]) if not finput: print( '\n---------------------------------------------------------------' ) print('\n Debes Abrir un Archivo.') print( '\n---------------------------------------------------------------' ) return print( '\n---------------------------------------------------------------' ) print('\n Leyendo el Archivo.') print(' Archivo:', finput) try: f = open(finput, 'rb') except: print('\n No Existe el Archivo:', finput) print( '\n---------------------------------------------------------------' ) return datas = f.read() datas = datas.split(header_INIT.encode()) datas.pop(0) ldata = len(datas) if ldata == 0: print('\n No hay Datos Almacenados.') else: print('\n ' + str(ldata) + ' Archivos Almacenados.') print('\n Descomprimiendo los Datos.') print( '\n---------------------------------------------------------------' ) for i, data in enumerate(datas): data = bz2.decompress(data).decode() print('\n > Contenido #' + str(i + 1).zfill(2)) print(' ---- INI ----') print(data) print(' ---- EOF ----') f.close() print( '\n---------------------------------------------------------------' )
def test_upgrade(self): bc = Explorer('e', data=self.valid_data) bc.stop = MagicMock() bc.start = MagicMock() bc.upgrade("myflist") bc.stop.assert_called_once() bc.start.assert_called_once() assert bc.data['explorerFlist'] == 'myflist'
def prepare(ID): if ID not in os.listdir('traverse/temp/'): return ("Error. Subject with ID: <b>" + ID + "</b> is not registered", 400) E = Explorer(ID=ID) input_names = ['Weight', 'Load', 'Velocity', 'Slope'] if 'input_names' in request.args: input_names = request.args['input_names'].split(',') epochs = 100 if 'epochs' in request.args: epochs = request.args['epochs'] find_nn(E, epochs=epochs) return ("Ok. Model for subject <b>" + ID + "</b> created", 200)
def __init__(self): self.config = Registry(os.path.join(data_dir, 'config.json'), default=default_config).get_root() self.marksdb = Registry(os.path.join(data_dir, 'marks.json'), undefined_node='node').get_root() self.cookiejar = DCookieJar() self.cookiejar = DCookieJar(os.path.join(data_dir, 'cookies.txt')) self.login = LoginWin() self.login.brs.browser.setCookieJar(self.cookiejar) self.login.setWindowTitle(u'登陆 | Broom - %s' % __version__) self.pcs = PCS() self.root_explorer = ex = Explorer(self, self.marksdb.marks) ex.setWindowTitle(ex.windowTitle() + ' - %s' % __version__) self.player = Player(self, self.config.webkit.cache_location) self.player.set_cookiejar(self.cookiejar) self.init_signals()
def changedTask(self): """called when mode is changed changes names in Options menu exchanges Process, Explore, Control notepages calls m.changeMode puts old filestorage in m.fs[m.mode] and the self.root.[...].fileStorage is reassigned saves old slaves of GUI's notebook and loads new renames GUI and saves the mode selection to options """ if self.task.get() != m.mode: if m.mode: oldname = m.fullname[m.mode] newname = m.fullname[self.task.get()] self.menu_options.entryconfigure( "Parameter settings (" + oldname + ")", label="Parameter settings (" + newname + ")") self.menu_options.entryconfigure(oldname + " options", label=newname + " options") if m.mode in m.slaves: m.slaves[m.mode][1] = self.root.selectFunction.select() m.changeMode(self.task.get()) if m.mode not in m.fs: m.fs[m.mode] = FileStorage() self.root.selectFunction.fileStorage = m.fs[m.mode] if m.mode not in m.slaves: m.slaves[m.mode] = [ m.Slaves(Processor(self.root.selectFunction), Explorer(self.root.selectFunction), Controller(self.root.selectFunction)), None ] self.root.processor = m.slaves[m.mode][0].processor self.root.explorer = m.slaves[m.mode][0].explorer self.root.controller = m.slaves[m.mode][0].controller self.root.changeSlaves() if m.slaves[m.mode][1]: self.root.selectFunction.select(m.slaves[m.mode][1]) self.root.changeTitle(m.name) optionWrite("DefaultTask", "'" + self.task.get() + "'", general=True)
def test_start(self): bc = Explorer('e', data=self.valid_data) bc.state.set('actions', 'install', 'ok') bc._get_container = MagicMock() bc.api = MagicMock() bc._block_creator.schedule_action = MagicMock() bc.write_caddyfile = MagicMock() bc.start() bc._get_container.assert_called_once() assert bc.write_caddyfile.called bc.state.check('status', 'running', 'ok') bc.state.check('actions', 'start', 'ok')
def test_install_with_value_error(self): bc = Explorer('e', data=self.valid_data) bc.api = MagicMock() bc._create_blockcreator = MagicMock(side_effect=RuntimeError()) bc._block_creator.schedule_action = MagicMock() # TODO: better execption catching. with pytest.raises(Exception): bc.install() bc.state.check('actions', 'install', 'ok')
def __init__(self): super().__init__() self.title("CM Manager " + ".".join(version())) self.option_add("*tearOff", FALSE) self.resizable(FALSE, FALSE) ''' used when size of the window is changed for placeWindow arguments self.after(50, lambda: print(self.winfo_width())) self.after(50, lambda: print(self.winfo_height())) ''' placeWindow(self, 1010, 786) # notebook self.selectFunction = ttk.Notebook(self) self.selectFunction.grid() # FileStorage is associated with the Notebook self.selectFunction.fileStorage = FileStorage() self.processor = Processor(self.selectFunction) self.explorer = Explorer(self.selectFunction) self.controller = Controller(self.selectFunction) notepageWidth = 20 self.selectFunction.add(self.processor, text = "{:^{}}".format("Process", notepageWidth)) self.selectFunction.add(self.explorer, text = "{:^{}}".format("Explore", notepageWidth)) self.selectFunction.add(self.controller, text = "{:^{}}".format("Control", notepageWidth)) self.selectFunction.bind("<<NotebookTabChanged>>", lambda e: self.checkProcessing(e)) # menu self["menu"] = MenuCM(self) # checks for new messages and versions on the web if optionGet("CheckMessages", True, "bool"): self.onStart() self.mainloop()
def __init__(self): super().__init__() self.title("CM Manager " + ".".join(version())) self.option_add("*tearOff", FALSE) self.resizable(FALSE, FALSE) ''' # used when size of the window is changed for placeWindow arguments self.after(250, lambda: print(self.winfo_width())) self.after(250, lambda: print(self.winfo_height())) ''' placeWindow(self, 1010, 834) # notebook self.selectFunction = ttk.Notebook(self) self.selectFunction.grid() # FileStorage is associated with the Notebook self.selectFunction.fileStorage = FileStorage() self.processor = Processor(self.selectFunction) self.explorer = Explorer(self.selectFunction) self.controller = Controller(self.selectFunction) notepageWidth = 20 self.selectFunction.add(self.processor, text = "{:^{}}".format("Process", notepageWidth)) self.selectFunction.add(self.explorer, text = "{:^{}}".format("Explore", notepageWidth)) self.selectFunction.add(self.controller, text = "{:^{}}".format("Control", notepageWidth)) self.selectFunction.bind("<<NotebookTabChanged>>", lambda e: self.checkProcessing(e)) # menu self["menu"] = MenuCM(self) if not optionGet("Developer", False, 'bool'): self.protocol("WM_DELETE_WINDOW", self.closeFun) self.mainloop()
class GUI(Tk): "represents GUI" def __init__(self): super().__init__() self.title("CM Manager " + ".".join(version())) self.option_add("*tearOff", FALSE) self.resizable(FALSE, FALSE) ''' used when size of the window is changed for placeWindow arguments self.after(50, lambda: print(self.winfo_width())) self.after(50, lambda: print(self.winfo_height())) ''' placeWindow(self, 1010, 786) # notebook self.selectFunction = ttk.Notebook(self) self.selectFunction.grid() # FileStorage is associated with the Notebook self.selectFunction.fileStorage = FileStorage() self.processor = Processor(self.selectFunction) self.explorer = Explorer(self.selectFunction) self.controller = Controller(self.selectFunction) notepageWidth = 20 self.selectFunction.add(self.processor, text = "{:^{}}".format("Process", notepageWidth)) self.selectFunction.add(self.explorer, text = "{:^{}}".format("Explore", notepageWidth)) self.selectFunction.add(self.controller, text = "{:^{}}".format("Control", notepageWidth)) self.selectFunction.bind("<<NotebookTabChanged>>", lambda e: self.checkProcessing(e)) # menu self["menu"] = MenuCM(self) # checks for new messages and versions on the web if optionGet("CheckMessages", True, "bool"): self.onStart() self.mainloop() def onStart(self): "checks web for new version and post" try: self.checkNewVersion() except Exception: pass try: self.checkNewPost() except Exception: pass def checkNewVersion(self): "checks whether there is a new version available" newVersion = self.returnSiteContent("http://www.cmmanagerweb.appspot.com/version").\ split(".") versionSeen = optionGet("DontShowVersion", version(), "list") for i in range(3): if int(newVersion[i]) > int(versionSeen[i]): DialogBox(self, title = "New version available", message = self.returnSiteContent( "http://www.cmmanagerweb.appspot.com/version/message"), dontShowOption = "DontShowVersion", optionValue = newVersion) break def checkNewPost(self): "checks whether there is some post with new information on the web" currentPost = optionGet("WebPostNumber", 0, "int") webPostNumber = int(self.returnSiteContent("http://www.cmmanagerweb.appspot.com/post")) if webPostNumber > currentPost: DialogBox(self, "New information", self.returnSiteContent( "http://www.cmmanagerweb.appspot.com/post/message")) optionWrite("WebPostNumber", webPostNumber) def returnSiteContent(self, link): "return text obtained from web site" site = urlopen(link) text = site.read() site.close() text = str(text)[2:-1] return text def checkProcessing(self, event): """checks whether it is possible for processor and controller to process files and change states of buttons accordingly""" self.processor.checkProcessing() self.controller.checkProcessing() self.explorer.checkProcessing()
#Input is converted to upper case to allow for mixed case entry, #since behaviour is still well defined init = explorerInitPattern.match(line.upper()) lineNumber += 1 #if the regex does not match, output an error and quit if init is None: print("Invalid input in line {}. Line should contain: [x coord] [y coord] [facing direction (N,S,E,W)]".format(lineNumber)) sys.exit(1) #extract the values from the line x = int(init.group(1)) y = int(init.group(2)) facing = init.group(3) #construct the explorer object from the extracted values currentExplorer = Explorer(x,y,facing,bounds) #store the explorer in a list of explorers explorers.append(currentExplorer) ## LINE 2: MOVEMENT INSTRUCTIONS ## #Input is converted to upper case to allow for mixed case entry, #since behaviour is still well defined line = input().upper() lineNumber += 1 #use regex to confirm that string only contains valid instructions move = explorerMovePattern.match(line) #if the regex does not match, output an error and quit if move is None:
#!/usr/bin/env python import rospy from explorer import Explorer from std_msgs.msg import String if __name__ == '__main__': try: rospy.init_node('move_forward', anonymous = False) randomExplorer = Explorer() rospy.Subscriber("/laboratorio3/exploration", String, randomExplorer.callback) randomExplorer.navigate() rospy.spin() except rospy.ROSInterruptException: rospy.loginfo("Ctrl-C caught. Quitting")