예제 #1
0
    def finish_auction(self):
        # Refund
        if len(self.bids) == 0:
            if self.auction.seller != SELLER:
                self.give_item(self.seller)

            return True

        # Buyer
        if not self.auction.is_buy_now or self.auction.buyer_id == 0:
            bid = self.bids[0]
            self.buyer = Engine(DummyRequest(bid.buyer.id))
            self.buyer.start()
            self.buyer.user.profile.earn('cash', bid.max_price - bid.price)

            bid.is_refunded = True
            bid.save()
        else:
            self.buyer = Engine(DummyRequest(self.auction.buyer_id))
            self.buyer.start()

        self.give_item(self.buyer)

        # Seller
        if not self.auction.is_buy_now or self.auction.buyer_id == 0:
            price = self.auction.current_price
            self.seller.user.profile.earn('cash', self.auction.current_price)
        else:
            price = self.auction.buy_it_now_price
            self.seller.user.profile.earn('cash', self.auction.buy_it_now_price)

        self.seller.notify.add(type='auction', key='income', value=price, date=None)
        self.buyer.notify.add(type='auction', key='outcome', value=price, date=None)
        self.seller.notify.add(type='auction', key='transaction', value=1, date=None)
        self.buyer.notify.add(type='auction', key='transaction', value=1, date=None)

        if len(self.bids) == 1: return True

        if not self.auction.is_buy_now or self.auction.buyer_id == 0:
            self.bids = self.bids[1:]

        for bid in self.bids:
            if bid.is_refunded == True: continue

            profile = UserProfile.objects.get_by_id(bid.buyer.id)
            profile.earn('cash', bid.max_price)
            bid.is_refunded = True
            bid.save()
예제 #2
0
def test_click_bomb():
    e = Engine(10, 10, 10)
    for i in range(10):
        for j in range(10):
            if not e.check_location(i, j):
                return
    assert False, "Clicking bomb spaces did not return false."
예제 #3
0
파일: main.py 프로젝트: Torellin/PiTable
def main():
    # Init first "game" on screen
    print("Start")
    game = games.Home()

    # Check if running on pi
    try:
        import RPi.GwwPIO as gpio

        from display.stripDisplay import StripDisplay
        display = StripDisplay()

    except (ImportError, RuntimeError):
        from display.pygamePixelDisplay import PygamePixelDisplay
        display = PygamePixelDisplay(caption="PiTable Emulator",
                                     gridSize=[16, 16],
                                     width=1000,
                                     height=1000,
                                     space=2)

    screensaver = games.Anim()

    # Init Engine
    engine = Engine(game, screensaver, display)
    engine.init()
    engine.run()
예제 #4
0
    def test_longer_runs_are_better(self):
        e = Engine(
            'CoinPoker', 1,
            {
                1: {'name': 'joe', 'balance': 1000, 'status': 1},
                2: {'name': 'jane', 'balance': 1000, 'status': 1},
            },
            50, 100, 0,
        )
        e.available_actions()

        mc = MonteCarlo(e, 1)
        mc.run(10)
        assert len(mc.current_actions) > 0
        total_traversions = sum(a[2] for a in mc.current_actions)
        assert total_traversions > 1, 'Must have traversed something!'

        total_traversions_batches = 0
        for n in range(1, 11):
            mc = MonteCarlo(e, 1)
            mc.run(1)
            assert len(mc.current_actions) > 0
            total_traversions_batches += sum(a[2] for a in mc.current_actions)
            assert total_traversions_batches > 1, 'Must have traversed something!'

        assert total_traversions > total_traversions_batches
예제 #5
0
파일: main.py 프로젝트: PlumpMath/meo_tech
    def __init__(self):

        # Create the main app Log file
        log.basicConfig(filename="MeoTech.log",
                        level=log.DEBUG,
                        format="%(asctime)s %(levelname)s: %(message)s",
                        datafmt="%d-%m-%Y %H:%M:%S")

        # Init Panda
        ShowBase.__init__(self)

        # Init Engine
        self.engine = Engine(self)

        # Init Game
        self.game = Game(self)

        # Debug stuff
        wantDebug = True

        if wantDebug:
            self.engine.showBulletDebug()
            print " "
            print "Panda Render.ls()"
            print "--------------------------------------------------------"
            print render.ls()
            print "--------------------------------------------------------"
