示例#1
0
 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)
示例#2
0
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()
示例#3
0
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!")
示例#4
0
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)
示例#5
0
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()
示例#6
0
    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)
示例#7
0
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()
示例#8
0
    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()
示例#9
0
 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)
示例#10
0
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
示例#11
0
    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)
示例#12
0
 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)
示例#13
0
 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()
示例#14
0
 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()
示例#15
0
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()
示例#16
0
 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)
示例#17
0
 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)
示例#18
0
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()
示例#19
0
 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)
示例#20
0
    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 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()
示例#22
0
    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
示例#23
0
 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
示例#24
0
    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()
示例#25
0
 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
示例#26
0
    def least(self, x_rand):  # type: (StateNode) -> StateNode
        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_least = self.root
        else:
            nodes = filter(lambda x: self.collision_free(x, x_rand),
                           self.vertices)
            if nodes:
                costs = list(map(lambda x: x.g + self.cost(x, x_rand), nodes))
                x_least = nodes[int(np.argmin(costs))]
            else:
                x_least = None
        if x_least:
            replenish(x_least, x_rand)
            Debugger().debug_nearest_searching(x_least.state,
                                               switch=self.debug)
        return x_least
    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)
示例#28
0
#Timex 2048
from cpu import CPU
from rom import ROM
from loggers import Logger
from debugger import Debugger
import sys
import getopt

if __name__ == '__main__':
    argv = sys.argv[1:]
    options, args = getopt.getopt(argv, "",
                                  ["attach-logger", "rom=", "mapAt="])
    debugger = Debugger()
    debugger.setBreakpoint(0x100)

    attach_logger = False
    rom_loaded = False
    mapAt = 0x0
    rom = ROM()
    for name, value in options:
        if name == '--mapAt':
            mapAt = int(value, 16)
            rom = ROM(mapAt=mapAt)
            print(f'[+] Mapping ROM at 0x{mapAt:4X}.')
        if name == '--rom':
            rom.loadFrom(value, False)
            print(f'[+] ROM loaded from {value}.')
            rom_loaded = True
        if name == '--attach-logger':
            attach_logger = True
            print(f'[+] Logger attached.')
示例#29
0
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('~')
示例#30
0
文件: main.py 项目: karust/emma
from debugger import Debugger
from helpers import Processes

if __name__ == "__main__":
    dbg = Debugger()
    print("File loaded:", dbg.loadFile("Debugger.dll"))

    procs = Processes()
    print("Number of processes: ", procs.getNumProcs())
    print("Process IDs: ", procs.getPIDs())
    print("Process info: ", procs.getProcInfo(72))
    #for p in procs.getPIDs():
    #    print(p,") Process info: ", procs.getProcInfo(p))