def draw(self, screen): if self.data[TILE_TYPE] == TILE_GOLD: self.image = pg.image.load('gold_get.png') elif self.data[TILE_TYPE] == TILE_MONSTER: try: self.image = pg.image.load( # show image of the first monster in the list as tile image os.path.join(MONSTER_IMG_FILE_PATH, self.data[TILE_MONSTER_DATA][0][0][MONSTER_IMG_FILE])) except RuntimeError as e: DEBUG.log(e, level=1) self.image = pg.image.load('smile.png') elif self.data[TILE_TYPE] == TILE_WEAPON_SHOP: self.image = pg.image.load('weapon_shop.png') elif self.data[TILE_TYPE] == TILE_ARMOR_SHOP: self.image = pg.image.load('armor_shop.png') elif self.data[TILE_TYPE] == TILE_RESPAWN: self.image = pg.image.load('respawn.png') elif self.data[TILE_TYPE] == TILE_HEAL: self.image = pg.image.load('heal.png') elif self.data[TILE_TYPE] == TILE_OTHER_EVENT: self.image = pg.image.load('smile.png') self.image = pg.transform.scale(self.image, (self.width, self.height)) DEBUG.log("received image, image={}".format(self.image), level=3) screen.blit(self.image, (self.x_pos, self.y_pos))
def win(self, fight_scene_surface, data): DEBUG.log("Fight won", level=1) msg = "{} has gained {} exp and {} gold!"\ .format(self.player_name, 10*data[MONSTER_LEVEL], 10*data[MONSTER_LEVEL]) self.show_textbox_at_centre(fight_scene_surface, msg, 2000) # For now, loot is 10*(monster's level) self.exp += 10*data[MONSTER_LEVEL] self.gold += 10*data[MONSTER_LEVEL] if self.exp >= EXP_REQUIRED[self.level]: DEBUG.log("Level up", level=1) if self.level >= 15: raise NotImplementedError("Level higher than 15 not implemented yet.") self.level += 1 self.full_health += 15 self.current_health += 15 self.base_attack += 2 self.current_attack += 2 levelup_msg = "{} level up! Lv.{}".format(self.player_name, self.level) self.show_textbox_at_centre(fight_scene_surface, levelup_msg, 2000) self.action_result = ACTION_RESULT_WIN
def on_init(self): pygame.init() if gc.GUI["Debugger"]: width = self.width + self.height else: width = self.width self._display_surf = pygame.display.set_mode((width, self.height), pygame.DOUBLEBUF) self._game_display = pygame.Surface(self.size) self.ppcm = 3 #TODO: variable window size self.center = [ self._game_display.get_height() / (2 * self.ppcm), self._game_display.get_width() / (2 * self.ppcm) ] self._display_surf.set_alpha(None) self._running = True game_display_data = { "display": self._game_display, "ppcm": self.ppcm, "center": self.center } self.game = Game(game_display_data) if gc.GUI["Debugger"]: self.debugger = Debugger(self._display_surf, self.game.robotProgramHandlers) self.debugger.setFocusedRobot(self.focusedrobot) if gc.GUI["Logger"]: self.logger = Logger(self.game) self.logger.startLogging() pygame.mixer.quit()
def main(): debug = Debugger() chrono = Chrono() universe = Universe(debug) source = Source(debug).get_source() bucket_chain = BucketChain(debug, chrono, universe, source) clusters = Clusters(debug, chrono, universe) algorithm = OnlineClustering(debug, universe, bucket_chain, clusters) while True: operation_time = time.time() if bucket_chain.is_updated(): universe.compute_log_n_df() bucket_chain.compute_universal_counts() bucket_chain.compute_universal_tfidf() clusters.update_centroid_counts() clusters.update_centroid_tfidf() algorithm.pre_clustering_work() algorithm.online_clustering() clusters.remove_old_clusters() universe.prune_terms(clusters) debug.log("BUCKET FINISHED IN: " + str(time.time() - operation_time)) clusters.debug_active_clusters() clusters.save_active_clusters()
class Emu(object): def __init__(self, debug, graphicsScale): self.rom = Rom() self.gpu = Gpu(graphicsScale) self.cpu = Cpu(self.gpu) self.gpu.setCpu(self.cpu) self.debugger = None self.debugger = Debugger(self.cpu) if True == debug: self.debugger.activate() def run(self, binPath): self.rom.load(binPath) self.cpu.execProg(self.rom.romData, self.debugger) self.pyGameMainLoop() def pyGameMainLoop(self): while 1: event = pygame.event.wait() if event.type == pygame.KEYDOWN: keysPressed = pygame.key.get_pressed() self.cpu.keyboard.keyPressedIndication(keysPressed) if keysPressed[pygame.K_q]: self.cpu.stop() if event.type == pygame.QUIT: self.cpu.stop() if False == self.cpu.running: raise SystemExit
def test_attachDetachLogger_detaches_logger_when_ther_is_not_Empty(self): debugger = Debugger() cpu = FakeCpu() cpu.logger = Logger(cpu) debugger.attachDetachLogger(cpu) self.assertTrue(type(cpu.logger) is EmptyLogger)
def __init__(self, index, data): self.index = index self.data = data self.width = TILE_WIDTH self.height = TILE_HEIGHT # set the position of tile, which goes round the window if self.index < NUM_TILES_WIDTH - 1: # upper row (excluding top right) self.x_pos = self.index * self.width self.y_pos = 0 elif self.index < NUM_TILES_WIDTH + NUM_TILES_HEIGHT - 2: # right column (excluding bottom right) self.x_pos = WINDOW_WIDTH - self.width self.y_pos = (self.index - NUM_TILES_WIDTH + 1) * self.height elif self.index < 2*NUM_TILES_WIDTH + NUM_TILES_HEIGHT - 3: # lower row (excluding bottom left) self.x_pos = WINDOW_WIDTH - ((self.index - (NUM_TILES_WIDTH + NUM_TILES_HEIGHT - 2)) + 1) * self.width self.y_pos = WINDOW_HEIGHT - self.height elif self.index < 2*NUM_TILES_WIDTH + 2*NUM_TILES_HEIGHT - 4: # left column (excluding top left) self.x_pos = 0 self.y_pos = WINDOW_HEIGHT - (self.index - (2*NUM_TILES_WIDTH + NUM_TILES_HEIGHT - 3) + 1) * self.height else: raise IndexError("Tile index out of range: {}".format(self.index)) DEBUG.log("initialized tile, index={}, pos=({},{})".format(self.index, self.x_pos, self.y_pos), level=2)
def get(self, url, timeout = _config.SOCKET_TIMEOUT): try: res = urllib2.urlopen(url, timeout = timeout) ret = res.read() return _defcode.RPC_GET_OK, ret except Exception, e: _debugger.exc(e) return _defcode.RPC_GET_FAILED, e
def dispatch(self, e, **args): for c in self.__ecCather: try: c(e, **args) #pragma: no cover 1 except Exception,e: _debugger.out(e) if DEBUG:raise
def __init__(self, debug, graphicsScale): self.rom = Rom() self.gpu = Gpu(graphicsScale) self.cpu = Cpu(self.gpu) self.gpu.setCpu(self.cpu) self.debugger = None self.debugger = Debugger(self.cpu) if True == debug: self.debugger.activate()
def post(self, url, data, header, timeout = _config.SOCKET_TIMEOUT): try: req = urllib2.Request(url, data, header) res = urllib2.urlopen(req, timeout = timeout) ret = res.read() return _defcode.RPC_POST_OK, ret except Exception, e: _debugger.exc(e) return _defcode.RPC_POST_FAILED, e
def draw_monster_card(centre_screen, data): """ :param centre_screen: screen excluding the tiles area :param data: monster's data :return: the surface that the card is drawn """ centre_screen.fill(BACKGROUND_COLOUR) try: image = pg.image.load(os.path.join(MONSTER_IMG_FILE_PATH, data[MONSTER_IMG_FILE])) except RuntimeError as e: DEBUG.log(e, level=1) try: image = pg.image.load('smile.png') except: raise Exception finally: image = pg.transform.scale(image, (centre_screen.get_height(), centre_screen.get_height())) DEBUG.log("received image, image={}".format(image), level=3) card_surface = centre_screen.subsurface(0, 0, image.get_height(), image.get_height()) card_surface.blit(image, (0, 0)) monster_level_textbox = eztext.Input( font=pg.font.Font(None, 40), maxlength=0, prompt="Lv.{}".format(data[MONSTER_LEVEL]), x=10, y=10, ) monster_level_textbox.draw(card_surface) monster_hp_textbox = eztext.Input( font=pg.font.Font(None, 40), maxlength=0, prompt="HP:{}".format(data[MONSTER_HEALTH]), x=10, y=10+monster_level_textbox.get_size()[1], ) monster_hp_textbox.draw(card_surface) monster_attack_textbox = eztext.Input( font=pg.font.Font(None, 40), maxlength=0, prompt="ATT:{}".format(data[MONSTER_ATTACK]), x=10, y=10+monster_level_textbox.get_size()[1]+monster_hp_textbox.get_size()[1], ) monster_attack_textbox.draw(card_surface) monster_defence_textbox = eztext.Input( font=pg.font.Font(None, 40), maxlength=0, prompt="DEF:{}".format(data[MONSTER_DEFENCE]), x=10, y=10+monster_level_textbox.get_size()[1]+monster_hp_textbox.get_size()[1]+monster_attack_textbox.get_size()[1], ) monster_defence_textbox.draw(card_surface) pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT))) return card_surface
def __init__(self, plugin, parent=None): """Constructor.""" super(RemoteDebugDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html#widgets-and-dialogs-with-auto-connect self.setupUi(self) self._plugin = plugin self._debugger = Debugger()
def update_state(self, eventObj): if eventObj.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN) or not self._visible: return if eventObj.type == pg.MOUSEBUTTONDOWN: self._mouseDown = True if eventObj.type == pg.MOUSEBUTTONUP and self._mouseDown: mouse_pos = pg.mouse.get_pos() if self._topLeft[0] <= mouse_pos[0]-self._pos_offset[0] <= self._topLeft[0]+self._rect.width \ and self._topLeft[1] <= mouse_pos[1]-self._pos_offset[1] <= self._topLeft[1]+self._rect.height: DEBUG.log("Button {} pressed".format(self.text), level=3) self.buttonPressed = True
def run() -> None: """ launches all tasks for debugger """ parameters = get_parameters() analyzer = Analyzer(parameters.binary, logs=vars(parameters).get("output-file")) analyzer.run() binary_infos = analyzer.get() check_elf(binary_infos) debugger = Debugger(binary_infos) debugger.run()
def exist(state): def key(y): dxy = np.fabs(y.state[:-1] - s[:-1]) da = ((y.state[-1] + np.pi) % (2 * np.pi) - np.pi) - ((s[-1] + np.pi) % (2 * np.pi) - np.pi) return dxy[0] < self.exist_res and dxy[ 1] < self.exist_res and da < self.exist_res s = np.array(state) result = filter(key, self.vertices) Debugger.breaker('sample exclusive: {}'.format(result == []), switch=self.debug) return result
def show_textbox_at_centre(centre_screen, prompt, time): centre_screen.fill(BACKGROUND_COLOUR) textbox = eztext.Input( font=pg.font.Font(None, 30), color=BLACK, maxlength=0, prompt=prompt, x=0, y=0, ) textbox.draw(textbox.get_centre_surface(centre_screen)) #textbox.update(pg.event.get()) DEBUG.log("Displaying textbox with message '{}'".format(prompt), level=2) pg.display.flip() pg.time.delay(time)
def TestBench(steps, *args): # useful values # clock clk = Signal(bool(0)) clkDriver = ClkDriver(clk=clk, period=2) # counter cnt = Signal(intbv(0, min=0, max=steps+2)) counter = Counter(clk=clk, cnt=cnt) # Template template = Template(clk=clk) # debugger debugger = Debugger(period=1, funcs={"cnt":lambda c: str(int(c)), "clk":lambda c: str(int(c)), }, cnt=cnt, clk=clk, ) @instance def tests(): for i in range(steps): yield delay(1) return instances()
def test_get_analysis_calls_correct_things(): ''' ensure that getAnalysis() calls getStackTrace()/getRawAnalysis() ''' with unittest.mock.patch('debugger.Debugger.getStackTrace') as gst: with unittest.mock.patch('debugger.Debugger.getRawAnalysis') as gra: assert Debugger('', '').getAnalysis() gra.assert_called_once() gst.assert_called_once()
def main(experiment_meta_data, data_info): print( f'Parsing the {experiment_meta_data} to obtain model and parameters.') experiments_data = json.load(open(experiment_meta_data, 'r')) dataset_meta = json.load(open(data_info, 'r')) debugger = Debugger(experiments_data[DEBUG_STATUS]) print(experiments_data) print(dataset_meta) data_frame = InputOutputFrame(debugger, dataset_meta[INPUT_LOCATION], dataset_meta[OUTPUT_LOCATION], dataset_meta[FOLDS_LOCATION], \ dataset_meta[MAX_SENTENCES_PER_AUTHOR], dataset_meta[MIN_PADDING_PER_AUTHOR], nrows=get_optional(dataset_meta, NUMBER_OF_ROWS)) models_name = experiments_data[MODELS_NAME] output_directory = get_output_directory_name( experiments_data[OUTPUT_DIRECTORYS_LOCATION], models_name) if (not os.path.isdir(output_directory)): os.makedirs(output_directory) print("Starting the experiments.") experiment = Experiment(debugger, output_directory,get_optional(experiments_data,RESULTS_IMPORT_LOCATION), data_frame, experiments_data[BALANCE_DATA], experiments_data[EXPERIMENTS_NAME], models_name,\ experiments_data[RUN_IDENTIFICATOR], experiments_data[FOLDS], experiments_data[PREDICTION_TYPE], experiments_data[TARGETS], experiments_data[OPTIMIZATION_PARAMETERS],\ experiments_data[PRINT_BATCH_STATUS], experiments_data[MAX_CONSTANT_F1], experiments_data[NUMBER_OF_EPOCHS], experiments_data[DECAY_RATE], experiments_data[DECAY_EPOCH],\ experiments_data[VALIDATION_SET_PERCENTAGE], experiments_data[CUDA_DEVICE], experiments_data[USE_GPU], experiments_data[RANDOM_STATE]) experiment.start() print("Experiment finished!")
def __init__(self): QtGui.QMainWindow.__init__(self) self.init_ui() self.save_restore_state(False) self.cfg_window = RunConfigWindow() self.about_dialog = AboutDialog() self.pty_stdout = PtyView(self.ui.commander) stdout_path = self.pty_stdout.get_file_path() self.debugger = Debugger(stdout_path, stdout_path, self.cfg_window.working_dir) self.ui.commander.set_tab_comp_handler(self.debugger.complete_tab) self.last_highlighted_editor = None self.my_listener = MyListeningThread(self.debugger.dbg, self.FocusLine) self.FocusLine.connect(self.do_focus_line) self.my_listener.StateChanged.connect(self.on_state_changed) self.my_listener.BPChanged.connect(self.on_bp_changed) self.debugger.listener = self.my_listener self.my_listener.start() self.opened_files = {} self.bp_locations = {} args = Qt.qApp.arguments() self.cfg_window.working_dir = os.getcwd() if len(args) > 1: self.do_exe_file_open(args[1]) if len(args) > 2: self.cfg_window.arglist = [str(x) for x in args[2:]] logging.info('Ready')
def debugger_init(debug=0): global debugger # get needed vim variables # port that the engine will connect on port = int(vim.eval('debuggerPort')) if port == 0: port = 9000 # the max_depth variable to set in the engine max_children = vim.eval('debuggerMaxChildren') if max_children == '': max_children = '32' max_data = vim.eval('debuggerMaxData') if max_data == '': max_data = '1024' max_depth = vim.eval('debuggerMaxDepth') if max_depth == '': max_depth = '1' minibufexpl = int(vim.eval('debuggerMiniBufExpl')) if minibufexpl == 0: minibufexpl = 0 debugger = Debugger(port, max_children, max_data, max_depth, minibufexpl, debug)
def collision_free(self, x_from, x_to): # type: (StateNode, StateNode) -> bool """check if the path from one state to another state collides with any obstacles or not.""" # making contours of the curve states = reeds_shepp.path_sample(x_from.state, x_to.state, 1. / self.maximum_curvature, 0.3) # states.append(tuple(x_to.state)) # include the end point contours = [ self.transform(self.check_poly, s[0], s[1], s[2]) for s in states ] contours = [ np.floor(con / self.grid_res + self.grid_map.shape[0] / 2.).astype(int) for con in contours ] # making mask mask = np.zeros_like(self.grid_map, dtype=np.uint8) [cv2.fillPoly(mask, [con], 255) for con in contours] # checking result = np.bitwise_and(mask, self.grid_map) Debugger().debug_collision_checking(states, self.check_poly, np.all(result < self.obstacle), switch=self.debug) return np.all(result < self.obstacle)
def recheck(x): available, cost = self.collision_free(x_new, x), self.cost(x_new, x) if available and x.g > x_new.g + cost: Debugger().debug_rewiring(x, x_new.g + cost, switch=self.debug) x.g = x_new.g + cost x.fu, x.fl = x.g + x.hu, x.g + x.hl x.rematch(x_new)
def main(): opt = parse_command_line_args() if opt.disassemble is not None: if opt.disassemble == "boot": opt.disassemble = opt.boot_rom binary = load_binary(opt.disassemble) print("Disassembly of %s\n" % os.path.relpath(opt.disassemble)) disassemble(binary, opt.start_address) sys.exit(0) if opt.cartridge is not None: log("Loading boot ROM from %s" % os.path.relpath(opt.boot_rom)) boot = load_binary(opt.boot_rom) log("Loading cartridge from %s" % os.path.relpath(opt.cartridge)) binary = load_binary(opt.cartridge) cartridge = Cartridge(binary) log(cartridge) log("Booting Gameboy") gameboy = Gameboy(cartridge, boot, no_display=opt.no_display, zoom=opt.zoom) if opt.skip_boot: set_boot(gameboy) gameboy.memory.boot_rom_active = False if opt.debug: Debugger(gameboy).run() sys.exit(0) else: try: gameboy.cpu.run() except EmulatorError as e: log("\n** Exception: %s" % str(e).strip()) Debugger(gameboy).run() except Exception as e: log("\n** Exception: %s" % str(e).strip()) gameboy.cpu.print_registers() log("") raise
def planning(self, times, repeat=10, optimize=False, debug=False): """main flow.""" self.debug = debug past = time.time() for i in range(times): x_new = self.sample_free(i, repeat) x_nearest = self.nearest(x_new) if not optimize else self.least( x_new) if x_nearest and self.benefit(x_new) and self.collision_free( x_nearest, x_new): self.attach(x_nearest, x_new) self.rewire(x_new) self.x_best = self.best() self.branch_and_bound() Debugger().debug_planned_path(self, i, switch=self.debug) Debugger().debug_planning_hist(self, i, (time.time() - past), switch=True)
def branch_and_bound(self, space=None): def out(x): vertices.remove(x) x.remove() vertices = space if space else self.vertices vs = filter(lambda x: x.fl > self.x_best.fu + self.epsilon, vertices) map(out, vs) Debugger().debug_branch_and_bound(vs, switch=self.debug)
def __init__(self): super(MainWindow, self).__init__() self.debugger = Debugger(DummyCpu()) self.ui = uic.loadUi('gui.ui', self) self.ui.editor.setReadOnly(True) # nearly (all) connects are done via qtdesigner self.ui.editor.breakpointSet.connect(self.breakpointSet) self.ui.editor.breakpointRemoved.connect(self.breakpointRemoved) #TODO register on registerlabels for i in ['Z', 'N', 'C', 'V']: getattr(self.ui, i).toggled.connect( partial( lambda flag, state: setattr(self.debugger, flag, state), i)) self.updateDisplay()
def swap(self, i): self.branch_and_bound(self.g_vertices) self.branch_and_bound(self.s_vertices) if self.root is self.start: self.root = self.goal self.gain = self.start self.vertices = self.g_vertices n = -((i / 2) % len(self.heuristic)) - 1 if self.heuristic else i Debugger.breaker('swap: goal -> start, {}, {}'.format(i, n), self.debug) return n else: self.root = self.start self.gain = self.goal self.vertices = self.s_vertices n = (i / 2) % len(self.heuristic) if self.heuristic else i Debugger.breaker('swap: start -> goal, {}, {}'.format(i, n), self.debug) return n
def is_free(state): contour = self.transform(self.check_poly, state[0], state[1], state[2]) contour = np.floor(contour / self.grid_res + self.grid_map.shape[0] / 2.).astype(int) mask = np.zeros_like(self.grid_map, dtype=np.uint8) cv2.fillPoly(mask, [contour], 255) result = np.bitwise_and(mask, self.grid_map) Debugger().breaker( 'sample free: {}'.format(np.all(result < self.obstacle)), self.debug) return np.all(result < self.obstacle)
def setDebugMode(self): """Set the debug mode, creating a debugger an setting it up as a proxy.""" self.debugMode = True self.debugger = Debugger(self, self.interpreter) # Set the debugger as a proxy. self.interpreter = self.debugger # Create a logging handler for debugging messages. debugHandler = logging.StreamHandler(sys.stdout) debugHandler.setFormatter(logging.Formatter(self.formatStr)) debugHandler.setLevel(logging.DEBUG) self.logger.addHandler(debugHandler)
def roll_dice(self, centre_screen, event_type): """ :param centre_screen: (Surface) centre screen area :param event_type: (int) EVENT_GO_FORWARD, EVENT_GOLD, or EVENT_MONSTER_FIGHT :return: random number from 1~6 """ centre_screen.fill(BACKGROUND_COLOUR) # set up textbox for rolling dice dice_roll_textbox = self.get_dice_roll_textbox(event_type) centre_of_centre = dice_roll_textbox.get_centre_surface(centre_screen) dice_roll_textbox.draw(centre_of_centre) pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT))) # dice rolling loop while True: DEBUG.log("Waiting for player to roll dice", level=3) for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() elif event.type == pg.MOUSEBUTTONDOWN: DEBUG.log("Mouse pressed to roll dice", level=2) dice_number = Player.get_dice_number() if not SKIP_DICE_GRAPHICS: Player.show_dice_graphics(centre_screen, dice_number) return dice_number elif event.type == pg.KEYDOWN and event.key == pg.K_RETURN: DEBUG.log("Pressed enter to show status", level=2) self.show_status(centre_screen) # go back to dice roll / status show UI dice_roll_textbox.draw(centre_of_centre) pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT)))
def main(argv=None): """Popuplate options on the class from sys.argv""" if not argv: argv = sys.argv[1:] parser = make_parser() args = parser.parse_args(argv) Debugger(project=args.project, host=args.host, port=args.port, setup_project=setup_project, project_options=args.options).run()
def test_zexdoc(self): print(">>> RUNNING ZEXDOC") debugger = Debugger() debugger.stopOnError = False debugger.setHook(0x5, self.systemFunction) debugger.setHook(0x0, self.stop) rom = ROM(mapAt=0x100) rom.loadFrom('./zexdoc.com', False) cpu = CPU(rom=rom, debugger=debugger) cpu.SP = 0xF000 cpu.run(0x100) self.assertTrue(True)
def openNewFile(self): filename = QFileDialog.getOpenFileName( self, 'Open File', filter= "Compiled/Debug Files (*.out.dbg *.s.out) (*.out.dbg *.out);;All Files (*)" ) if filename != '': self.debugger = Debugger.loadFromFile(str(filename), memorysize=1024 * 1024) self.ui.ram.setData(''.join(map(chr, self.debugger.ram))) self.ui.editor.setText(self.debugger.fileContent()) self.ui.editor.resetMarker() self.updateDisplay()
def attach(self, x_nearest, x_new): # type: (StateNode, StateNode) -> None """add the new state to the tree and complement other values. And fill the hu and fu properties of x_new. """ x_new.match(x_nearest) available = self.collision_free(x_new, self.gain) x_new.hu = x_new.hl if available else np.inf x_new.fu = x_new.g + x_new.hu x_new.status = 0 if available else 1 self.vertices.append(x_new) Debugger().debug_attaching(x_nearest, x_new, 1. / self.maximum_curvature, switch=self.debug)
def rewire(self, x_new, gamma=0.2): # type: (StateNode, float) -> None """rewiring tree by the new state.""" def recheck(x): available, cost = self.collision_free(x_new, x), self.cost(x_new, x) if available and x.g > x_new.g + cost: Debugger().debug_rewiring(x, x_new.g + cost, switch=self.debug) x.g = x_new.g + cost x.fu, x.fl = x.g + x.hu, x.g + x.hl x.rematch(x_new) xs = filter(lambda x: x.g > x_new.g + gamma, self.vertices) Debugger().debug_rewiring_check(xs, x_new, switch=self.debug) map(recheck, xs)
def process_monster_fight(self, fight_scene_surface, data, fight_condition_num): monster_fight_scene_textbox = eztext.Input( font=pg.font.Font(None, 25), maxlength=0, ) monster_current_hp = data[MONSTER_HEALTH] # monster attacks first MONSTER_TURN = 0 PLAYER_TURN = 1 turn = 0 while True: fight_scene_surface.fill(BACKGROUND_COLOUR) monster_fight_scene_textbox.set_prompt("{}:{}/{}, {}:{}/{}".format( self.player_name, max(self.current_health, 0), self.full_health, data[MONSTER_NAME], max(monster_current_hp, 0), data[MONSTER_HEALTH] )) monster_fight_scene_textbox.draw(fight_scene_surface) pg.display.flip() DEBUG.log("Fighting with monster, {}:{}/{} {}:{}/{}".format( self.player_name, max(self.current_health, 0), self.full_health, data[MONSTER_NAME], max(monster_current_hp, 0), data[MONSTER_HEALTH]), level=2) pg.time.delay(300) if self.current_health <= 0: self.die(fight_scene_surface) break elif monster_current_hp <= 0: self.win(fight_scene_surface, data) break if turn % 2 == MONSTER_TURN: self.current_health -= (data[MONSTER_ATTACK] - self.current_defence) elif turn % 2 == PLAYER_TURN: monster_current_hp -= (int(self.current_attack*(9+fight_condition_num)/10) - data[MONSTER_DEFENCE]) turn += 1
def start(self): DEBUG.log("Game started", level=1) self.board.draw(self.whole_screen) self.update_player_pos() # main loop (one turn per iteration) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() # determine who plays this turn which_player_turn = self.turn % self.num_players player = self.players[which_player_turn] # process dice rolling dice_result = player.roll_dice(self.centre_screen, EVENT_GO_FORWARD) # clear the centre screen and the tile that the player was in, because the player's not there anymore self.centre_screen.fill(BACKGROUND_COLOUR) self.board.tiles[player.position].draw(self.whole_screen) player.position += dice_result DEBUG.log("Player {}, moving to position {}".format(which_player_turn+1, player.position), level=1) if player.position >= len(self.board.tiles): break self.update_player_pos() action_result = player.invoke_tile_action(self.centre_screen, tile_data[player.position]) if action_result == ACTION_RESULT_DIE: # if died, clear the player token from the tile self.board.tiles[player.died_position].draw(self.whole_screen) self.update_player_pos() self.turn += 1
def nearest(self, x_rand): # type: (StateNode) -> StateNode """find the state in the tree which is nearest to the sampled state. And fill the g, hl and fl properties of the sampled state. """ def replenish(x_n, x_r): x_r.g, x_r.hl = x_n.g + self.cost(x_n, x_r), self.cost( x_r, self.gain) x_r.fl = x_r.g + x_r.hl # quick shot if self.collision_free(self.root, x_rand): x_nearest = self.root else: costs = list(map(lambda x: self.cost(x, x_rand), self.vertices)) x_nearest = self.vertices[int(np.argmin(costs))] replenish(x_nearest, x_rand) Debugger().debug_nearest_searching(x_nearest.state, switch=self.debug) return x_nearest
def connect_graphs(self, x_new): if self.root is self.start: vs = self.g_vertices else: vs = self.s_vertices costs = map(lambda x: self.cost(x_new, x), vs) x_nearest, cost = vs[int(np.argmin(costs))], np.min(costs) Debugger().debug_connect_graphs(x_nearest.state, x_new.g + cost + x_nearest.g, self.x_best.fu, switch=self.debug) if x_new.g + cost + x_nearest.g < self.x_best.fu: if self.collision_free(x_new, x_nearest): x_nearest.fu = x_new.fu = x_new.g + cost + x_nearest.g x_new.hu = x_new.fu - x_new.g x_nearest.hu = x_nearest.fu - x_nearest.g x_new.neighbor = x_nearest x_nearest.neighbor = x_new self.x_best = x_new
def shop_initial_dialog(self, centre_screen, tile_value): centre_screen.fill(BACKGROUND_COLOUR) button_rect = pg.Rect(0, 0, 240, 60) buy_button = Button( centre_screen, (centre_screen.get_width()/2, centre_screen.get_height()/2 - button_rect.height), "Buy", 20, rect=button_rect, pos_offset=(TILE_WIDTH, TILE_HEIGHT)) sell_button = Button( centre_screen, (centre_screen.get_width()/2, centre_screen.get_height()/2), "Sell", 20, rect=button_rect, pos_offset=(TILE_WIDTH, TILE_HEIGHT)) leave_button = Button( centre_screen, (centre_screen.get_width()/2, centre_screen.get_height()/2 + button_rect.height), "Leave", 20, rect=button_rect, pos_offset=(TILE_WIDTH, TILE_HEIGHT)) buy_button.update() sell_button.update() leave_button.update() pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT))) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() buy_button.update_state(event) sell_button.update_state(event) leave_button.update_state(event) if buy_button.buttonPressed: DEBUG.log("Buy button pressed", level=2) centre_screen.fill(BACKGROUND_COLOUR) self.shop_action_buy(centre_screen, tile_value) break elif sell_button.buttonPressed: DEBUG.log("Sell button pressed", level=2) centre_screen.fill(BACKGROUND_COLOUR) self.shop_action_sell(centre_screen) break elif leave_button.buttonPressed: DEBUG.log("Leave button pressed", level=2) self.action_result = ACTION_RESULT_SHOP_LEAVE # escape recursion if leaving return # recursive process for buying/selling self.shop_initial_dialog(centre_screen, tile_value)
def emerge(): if self.heuristic: i = n % len(self.heuristic) state, biasing = self.heuristic[i] rand = [state[0], state[1], state[2]] # [x_o, y_o, a_o] (x_mu, x_sigma), (y_mu, y_sigma), (a_mu, a_sigma) = biasing rand[0] += np.random.normal(x_mu, x_sigma) rand[1] += np.random.normal(y_mu, y_sigma) rand[2] += np.random.normal(a_mu, a_sigma) return rand else: Debugger().debug_no_heuristic(vertex.state, default, self.debug) rand = [vertex.state[0], vertex.state[1], vertex.state[2]] (r_mu, r_sigma), (t_mu, t_sigma), (a_mu, a_sigma) = default r, theta = np.random.normal( r_mu, r_sigma), np.random.normal(t_mu, t_sigma) + rand[2] rand[0] += r * np.cos(theta) rand[1] += r * np.sin(theta) rand[2] += np.random.normal(a_mu, a_sigma) return rand
def detect_video(yolo, video_path, output_path=""): debug = Debugger() vid = cv2.VideoCapture(video_path) if not vid.isOpened(): raise IOError("Couldn't open webcam or video") video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC)) video_fps = vid.get(cv2.CAP_PROP_FPS) video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))) isOutput = True if output_path != "" else False if isOutput: print("!!! TYPE:", type(output_path), type(video_FourCC), type(video_fps), type(video_size)) out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size) accum_time = 0 curr_fps = 0 fps = "FPS: ??" frm_num = 0 prev_time = timer() while True: return_value, frame = vid.read() if frame is None: break image = Image.fromarray(frame) image,boxes,confidence,classID = yolo.detect_image(image) result = np.asarray(image) curr_time = timer() exec_time = curr_time - prev_time prev_time = curr_time accum_time = accum_time + exec_time curr_fps = curr_fps + 1 if accum_time > 1: accum_time = accum_time - 1 fps = "FPS: " + str(curr_fps) curr_fps = 0 cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.50, color=(255, 0, 0), thickness=2) cv2.namedWindow("result", cv2.WINDOW_NORMAL) cv2.imshow("result", result) if isOutput: out.write(result) debug.store_detected_bounding_boxes(boxes,confidence,classID,frm_num)#detections are stored per frame slicing if cv2.waitKey(1) & 0xFF == ord('q'): break frm_num += 1 debug.write_detection() print("Finished Detection on Video, total frames detected:", frm_num) yolo.close_session()
async def __debugger_create_worker(self): app_dir = os.getcwd() log_dir = self.__log_dir or app_dir log_level = self.__log_level debugger = f"{app_dir}\\debugger.exe" if platform.system( ) == "Windows" else f"{app_dir}/debugger" cmd = f"{debugger} --log_level {log_level} --log_dir {log_dir} --mode debug" while self.__proc_idle is None: try: debugger = Debugger( self.__loop, self.__server, ) await debugger.create_process(cmd) self.__proc_idle = debugger loggers.get(MODUE_NAME).info( f"Subprocess({debugger.pid}) is created.") except Exception as e: self.__proc_idle = None loggers.get(MODUE_NAME).exception(e)
class VM: """This class encapsulates all the VM processing.""" def __init__(self): self.setUpLogging() # Program counter: position of the next instruction to execute. self.PC = 0 self.endAddress = 0 # Structure of the stores used in the vm. self.variables = {} self.code = [] self.rulesCode = [] self.macrosCode = [] self.preprocessCode = [] self.trie = SystemTrie() # Current code section in execution (a macro, a rule, ...). self.currentCodeSection = self.code # Execution state of the vm. self.status = VM_STATUS.HALTED # Transfer stage (chunker, interchunk or postchunk). self.transferStage = None # Chunker mode to process in shallow mode or advanced transfer. self.chunkerMode = None # Input will be divided in words with their patterns information. self.words = [] self.superblanks = [] self.lastSuperblank = -1 self.currentWords = [] self.nextPattern = 0 # Components used by the vm. self.tokenizer = None self.callStack = CallStack(self) self.stack = SystemStack() self.loader = None self.interpreter = Interpreter(self) # Components used only in debug mode. self.debugger = None self.debugMode = False self.input = sys.stdin # We use 'buffer' to get a stream of bytes, not str, because we want to # encode it using utf-8 (just for safety). self.output = sys.stdout.buffer def setUpLogging(self): """Set at least an error through stderr logger""" self.formatStr = "%(levelname)s: %(filename)s[%(lineno)d]:\t%(message)s" self.logger = logging.getLogger("vm") errorHandler = logging.StreamHandler(sys.stderr) errorHandler.setFormatter(logging.Formatter(self.formatStr)) errorHandler.setLevel(logging.ERROR) self.logger.addHandler(errorHandler) def setDebugMode(self): """Set the debug mode, creating a debugger an setting it up as a proxy.""" self.debugMode = True self.debugger = Debugger(self, self.interpreter) # Set the debugger as a proxy. self.interpreter = self.debugger # Create a logging handler for debugging messages. debugHandler = logging.StreamHandler(sys.stdout) debugHandler.setFormatter(logging.Formatter(self.formatStr)) debugHandler.setLevel(logging.DEBUG) self.logger.addHandler(debugHandler) def setLoader(self, header, t1xFile): """Set the loader to use depending on the header of the code file.""" if "assembly" in header: self.loader = AssemblyLoader(self, t1xFile) else: return False return True def setTransferStage(self, transferHeader): """Set the transfer stage to process by the vm.""" if "transfer" in transferHeader: self.transferStage = TRANSFER_STAGE.CHUNKER self.tokenizer = TransferWordTokenizer() # Set chunker mode, by default 'lu'. if "chunk" in transferHeader: self.chunkerMode = CHUNKER_MODE.CHUNK else: self.chunkerMode = CHUNKER_MODE.LU elif "interchunk" in transferHeader: self.transferStage = TRANSFER_STAGE.INTERCHUNK self.tokenizer = ChunkWordTokenizer() elif "postchunk" in transferHeader: self.transferStage = TRANSFER_STAGE.POSTCHUNK self.tokenizer = ChunkWordTokenizer(solveRefs=True, parseContent=True) def tokenizeInput(self): """Call to the tokenizer to divide the input in tokens.""" self.words, self.superblanks = self.tokenizer.tokenize(self.input) def initializeVM(self): """Execute code to initialize the VM, e.g. default values for vars.""" self.PC = 0 self.status = VM_STATUS.RUNNING while self.status == VM_STATUS.RUNNING and self.PC < len(self.code): self.interpreter.execute(self.code[self.PC]) def getSourceWord(self, pos): """Get the part of a source word needed for pattern matching, depending on the transfer stage.""" if self.transferStage == TRANSFER_STAGE.CHUNKER: return self.words[pos].source.lu elif self.transferStage == TRANSFER_STAGE.INTERCHUNK: word = self.words[pos].chunk return word.attrs["lem"] + word.attrs["tags"] else: return self.words[pos].chunk.attrs["lem"] def getNextInputPattern(self): """Get the next input pattern to analyze, lowering the lemma first.""" try: pattern = self.getSourceWord(self.nextPattern) tag = pattern.find("<") pattern = pattern[:tag].lower() + pattern[tag:] self.nextPattern += 1 except IndexError: return None return pattern def getUniqueSuperblank(self, pos): """Get the superblank at pos avoiding duplicates.""" try: if pos != self.lastSuperblank: self.lastSuperblank = pos return self.superblanks[pos] except IndexError: pass return "" def selectNextRule(self): """Select the next rule to execute depending on the transfer stage.""" if self.transferStage == TRANSFER_STAGE.POSTCHUNK: self.selectNextRulePostChunk() else: self.selectNextRuleLRLM() def selectNextRulePostChunk(self): """Select the next rule trying to match patterns one by one.""" # Go through all the patterns until one matches a rule. while self.nextPattern < len(self.words): startPatternPos = self.nextPattern pattern = self.getNextInputPattern() ruleNumber = self.trie.getRuleNumber(pattern) if ruleNumber is not None: # print('Pattern "{}" match rule: {}'.format(pattern, ruleNumber)) self.setRuleSelected(ruleNumber, startPatternPos, pattern) return else: self.processUnmatchedPattern(self.words[startPatternPos]) # if there isn't any rule at all to execute, stop the vm. self.status = VM_STATUS.HALTED def selectNextRuleLRLM(self): """Select the next rule to execute matching the LRLM pattern.""" longestMatch = None nextPatternToProcess = self.nextPattern # Go through all the patterns until one matches a rule. while self.nextPattern < len(self.words): startPatternPos = self.nextPattern # Get the next pattern to process pattern = self.getNextInputPattern() curNodes = self.trie.getPatternNodes(pattern) nextPatternToProcess += 1 # Get the longest match, left to right fullPattern = pattern while len(curNodes) > 0: # Update the longest match if needed. ruleNumber = self.trie.getRuleNumber(fullPattern) if ruleNumber is not None: longestMatch = ruleNumber nextPatternToProcess = self.nextPattern # Continue trying to match current pattern + the next one. pattern = self.getNextInputPattern() if pattern: fullPattern += pattern nextNodes = [] for node in curNodes: nextNodes.extend(self.trie.getPatternNodes(pattern, node)) curNodes = nextNodes # If the pattern doesn't match, we will continue with the next one. # If there is a match of a group of patterns, we will continue with # the last unmatched pattern. self.nextPattern = nextPatternToProcess # Get the full pattern matched by the rule. if self.nextPattern < len(self.words): end = fullPattern.find(self.getSourceWord(self.nextPattern)) if end > 0: fullPattern = fullPattern[:end] # If there is a longest match, set the rule to process if longestMatch is not None: # print('Pattern "{}" match rule: {}'.format(fullPattern, longestMatch)) self.setRuleSelected(longestMatch, startPatternPos, fullPattern) return # Otherwise, process the unmatched pattern. else: self.processUnmatchedPattern(self.words[self.nextPattern - 1]) longestMatch = None # if there isn't any rule at all to execute, stop the vm. self.status = VM_STATUS.HALTED def setRuleSelected(self, ruleNumber, startPos, pattern): """Set a rule and its words as current ones.""" # Output the leading superblank of the matched pattern. self.writeOutput(self.getUniqueSuperblank(startPos)) # Add only a reference to the index pos of words, to avoid copying them. wordsIndex = [] while startPos != self.nextPattern: wordsIndex.append(startPos) startPos += 1 # Create an entry in the call stack with the rule to execute. self.callStack.push("rules", ruleNumber, wordsIndex) if self.debugMode: self.debugger.ruleSelected(pattern, ruleNumber) def processRuleEnd(self): """Do all the processing needed when rule ends.""" # Output the trailing superblank of the matched pattern. self.writeOutput(self.getUniqueSuperblank(self.nextPattern)) def processUnmatchedPattern(self, word): """Output unmatched patterns as the default form.""" default = "" # Output the leading superblank of the unmatched pattern. default += self.getUniqueSuperblank(self.nextPattern - 1) # For the chunker, output the default version of the unmatched pattern. if self.transferStage == TRANSFER_STAGE.CHUNKER: # If the target word is empty, we don't need to output anything. if word.target.lu != "": wordTL = "^" + word.target.lu + "$" if self.chunkerMode == CHUNKER_MODE.CHUNK: if wordTL[1] == "*": default += "^unknown<unknown>{" + wordTL + "}$" else: default += "^default<default>{" + wordTL + "}$" else: default += wordTL # For the interchunk stage only need to output the complete chunk. elif self.transferStage == TRANSFER_STAGE.INTERCHUNK: default += "^" + word.chunk.lu + "$" # Lastly, for the postchunk stage output the lexical units inside chunks # with the case of the chunk pseudolemma. else: default += word.chunk.attrs["chcontent"][1:-1] # Output the trailing superblank of the matched pattern. default += self.getUniqueSuperblank(self.nextPattern) self.writeOutput(default) def terminateVM(self): """Do all the processing needed when the vm is being turned off.""" pass def writeOutput(self, string): """A single entry point to write strings to the output.""" self.output.write(string.encode("utf-8")) def run(self): """Load, preprocess and execute the contents of the files.""" try: self.loader.load() self.interpreter.preprocess() self.initializeVM() self.tokenizeInput() if self.debugMode: self.debugger.start() # Select the first rule. If there isn't one, the vm work has ended. if self.status == VM_STATUS.RUNNING: self.selectNextRule() while self.status == VM_STATUS.RUNNING: # Execute the rule selected until it ends. while self.status == VM_STATUS.RUNNING and self.PC < self.endAddress: self.interpreter.execute(self.currentCodeSection[self.PC]) self.processRuleEnd() # Select the next rule to execute. if self.status == VM_STATUS.RUNNING: self.selectNextRule() except (Exception) as e: self.logger.exception(e) exit(1) self.terminateVM() def printCodeSections(self): """Print all the code sections for information or debugging purposes.""" self.loader.printSection(self.code, "Code") self.loader.printSection(self.preprocessCode, "Preprocess") self.loader.printSection(self.rulesCode, "Rules", enum=True) self.loader.printSection(self.macrosCode, "Macros", enum=True)
def shop_action_buy(self, centre_screen, tile_value): shop_type = tile_value[TILE_ITEM_TYPE] data = tile_value[TILE_ITEM_DATA] item_count = len(data) + 1 # last item is "Cancel" button DEBUG.log("Number of items in this shop: {}".format(item_count-1), level=1) button_rect = pg.Rect(0, 0, 300, 40) centre_screen.fill(BACKGROUND_COLOUR) item_button_list = [] for item_index in range(item_count): y_pos = centre_screen.get_height()/2 - ((item_count/2-item_index) * button_rect.height) if item_index == item_count-1: item_name = "Cancel" else: item_name = data[item_index][ITEM_NAME] if shop_type is TILE_WEAPON_SHOP: item_name += " ATT:" + str(data[item_index][ITEM_POINT]) elif shop_type is TILE_ARMOR_SHOP: item_name += " DEF:" + str(data[item_index][ITEM_POINT]) item_name += " " + str(data[item_index][ITEM_PRICE]) + "G" DEBUG.log("Item name: {}".format(item_name), level=2) item_button = Button( centre_screen, (centre_screen.get_width()/2, y_pos), item_name, 14, rect=button_rect, pos_offset=(TILE_WIDTH, TILE_HEIGHT)) if item_name != "Cancel": try: item_button.insert_picture((0, 0), os.path.join(ITEM_IMG_FILE_PATH, data[item_index][ITEM_FILENAME])) except RuntimeError as e: DEBUG.log(e, level=1) try: item_button.insert_picture((0, 0), 'smile.png') except: raise Exception item_button.update() item_button_list.append(item_button) pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT))) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() for button in item_button_list: button.update_state(event) bought_item = None for button_index in range(len(item_button_list)): if item_button_list[button_index].buttonPressed: DEBUG.log("{}'th button pressed".format(button_index+1), level=2) if item_button_list[button_index].text == "Cancel": DEBUG.log("Cancel clicked", level=2) return else: bought_item = data[button_index] DEBUG.log("Item {} clicked".format(bought_item[ITEM_NAME]), level=2) break if bought_item: if bought_item[ITEM_PRICE] >= self.gold: DEBUG.log("Item too expensive.", level=1) self.show_textbox_at_centre( centre_screen, "You don't have enough gold.", 1500) self.shop_action_buy(centre_screen, data) elif shop_type is TILE_WEAPON_SHOP: DEBUG.log("Buying weapon", level=1) if self.weapon: DEBUG.log("Already have weapon", level=2) self.show_textbox_at_centre( centre_screen, "You're already equipping a weapon. Sell it first.", 1500) # recursion to go back to buy menu self.shop_action_buy(centre_screen, tile_value) else: DEBUG.log("Bought weapon {}".format(bought_item[ITEM_NAME])) self.weapon = bought_item self.current_attack += bought_item[ITEM_POINT] self.gold -= bought_item[ITEM_PRICE] self.show_textbox_at_centre( centre_screen, "You purchased {}!".format(bought_item[ITEM_NAME]), 1500) self.action_result = ACTION_RESULT_SHOP_BUY elif shop_type is TILE_ARMOR_SHOP: DEBUG.log("Buying armor", level=1) if self.armor: DEBUG.log("Already have armor", level=2) self.show_textbox_at_centre( centre_screen, "You're already equipping an armor. Sell it first.", 1500) # recursion to go back to buy menu self.shop_action_buy(centre_screen, tile_value) else: DEBUG.log("Bought weapon {}".format(bought_item[ITEM_NAME])) self.armor = bought_item self.current_defence += bought_item[ITEM_POINT] self.gold -= bought_item[ITEM_PRICE] self.show_textbox_at_centre( centre_screen, "You purchased {}!".format(bought_item[ITEM_NAME]), 1500) self.action_result = ACTION_RESULT_SHOP_BUY else: raise TypeError("Invalid type of item") return
def shop_action_sell(self, centre_screen): item_count = len(self.inventory) + 3 # weapon, armor, inventory, and cancel DEBUG.log("Number of items to sell: {}".format(item_count-1), level=1) button_rect = pg.Rect(0, 0, 300, 40) centre_screen.fill(BACKGROUND_COLOUR) item_button_list = [] for item_index in range(item_count): y_pos = centre_screen.get_height()/2 - ((item_count/2-item_index) * button_rect.height) if item_index == item_count-1: item_name = "Cancel" elif item_index == 0: # weapon if not self.weapon: item_name = "Empty" else: item_name = self.weapon[ITEM_NAME] item_name += " ATT:" + str(self.weapon[ITEM_POINT]) item_name += " " + str(self.weapon[ITEM_PRICE]/4) + "G" elif item_index == 1: if not self.armor: item_name = "Empty" else: item_name = self.armor[ITEM_NAME] item_name += " DEF:" + str(self.armor[ITEM_POINT]) item_name += " " + str(self.armor[ITEM_PRICE]/4) + "G" else: if not self.inventory[item_index-2]: item_name = "Empty" else: item_name = self.inventory[item_index-2][ITEM_NAME] item_name += " " + str(self.inventory[item_index-2][ITEM_PRICE]/4) + "G" DEBUG.log("Item name: {}".format(item_name), level=2) item_button = Button( centre_screen, (centre_screen.get_width()/2, y_pos), item_name, 14, rect=button_rect, pos_offset=(TILE_WIDTH, TILE_HEIGHT)) if item_name is not "Cancel" and item_name is not "Empty": try: if item_index == 0: item_button.insert_picture((0, 0), os.path.join(ITEM_IMG_FILE_PATH, self.weapon[ITEM_FILENAME])) elif item_index == 1: item_button.insert_picture((0, 0), os.path.join(ITEM_IMG_FILE_PATH, self.armor[ITEM_FILENAME])) except RuntimeError as e: DEBUG.log(e, level=1) try: item_button.insert_picture((0, 0), 'smile.png') except: raise Exception item_button.update() item_button_list.append(item_button) pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT))) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() for button in item_button_list: button.update_state(event) sold_item = None for button_index in range(len(item_button_list)): if item_button_list[button_index].buttonPressed: DEBUG.log("{}'th button pressed".format(button_index+1), level=2) if item_button_list[button_index].text == "Cancel": DEBUG.log("Cancel clicked", level=2) return elif button_index == 0 and self.weapon: sold_item = self.weapon DEBUG.log("Item {} clicked".format(sold_item[ITEM_NAME]), level=2) break elif button_index == 1 and self.armor: sold_item = self.armor DEBUG.log("Item {} clicked".format(sold_item[ITEM_NAME]), level=2) break else: #TODO: Implement other items pass if sold_item: if sold_item is self.weapon: DEBUG.log("Selling weapon {}".format(sold_item[ITEM_NAME])) self.weapon = None self.current_attack -= sold_item[ITEM_POINT] elif sold_item is self.armor: DEBUG.log("Selling armor {}".format(sold_item[ITEM_NAME])) self.armor = None self.current_defence -= sold_item[ITEM_POINT] self.gold += sold_item[ITEM_PRICE]/4 self.show_textbox_at_centre( centre_screen, "You sold {}!".format(sold_item[ITEM_NAME]), 1500) self.action_result = ACTION_RESULT_SHOP_SELL return
def showOpCodes(): print('{:<10}\t{:>10}\t{:>20}'.format('OpCode', 'Hex', 'Bin')) for name, member in OpCode.__members__.items(): print('{:<10}\t{:>10}\t{:>20}'.format(name, hex(member.value), bin(member.value))) if __name__ == '__main__': #showOpCodes() #showExampleEncodings() #print() #asm = Assembler('examples/factorial.asm') #asm = Assembler('examples/misc.asm') #asm = Assembler('examples/mul.asm') #asm = Assembler('examples/int.asm') asm = Assembler('examples/mov.asm') #asm = Assembler('examples/br.asm') #print('generated code:') program_memory = asm.parse() #for i in program_memory: # print('0x{0:04X}\t0b{0:016b}'.format(i)) cpu = Cpu(program_memory) seq = Seq(MPM, cpu) #TODO: intreruperi dbg = Debugger(seq) dbg.attach() # print(cpu.__dict__) # print(seq.__dict__)
class RemoteDebugDialog(QtGui.QDialog, FORM_CLASS): def __init__(self, plugin, parent=None): """Constructor.""" super(RemoteDebugDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html#widgets-and-dialogs-with-auto-connect self.setupUi(self) self._plugin = plugin self._debugger = Debugger() @pyqtSlot() def on_pydevd_path_but_clicked(self): pydevd_path = QFileDialog.getExistingDirectory( None, "Select pydev directory containing pydevd.py", self.pydev_path_ledit.text() ) if not pydevd_path: return # dialog canceled self.pydev_path_ledit.setText(pydevd_path) @pyqtSlot() def on_connect_but_clicked(self): self.setCursor(Qt.WaitCursor) try: self.start_debugging() finally: self.unsetCursor() @pyqtSlot() def on_exception_but_clicked(self): # Local vars for testing value display in debugger t01 = QgsApplication.pluginPath() t02 = QgsApplication.svgPaths() # t03 = QChar('x') t04 = QPoint(4, 5) t05 = QPointF(4.1, 5.1) t06 = QDate() t07 = QTime() t08 = QDir() t09 = QFile() t10 = QUrl() x01 = 42 x02 = "fortytwo" raise Exception("Exception raised. Check local variables in your debugger.") def start_debugging(self): debugger = self._debugger.client(self.debugger_cbox.currentIndex()) self._plugin.statusBar().showMessage(u"Connecting to remote debugger...") active = debugger.start_debugging(self._debugger_config()) self._plugin.statusBar().showMessage("") if active: self.accept() self._plugin.push_message(u"Debugging connection activated", duration=2) else: self._plugin.push_message(u"Debugging connection failed", level=1, duration=2) def _debugger_config(self): return {"pydev_path": self.pydev_path_ledit.text()}
class MainWindow(QtGui.QMainWindow): """ Main window of the debugger""" FocusLine = pyqtSignal(str, int, name='FocusLine') def __init__(self): QtGui.QMainWindow.__init__(self) self.init_ui() self.save_restore_state(False) self.cfg_window = RunConfigWindow() self.about_dialog = AboutDialog() self.pty_stdout = PtyView(self.ui.commander) stdout_path = self.pty_stdout.get_file_path() self.debugger = Debugger(stdout_path, stdout_path, self.cfg_window.working_dir) self.ui.commander.set_tab_comp_handler(self.debugger.complete_tab) self.last_highlighted_editor = None self.my_listener = MyListeningThread(self.debugger.dbg, self.FocusLine) self.FocusLine.connect(self.do_focus_line) self.my_listener.StateChanged.connect(self.on_state_changed) self.my_listener.BPChanged.connect(self.on_bp_changed) self.debugger.listener = self.my_listener self.my_listener.start() self.opened_files = {} self.bp_locations = {} args = Qt.qApp.arguments() self.cfg_window.working_dir = os.getcwd() if len(args) > 1: self.do_exe_file_open(args[1]) if len(args) > 2: self.cfg_window.arglist = [str(x) for x in args[2:]] logging.info('Ready') def init_ui(self): """initialize UI""" self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.tabCodeEditor.clear() self.ui.tabCodeEditor.setTabsClosable(True) self.ui.tabCodeEditor.setTabShape(QtGui.QTabWidget.Triangular) # setup frame viewer dock action_frames = self.ui.frame_dock.toggleViewAction() self.ui.menuView.addAction(action_frames) action_frames.setCheckable(True) action_frames.setIcon(QIcon(":/icons/icons/frame.png")) self.ui.frame_viewer.set_focus_signal(self.FocusLine) self.tabifyDockWidget(self.ui.frame_dock, self.ui.value_dock) self.tabifyDockWidget(self.ui.value_dock, self.ui.bp_dock) self.ui.frame_dock.raise_() # setup source file tree dock action_source_tree = self.ui.file_tree_dock.toggleViewAction() self.ui.menuView.addAction(action_source_tree) action_source_tree.setCheckable(True) action_source_tree.setIcon(QIcon(":/icons/icons/directory.png")) self.ui.source_tree.set_open_file_signal(self.FocusLine) self.connect(self.ui.action_Open, QtCore.SIGNAL('triggered()'), self.do_exe_file_open) self.connect(self.ui.action_Run, QtCore.SIGNAL('triggered()'), self.do_run) self.connect(self.ui.action_StepOver, QtCore.SIGNAL('triggered()'), self.do_step_over) self.connect(self.ui.action_StepInto, QtCore.SIGNAL('triggered()'), self.do_step_into) self.connect(self.ui.action_StepOut, QtCore.SIGNAL('triggered()'), self.do_step_out) self.connect(self.ui.btn_frame_up, QtCore.SIGNAL('clicked()'), self.ui.frame_viewer.frame_up) self.connect(self.ui.btn_frame_down, QtCore.SIGNAL('clicked()'), self.ui.frame_viewer.frame_down) self.ui.frame_viewer.set_show_args(self.ui.chk_show_args) self.connect(self.ui.tabCodeEditor, QtCore.SIGNAL('tabCloseRequested(int)'), self.close_tab) self.connect(self.ui.tabCodeEditor, QtCore.SIGNAL('currentChanged(int)'), self.ui.source_tree.set_file_selected) self.connect(self.ui.tabCodeEditor, QtCore.SIGNAL('customContextMenuRequested(QPoint)'), self.show_tab_context_menu) self.ui.action_Exit.triggered.connect(Qt.qApp.quit) self.ui.commander.commandEntered.connect(self.do_command) self.connect(self.ui.action_Run_Config, QtCore.SIGNAL('triggered()'), self.do_config) self.connect(self.ui.action_About, QtCore.SIGNAL('triggered()'), self.show_about) self.ui.frame_viewer.frame_changed.connect(self.ui.value_viewer.show_variables) def show_tab_context_menu(self, point): """ show context menu for tabs""" if point.isNull(): return tab_bar = self.ui.tabCodeEditor.tabBar() idx = tab_bar.tabAt(point) if idx < 0: return editor = self.ui.tabCodeEditor.widget(idx) menu = QMenu(tab_bar) save_action = menu.addAction(QIcon(":/icons/icons/save.png"), 'Save', editor.save) save_action.setEnabled(editor.document().isModified()) menu.exec_(tab_bar.mapToGlobal(point)) def save_restore_state(self, is_save): """ save/restore state to/from config file""" if is_save: SETTINGS.setValue('geometry', self.saveGeometry()) SETTINGS.setValue('windowState', self.saveState()) else: self.restoreState(SETTINGS.value('windowState').toByteArray()) self.restoreGeometry(SETTINGS.value('geometry').toByteArray()) def closeEvent(self, event): """overrided. when close event is triggered""" self.save_restore_state(True) if not (self.debugger.curr_process and self.debugger.curr_process.is_alive): event.accept() return reply = QtGui.QMessageBox.question(self, 'Message', 'Quit?', \ QMessageBox.Yes, QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.my_listener.quit() event.accept() else: event.ignore() def close_tab(self, idx): """ close a tab""" editor = self.ui.tabCodeEditor.widget(idx) if editor.document().isModified(): reply = QtGui.QMessageBox.question(self, 'Message', \ editor.source_file + ' has been modified', \ QMessageBox.Save, QMessageBox.Discard, QMessageBox.Cancel) if reply == QtGui.QMessageBox.Cancel: return if reply == QMessageBox.Save: editor.save() #self.opened_files.remove() #editor.close self.close_src_file(editor.source_file) self.ui.tabCodeEditor.removeTab(idx) def show_about(self): """ show "About" window""" self.about_dialog.show() def do_config(self): """show run-config window""" self.cfg_window.show() def do_exe_file_open(self, exe_filename=None): """open executable""" if not exe_filename: exe_filename = QtGui.QFileDialog.getOpenFileName(self, \ self.tr('Open Executable'), \ '', self.tr('Executable Files (*)')) if exe_filename is None: return main_file, line = self.debugger.open_file(exe_filename) if main_file is not None: self.open_src_file(main_file.fullpath, line) self.ui.action_Run.setEnabled(True) self.my_listener.add_target_broadcaster(self.debugger.target.GetBroadcaster()) self.ui.source_tree.set_root(main_file.GetDirectory(), False) self.exe_filename = exe_filename elif line == 0: logging.info('cannot find entry function') else: logging.info('error opening executable: %s', exe_filename) def do_focus_line(self, filename, line_no): """ slot for focusing line event""" # if line_no is 0, just focus the tab if not filename: editor = None else: filename = str(filename) logging.debug('Focusing [%s]:%d', filename, line_no) if filename not in self.opened_files: self.open_src_file(filename) editor = self.opened_files[filename] if editor is not None: self.ui.tabCodeEditor.setCurrentWidget(editor) if line_no: if self.last_highlighted_editor and self.last_highlighted_editor != editor: # clear previous highlight self.last_highlighted_editor.setExtraSelections([]) editor.focus_line(line_no) self.last_highlighted_editor = editor def on_state_changed(self, state): """slot for state change event""" self.ui.statusBar.update_state(SBDebugger.StateAsCString(state)) process = self.debugger.curr_process steppable = process is not None and process.is_alive and state == lldb.eStateStopped if steppable: self.ui.frame_viewer.show_frame_info(process) else: self.ui.frame_viewer.clear() if process is not None: self.ui.action_StepOver.setEnabled(steppable) self.ui.action_StepInto.setEnabled(steppable) self.ui.action_StepOut.setEnabled(steppable) self.ui.action_Run.setEnabled(state != lldb.eStateRunning) if state == lldb.eStateExited or state == lldb.eStateCrashed \ or state == lldb.eStateSuspended: self.do_focus_line(None, -1) if state == lldb.eStateExited: if process is not None: logging.info('process exited: [%d]:%s', process.GetExitStatus(), process.GetExitDescription()) self.ui.frame_viewer.clear() return def on_bp_changed(self, breakpoint, bp_type): """ handler of breakpoing changing""" self.ui.bp_viewer.update_bp_info(self.debugger.dbg.GetSelectedTarget()) # TODO: might be multiple locations for a BP filename, line_no = self.debugger.getBPLocationFromDesc(breakpoint) if not filename or not line_no: logging.warning('Cannot find location from BP') return if filename not in self.bp_locations: self.bp_locations[filename] = [] if bp_type == lldb.eBreakpointEventTypeAdded: self.bp_locations[filename].append(line_no) elif bp_type == lldb.eBreakpointEventTypeRemoved: if line_no in self.bp_locations[filename]: self.bp_locations[filename].remove(line_no) else: logging.warning('removing non-existed BP ' + filename + ':' + str(line_no)) # TODO: trigger a rescan of all BPs? return else: logging.debug('Unhandled BP event:' + str(bp_type)) return if filename in self.opened_files: lna = self.opened_files[filename].line_number_area lna.breakpoints = self.bp_locations[filename] lna.repaint() def close_src_file(self, name): """ close a source file""" editor = self.opened_files[name] editor.setParent(None) del self.opened_files[name] def open_src_file(self, src_filename, line=0): """show the source file in editor""" if not os.path.isfile(src_filename) or not os.access(src_filename, os.R_OK): logging.warn('Unable to access ' + src_filename) return if src_filename in self.opened_files: return editor = CodeEditor(self.ui.tabCodeEditor) idx = self.ui.tabCodeEditor.addTab(editor, os.path.basename(src_filename)) self.ui.tabCodeEditor.setTabToolTip(idx, src_filename) editor.open_source_file(src_filename) self.opened_files[str(src_filename)] = editor editor.line_number_area.BPToggled.connect(self.toggle_breakpoint) if line > 0: self.do_focus_line(src_filename, line) self.ui.source_tree.set_root(os.path.dirname(src_filename)) #self.debugger.disassemble(src_filename) def toggle_breakpoint(self, line_no): """ control the bp toggling""" sender = self.sender() filename = sender.filename # it should trigger BPChanged signal. self.debugger.toggle_breakpoint(filename, line_no) def do_command(self, cmd): """ on command entered""" cmd = str(cmd) cmds = cmd.split() cmd0 = cmds[0].lower() cmd1 = '' if len(cmds) > 1: cmd1 = cmds[1].lower() if cmd0 == 'r' or cmd0 == 'run' or (cmd0 == 'process' and cmd1 == 'launch'): if cmd0[0] == 'r' or cmd0 == 'run': args = cmds[1:] else: args = cmds[2:] self.do_run(args, True) return msg = self.debugger.execute(cmd0, cmd) self.ui.commander.append(msg) def do_run(self, args=None, from_cmd=False): """ on run command entered""" util.save_run_config(self.exe_filename, self.cfg_window.arglist, self.cfg_window.working_dir) process = self.debugger.run(args, from_cmd, self.cfg_window.arglist) if process is not None: self.my_listener.add_process_broadcaster(process.GetBroadcaster()) def do_step_over(self): """ on step over clicked""" self.debugger.next(True) def do_step_into(self): """ on step into clicked""" self.debugger.next(False) def do_step_out(self): """ on step out of frame""" self.debugger.step_out()
import os import sys from debugger import Debugger if __name__ == '__main__': if os.getuid() != 0: print "Run as root" print "sudo python -m python-cheat.run <pid> [<pid> ...]" sys.exit(-1) if len(sys.argv) < 2: print "sudo python -m python-cheat.run <pid> [<pid> ...]" sys.exit(-1) cheater = Debugger() for pid in sys.argv[1:]: try: pid = int(pid) print "Adding %d" % pid cheater.addProcess(pid, False) except Exception as e: print "Invalid pid %s" % pid print e sys.exit(-1) try: import rlcompleter import atexit home = os.path.expanduser('~')
def test_state_returns_flag_name_if_bit_is_set(self): debugger = Debugger() self.assertEqual("C", debugger.state(1 << CF, CF, "C"))
def test_disableBreakpoint_sets_breakpoint_to_false(self): debugger = Debugger() debugger.setBreakpoint(0x2222) debugger.disableBreakpoint(0x2222) self.assertFalse(debugger.breakpoints[0x2222])
def test_getAddr_correctly_parses_address(self): debugger = Debugger() addr = debugger.getAddr("0x1234") self.assertEqual(0x1234, addr)
def test_clearBreakpoint_sets_breakpoint_to_false(self): debugger = Debugger() debugger.setBreakpoint(0x2222) debugger.clearBreakpoint(0x2222) self.assertTrue(0x2222 not in debugger.breakpoints)
def show_status(self, centre_screen): centre_screen.fill(BACKGROUND_COLOUR) status_rect = pg.Rect( centre_screen.get_width()/3, centre_screen.get_height()/16, centre_screen.get_width()/3, centre_screen.get_height()*7/8 ) status_surface = centre_screen.subsurface(status_rect) status_surface.fill(GRAY) token_image = pg.transform.scale(self.token_image, (status_rect.width/3, status_rect.width/3)) status_surface.blit(token_image, (status_rect.width/3, status_rect.height/12)) current_height = 50+token_image.get_height() name_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render(self.player_name, True, BLACK) status_surface.blit(name_text_surf, name_text_surf.get_rect().move(8, current_height)) current_height += name_text_surf.get_height()+10 level_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render("Lv: {}".format(self.level), True, BLACK) status_surface.blit(level_text_surf, level_text_surf.get_rect().move(8, current_height)) current_height += level_text_surf.get_height()+10 health_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render("HP: {}/{}".format(self.current_health, self.full_health), True, BLACK) status_surface.blit(health_text_surf, health_text_surf.get_rect().move(8, current_height)) current_height += health_text_surf.get_height()+10 attack_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render("ATT: {} + {}".format(self.base_attack, self.current_attack-self.base_attack), True, BLACK) status_surface.blit(attack_text_surf, attack_text_surf.get_rect().move(8, current_height)) current_height += attack_text_surf.get_height()+10 defence_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render("DEF: {} + {}".format(self.base_defence, self.current_defence-self.base_defence), True, BLACK) status_surface.blit(defence_text_surf, defence_text_surf.get_rect().move(8, current_height)) current_height += defence_text_surf.get_height()+10 weapon_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render("Weapon: {}".format(self.weapon[ITEM_NAME] if self.weapon else "None"), True, BLACK) status_surface.blit(weapon_text_surf, weapon_text_surf.get_rect().move(8, current_height)) if self.weapon: try: weapon_image = pg.image.load(os.path.join(MONSTER_IMG_FILE_PATH, self.weapon[ITEM_FILENAME])) except RuntimeError as e: DEBUG.log(e, level=1) try: weapon_image = pg.image.load('smile.png') except: raise Exception finally: weapon_image = pg.transform.scale(weapon_image, (weapon_text_surf.get_height(), weapon_text_surf.get_height())) status_surface.blit(weapon_image, weapon_image.get_rect().move(80, current_height)) current_height += weapon_text_surf.get_height()+10 armor_text_surf = pg.font.Font('freesansbold.ttf', 15)\ .render("Armor : {}".format(self.armor[ITEM_NAME] if self.armor else "None"), True, BLACK) status_surface.blit(armor_text_surf, armor_text_surf.get_rect().move( 10, current_height)) if self.armor: try: armor_image = pg.image.load(os.path.join(MONSTER_IMG_FILE_PATH, self.armor[ITEM_FILENAME])) except RuntimeError as e: DEBUG.log(e, level=1) try: armor_image = pg.image.load('smile.png') except: raise Exception finally: armor_image = pg.transform.scale(armor_image, (armor_text_surf.get_height(), armor_text_surf.get_height())) status_surface.blit(armor_image, armor_image.get_rect().move(80, current_height)) pg.display.update(centre_screen.get_rect(topleft=(TILE_WIDTH, TILE_HEIGHT))) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() elif event.type == pg.MOUSEBUTTONDOWN or (event.type == pg.KEYDOWN and event.key == pg.K_RETURN): DEBUG.log("Exiting player status", level=2) centre_screen.fill(BACKGROUND_COLOUR) return
def test_setBrakpoint_adds_a_breakpoint(self): debugger = Debugger() debugger.setBreakpoint(0x1111) self.assertTrue(debugger.breakpoints[0x1111])