예제 #6
0
def test_toggle_flag():
    e = Engine(10, 10, 10)
    orig_space = e.get_display_board()[0, 0]
    e.toggle_flag(0, 0)
    assert e.get_display_board()[0, 0] == Spaces.FLAG
    e.toggle_flag(0, 0)
    assert e.get_display_board()[0, 0] == orig_space
예제 #7
0
    def __init__(self):

        welcome("Server")

        config.arguments = Arguments()
        config.file_manager = File_Manager(dir=config.arguments.destination)

        config.graphical_user_interface = GUI()

        config.engine = Engine(self)

        fps_counter = FPS_extractor()
        data_acquisition = DAQ_extractor(config.file_manager.new_folderpath)

        extractors = [fps_counter, data_acquisition]
        config.engine.load_extractors(extractors)

        try:
            print("Initiating tracking via {}".format(
                config.arguments.importer))
            import_command = "from importers.{} import Importer".format(
                config.arguments.importer)

            exec(import_command, globals())

        except Exception as e:
            print("Invalid importer selected.\n", e)

        config.importer = Importer()
        config.importer.start()
        config.importer.route()
예제 #8
0
    def load_game(file_path,
                  is_save,
                  scr_wd=80,
                  scr_ht=40,
                  fov_mode=False,
                  debug=False):
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)

        if is_save:
            engine = Serializer.deserialize_engine(data)
        else:
            engine = Engine(screen_width=scr_wd,
                            screen_height=scr_ht,
                            fov_mode=fov_mode,
                            debug=debug)
            engine.map.walls = []
            engine.map.free_all_cells()
            for x, y in data['coords']:
                new_wall = Wall(x, y, 1, 1)
                engine.map.walls.append(new_wall)
                engine.map.cells[y][x].block()

            engine.player = EngineInitializer.init_player(
                engine, engine.load_type)
            engine.mobs = EngineInitializer.init_entities(
                engine, engine.load_type)

        return engine
예제 #9
0
    def __init__(self):

        welcome("Server")

        arguments = Arguments()
        file_manager = File_Manager(dir=arguments.destination)
        print(arguments.video)
        graphical_user_interface = GUI()

        ENGINE = Engine(self, graphical_user_interface, file_manager,
                        arguments)

        fps_counter = FPS_extractor()
        data_acquisition = DAQ_extractor(file_manager.new_folderpath)

        extractors = [fps_counter, data_acquisition]
        ENGINE.load_extractors(extractors)

        try:
            print("Initiating tracking via {}".format(arguments.importer))
            import_command = "from importers.{} import Importer".format(
                arguments.importer)
            exec(import_command, globals())
        except Exception as e:
            print("Invalid importer selected.\n", e)

        importer = Importer(ENGINE)

        importer.route()
예제 #10
0
def main(library_file: str, scenario_file: str, query_file: str = None):
    domain_desc = parsing.domain_description.parse_file(library_file)
    print('Parsed domain description:')
    for statement in domain_desc.statements:
        print(statement)
    scenario = parsing.scenario.parse_file(scenario_file)
    print('Parsed scenario:')
    for statement in scenario.observations:
        print(statement)
    for statement in scenario.action_occurrences:
        print(statement)
    queries = parsing.query.parse_file(query_file)
    print('Parsed queries:')
    for statement in queries:
        print(statement)
    engine = Engine()

    if len(queries) == 0:
        print("The library and the scenario are valid.")

    if engine.run(scenario=scenario, domain_desc=domain_desc):
        print('After the engine ran We found', len(engine.models), 'models')
        i = 0
        for model in engine.models:
            print('Final model:', i, '\n', model)
            print('Action history for model', i, 'is:', model.action_history)
            i += 1
        if len(engine.models) != 0:
            for query in queries:
                print('Query:', query, 'was evaluated to:', query.validate(engine.models, scenario))
        else:
            for query in queries:
                print('Query:', query, 'was evaluated to:', query.validate(engine.models, scenario))
예제 #11
0
 def test_player_stats(self):
     e = Engine(
         'CoinPoker',
         1,
         {
             1: {
                 'name': 'joe',
                 'balance': 1000,
                 'status': 1
             },
             2: {
                 'name': 'jane',
                 'balance': 1000,
                 'status': 1
             },
         },
         50,
         100,
         0,
     )
     e.available_actions()
     stats = ES.player_stats(e, e.s)
     assert 'actions' in stats
     assert len(stats['actions']) >= 4
     assert 0 < stats['hs'] < 100
예제 #12
0
def autopilot_mode():
    print("Autopilot mode has been activated.")
    configuration_parser.read('./config/configuration.txt')
    configuration = configuration_parser['Files']
    counter = read_actions(configuration)
    engine = Engine(configuration, counter, actions)
    engine.execute()
예제 #13
0
def launch_engine():
    if request.method == 'POST' and check_request(request.json):

        url = request.json['url']
        username = request.json['username']
        password = request.json['password']
        location = request.json['location']
        text = ScraperManager().get_text_content(url)

        # if the scrap is too long
        if text is None:
            return json.dumps({'send': False, 'error': 'scrap'})

        engine = Engine(text=text,
                        username=username,
                        password=password,
                        location=location)
        data = engine.run()
        if data is not None:
            return json.dumps({
                'send': True,
                'success': True,
                'text': data.get('text'),
                'pure': data.get('pure'),
                'yago': data.get('yago')
            })

        return json.dumps({'send': True, 'success': False})

    return json.dumps({'send': False, 'error': 'error'})
예제 #14
0
def test_click_safe():
    b1 = np.array([[Spaces.BOMB, Spaces.UNKNOWN], [Spaces.BOMB, Spaces.BOMB]])
    e = Engine(10, 10, 1)
    e._board = b1
    e._width = 2
    e._height = 2
    e._first_move = True
    e.check_location(0, 1)
    assert e.get_real_board()[0, 0] == Spaces.BOMB
    assert e.get_real_board()[1, 0] == Spaces.BOMB
    assert e.get_real_board()[1, 1] == Spaces.BOMB
    assert e.get_real_board()[0, 1] == Spaces.THREE

    b2 = np.array([[Spaces.UNKNOWN, Spaces.UNKNOWN, Spaces.BOMB],
                   [Spaces.UNKNOWN, Spaces.UNKNOWN, Spaces.BOMB],
                   [Spaces.UNKNOWN, Spaces.UNKNOWN, Spaces.BOMB]])
    e._board = b2
    e._width = 3
    e._height = 3
    e._first_move = True
    e.check_location(0, 0)
    assert e.get_real_board()[0, 0] == Spaces.ZERO
    assert e.get_real_board()[0, 1] == Spaces.TWO
    assert e.get_real_board()[0, 2] == Spaces.BOMB
    assert e.get_real_board()[1, 0] == Spaces.ZERO
    assert e.get_real_board()[1, 1] == Spaces.THREE
    assert e.get_real_board()[1, 2] == Spaces.BOMB
    assert e.get_real_board()[2, 0] == Spaces.ZERO
    assert e.get_real_board()[2, 1] == Spaces.TWO
    assert e.get_real_board()[2, 2] == Spaces.BOMB
예제 #15
0
def test_click_flag():
    e = Engine(10, 10, 1)
    orig_space = e.get_display_board()[0, 0]
    e.toggle_flag(0, 0)
    assert e.get_display_board()[0, 0] == Spaces.FLAG
    e.check_location(0, 0)
    assert e.get_display_board()[0, 0] == orig_space
예제 #16
0
 def test_three_initial_model_case(self):
     scenario = parsing.scenario.parse_file(
         "../test_models/three_initial_model_case_scenario.txt")
     domain = parsing.domain_description.parse_file(
         "../test_models/three_initial_model_case_domain.txt")
     engine = Engine()
     engine.run(scenario, domain)
     self.assertEqual(3, len(engine.models))
예제 #17
0
 def test_model_destruction_observation_case(self):
     scenario = parsing.scenario.parse_file(
         "../test_models/model_destruction_observation_case_scenario.txt")
     domain = parsing.domain_description.parse_file(
         "../test_models/model_destruction_observation_case_domain.txt")
     engine = Engine()
     engine.run(scenario, domain)
     self.assertEqual(0, len(engine.models))
예제 #18
0
def parse_and_export():
    engine = Engine()
    c = engine.get_all_collectors()
    logging.debug("Engine_invoker: parsing data")
    engine.parse_all_collectors_data()
    logging.debug("Engine_invoker: exporting data")
    engine.export('/root/Desktop/')
    logging.debug("Engine_invoker: Complete. Exiting")
예제 #19
0
 def test_model_impossible_condition_case(self):
     scenario = parsing.scenario.parse_file(
         "../test_models/model_impossible_condition_case_scenario.txt")
     domain = parsing.domain_description.parse_file(
         "../test_models/model_impossible_condition_case_domain.txt")
     engine = Engine()
     engine.run(scenario, domain)
     self.assertEqual(1, len(engine.models))
예제 #20
0
def main(clean_directory="resources/clean_data"):
    initial_time = time.time()

    clean_files = [
        f for f in listdir(clean_directory)
        if isfile(join(clean_directory, f)) and "2" in f
    ]

    for file in clean_files:
        results = []
        print(f"processing {file} file")
        dataset = Dataset(f"{clean_directory}/{file}")

        data_points = dataset.get_data()

        count = 1
        for data_point in data_points:
            start = time.time()
            print(f"\tlooking at {count}:{len(data_points)}")
            chess_engine = Engine(data_point.board,
                                  data_point.color,
                                  depth=data_point.mate_in * 2,
                                  algorithm="alpha-beta")
            result_moves = chess_engine.find_next_move()

            moves_to_mate = len(result_moves) // 2 + 1

            duration = (time.time() - start)
            print(
                f"\t\tfound mate in {moves_to_mate} moves; expecting {data_point.mate_in} in {duration} seconds"
            )

            result_moves_string = [str(move) for move in result_moves]

            results.append(
                (data_point.board.fen(), "->".join(result_moves_string),
                 moves_to_mate, data_point.mate_in, duration))

            count += 1
            # if count > 10:
            #     break

        output_name = file.split("/")[-1].split(".")[0]
        output_path = f"resources/results/{output_name}_results.csv"

        print(f"downloading results to {output_path}")
        with open(output_path, "w") as f:
            f.write(
                "fen,sequence_of_moves,found_mate,best_mate,difference,compute_duration\n"
            )

            for result in results:
                f.write(
                    f"{result[0]},{result[1]},{result[2]},{result[3]},{int(result[3]) - result[2]},{result[4]}\n"
                )

    print("_" * 80)
    print(f"total time: {(time.time() - initial_time)/60} minutes")
예제 #21
0
 def parse(self):
     if(os.name == "nt"):
         subprocess.Popen([self.script_file, self.click_dir, self.parsed_folder], cwd=os.path.dirname(os.path.realpath(__file__)))
     else:
         e = Engine()
         e.incNumParsersRunning()
         s = subprocess.Popen([self.script_file, self.click_dir, self.parsed_folder],shell=False)
         (out, err) = s.communicate()
         e.decNumParsersRunning()
예제 #22
0
def test_display_board():
    b1 = np.array([[Spaces.BOMB, Spaces.UNKNOWN], [Spaces.BOMB, Spaces.BOMB]])
    e = Engine(10, 10, 10)
    e._board = b1
    dboard = e.get_display_board()
    assert dboard[0, 0] == Spaces.UNKNOWN
    assert dboard[0, 1] == Spaces.UNKNOWN
    assert dboard[1, 0] == Spaces.UNKNOWN
    assert dboard[1, 1] == Spaces.UNKNOWN
예제 #23
0
 def setUp(self):
     self.controller_1 = ManualController(0)
     self.controller_2 = ManualController(1)
     self.user_1 = User(0, self.controller_1)
     self.user_2 = User(1, self.controller_2)
     self.engine = Engine()
     self.engine.add_user(self.user_1)
     self.engine.add_user(self.user_2)
     self.engine.deck = Deck(shuffle=False, is_small=False)
예제 #24
0
def starter(default_screen=True, fov_mode=False, debug=False):
    scr_wd, scr_ht = 80, 40
    if not default_screen:
        scr_wd = int(input("Please, input the screen width:  "))
        scr_ht = int(input("Please, input the screen height: "))

    if os.path.isfile('media/GAME_SAVE.json'):
        new_or_save = str(
            input(
                'Load save game - print 2, load SD-map - print 1, new game - 0: '
            ))
        if new_or_save == '2':
            return Serializer.load_game('media/GAME_SAVE.json',
                                        is_save=True,
                                        scr_wd=scr_wd,
                                        scr_ht=scr_ht,
                                        fov_mode=fov_mode,
                                        debug=debug)
        elif new_or_save == '1':
            return Serializer.load_game('media/SD_MAP.json',
                                        is_save=False,
                                        scr_wd=scr_wd,
                                        scr_ht=scr_ht,
                                        fov_mode=fov_mode,
                                        debug=debug)

        return Engine(screen_width=scr_wd,
                      screen_height=scr_ht,
                      fov_mode=fov_mode,
                      debug=debug)

    new_or_load = str(input('Load SD-map - print 1, new game - 0: '))
    if new_or_load == '1':
        return Serializer.load_game('media/SD_MAP.json',
                                    is_save=False,
                                    scr_wd=scr_wd,
                                    scr_ht=scr_ht,
                                    fov_mode=fov_mode,
                                    debug=debug)

    return Engine(screen_width=scr_wd,
                  screen_height=scr_ht,
                  fov_mode=fov_mode,
                  debug=debug)
예제 #25
0
    def test_showdown_hs(self):
        e = Engine(
            'CoinPoker',
            1,
            {
                1: {
                    'name': 'joe',
                    'balance': 1000,
                    'status': 1
                },
                2: {
                    'name': 'joe',
                    'balance': 1000,
                    'status': 1
                },
            },
            50,
            100,
            0,
        )
        e.available_actions()

        # p1
        e.do(['r', 100])
        e.available_actions()

        # p2
        e.do(['c'])
        e.available_actions()

        # p2
        e.do(['k'])
        e.available_actions()

        # p1
        e.do(['b', 200])
        e.available_actions()

        # p2 has:
        # preflop_1 = l
        # preflop_2 = c
        # flop_1 = k
        hs = ES.showdown_hs(e, e.s, percentile=50)
        assert hs is not None
        assert 0 < hs < 1
        hs2 = ES.showdown_hs(e, e.s, percentile=10)
        assert hs2 < hs
        hs3 = ES.showdown_hs(e, e.s, percentile=90)
        assert hs3 > hs

        res = ES.showdown_hs(e, e.s, 200)
        hits = res.hits.hits
        assert len(hits) == 200
        assert hits[0]['_score'] > 4
        assert hits[-1]['_score'] > 0
예제 #26
0
    def __init__(self, table):
        '''
        Create an engine for this game
        monte carlo will use the engine instances for iterations
        Game will only keep track of this current game

        First get actions from engine, then the repr
        '''
        self.engine = Engine(table.site_name, table.button, table.players, table.sb, table.bb)
        self.history = {}
        self.cursor = 0
예제 #27
0
    def __init__(self):
        self.preprocess = PreProcessing()
        self.engine = Engine()

        # model
        model = self.engine.nn_train_fit()

        test_data = self.preprocess.get_test_data()
        prediction = model.predict(test_data)
        print(prediction)
        self.save_submit(prediction)
def start_threads():
    global frozen
    if not frozen:
        return 'Already running'
    frozen = False

    for i in range(1):
        e = Engine(event=event, tid=i)
        e.start()
        threads.append(e)
    return 'Started'
예제 #29
0
 def _generate_one_scenerio(self):
     self._games += 1
     if self._games % 1000 == 0:
         print('{:,} complete'.format(self._games))
     self._engine = Engine(12, 12, 30)
     first_move = np.floor(
         np.multiply(np.random.rand(1, 2), np.array([[10,
                                                      10]]))).astype(int)[0]
     self._engine.check_location(first_move[0], first_move[1])
     daters = [self._get_next_data(self._engine) for i in range(10)]
     return daters
예제 #30
0
def execute_tshark_stop():
    logging.getLogger().setLevel(logging.DEBUG)
    logging.debug('Stopping Program')
    logging.debug("Engine_invoker: getting engine instance")
    engine = Engine()
    logging.debug("Engine_invoker: invoking print_collector_names")
    engine.print_collector_names()
    logging.debug("Engine_invoker: obtaining tshark collector")
    c = engine.get_collector("tshark")
    logging.debug("Engine_invoker: stopping collector")
    engine.stop_collector(c)