예제 #1
0
    def test_saves_fp_on_locals(self):
        files = {'dummy.txt': 'oi'}
        console = Console(files=files)
        code = "fd = open('dummy.txt')"
        console.run_tests(code, TEST_CODE)

        locals_ = console.get_locals()
        json_data = pickle.dumps(locals_)
        new_locals = pickle.loads(json_data)
        console = Console(locals_=new_locals)
        code = "print fd.read()"
        console.run_tests(code, TEST_CODE)
        self.assertEqual('oi\n', console.output)
예제 #2
0
파일: chatbot.py 프로젝트: tp6fu6m3/Chatbot
 def __init__(self, isChat):
     self.speech_domain = ''
     self.isChat = isChat
     if isChat:
         self.console = Console()
     self.answerer = Answerer()
     self.default_response = ['是嗎?', '有道理', '我認同', '我不太明白你的意思', '原來如此']
예제 #3
0
 def __init__(self):
     """Inicjalizacja gry"""
     self._current_player = Player("Adam", Color.White)
     self._next_player = Player("Eve", Color.Black)
     self._console = Console()
     self._board = Chessboard()
     self._board.init()
예제 #4
0
 def __init__(self):
   self._cursor = (1, 1)
   self._start = (1, 1)
   self._goal = (33, 8)
   self._console = Console()
   self._map = Map()
   self._astar = AStar(self._map.cost)
예제 #5
0
 def __init__(self, hints_file="../resource/hints.json"):
     self.problem_template = ProblemTemplate()
     self.io_helper = IOHelper()
     self.console = Console()
     self.problem_metadata = problem_metadata
     with open(hints_file, "r", encoding="utf-8") as f:
         self.hints_json = json.load(f)
예제 #6
0
def init():
    global console
    from plugin import config_manager
    console = Console(
        interpreter_locals=dict(pm=plugin_manager,
                                cm=config_manager,
                                console_command=ConsoleCommands()))
예제 #7
0
    def __init__(self):
        """ Start up the game window and initialize game resources """

        pygame.init()

        # Get game settings
        self.settings = Settings()

        # Set up the display
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Mission X")
        self.console = Console(self)

        # Start storing game statistics
        self.stats = GameStats(self)

        # Attach appropriate groups to respective variables
        self.ship = Ship(self)
        self.rockets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.stars = pygame.sprite.Group()

        # Make play button
        self.play_button = Button(self, 'Play')
예제 #8
0
 def __init__(self):
     """
     Pull all variables from config.py file.
     """
     self.player = Player()
     self.database = config.database
     self.Max_point_tournament = config.Max_point_tournament
     self.BotNet_update = config.BotNet_update
     self.joinTournament = config.joinTournament
     self.tournament_potator = config.tournament_potator
     self.booster = config.booster
     self.Use_netcoins = config.Use_netcoins
     self.attacks_normal = config.attacks_normal
     self.updates = config.updates
     self.updatecount = config.updatecount
     self.maxanti_normal = config.maxanti_normal
     self.active_cluster_protection = config.active_cluster_protection
     self.mode = config.mode
     self.stat = "0"
     self.wait_load = config.wait_load
     self.c = Console(self.player.username, self.player.password)
     self.u = Update(self.player.username, self.player.password)
     self.b = Botnet(self.player)
     self.ddos = ddos.Ddos()
     self.init()
예제 #9
0
파일: tests.py 프로젝트: mmassad/Black_Jack
def four_splits():
    game = Game()
    game.console = Console()
    game.deck = Deck()
    game.deck.cards[2:14] = [
        Card("9", "Spades", False),
        Card("9", "Clubs", False),
        Card("9", "Hearts", False),
        Card("9", "Diamonds", False),
        Card("9", "Spades", False),
        Card("2", "Clubs", False),
        Card("3", "Hearts", False),
        Card("4", "Diamonds", False),
        Card("5", "Spades", False),
        Card("6", "Clubs", False),
        Card("7", "Hearts", False),
        Card("8", "Diamonds", False)
    ]

    game.dealer = Dealer("Table", [])
    game.dealer.hit(game.deck)
    game.dealer.hit(game.deck)

    game.player = Player("Player 0", 10, [[]])
    game.player.hit(game.deck, 0)
    game.player.hit(game.deck, 0)

    game.console.print_table(game.dealer, game.player)
    game.player_turn(game.player, 0)
예제 #10
0
파일: tests.py 프로젝트: mmassad/Black_Jack
def winner_with_split_hand():
    # Testing winner function when player has multiple hands
    console = Console()
    dealer = Dealer("Table", [
        Card("A", "Spades", False),
        Card("3", "Spades", False),
        Card("4", "Spades", False)
    ])
    dealer.points = 18

    player_test = Player(
        "Player 0", 2,
        [[Card("J", "Spades", False),
          Card("7", "Spades", False)],
         [
             Card("10", "Spades", False),
             Card("4", "Spades", False),
             Card("9", "Spades", False)
         ], [Card("A", "Spades", False),
             Card("Q", "Spades", False)],
         [
             Card("2", "Spades", False),
             Card("8", "Spades", False),
             Card("8", "Spades", False)
         ]])
    player_test.bet = [2, 2, 2, 2]
    player_test.points = [17, 23, 21, 18]

    print(" Chips: \t" + str(player_test.chips) + "\t")
    dealer.check_winner(player_test)
    print(" Chips: \t" + str(player_test.chips) + "\t")
예제 #11
0
    def __init__(self):
        """
        Pull all variables from config.py file.
        """

        self.player = Player()
        self.database = config.database
        self.Max_point_tournament = config.Max_point_tournament
        self.BotNet_update = config.BotNet_update
        self.joinTournament = config.joinTournament
        self.tournament_potator = config.tournament_potator
        self.booster = config.booster
        self.Use_netcoins = config.Use_netcoins
        self.attacks_normal = config.attacks_normal
        self.updates = config.updates
        self.updatecount = config.updatecount
        self.maxanti_normal = config.maxanti_normal
        self.active_cluster_protection = config.active_cluster_protection
        self.mode = config.mode
        self.number_task = config.number_task
        self.min_energy_botnet = config.minimal_energy_botnet_upgrade
        self.stat = "0"
        self.wait_load = config.wait_load
        self.c = Console(self.player)
        self.u = Update(self.player)
        # disable botnet for > api v13
        self.b = Botnet(self.player)
        self.ddos = ddos.Ddos(self.player)
        self.m = Mails(self.player)
        self.init()
예제 #12
0
 def setUp(self):
     self.credentials_json = json.dumps({
         'sessionId': 'id',
         'sessionKey': 'key',
         'sessionToken': 'token'
     })
     self.c = Console()
예제 #13
0
    def __init__(self):
        self.width = getWidth()
        self.height = getHeight()

        self.fps = getFPS()
        self.bubbleCount = int(getWidth() / 160)
        self.drawBubbles = True
        self.drawBG = True

        pygame.init()
        self.fpsClock = pygame.time.Clock()
        if fullscreen():
            self.windowSurfaceObj = pygame.display.set_mode(
                (self.width, self.height), pygame.FULLSCREEN)
        else:
            self.windowSurfaceObj = pygame.display.set_mode(
                (self.width, self.height))
        pygame.display.set_caption('Anim')

        pygame.mouse.set_visible(cursor())

        for i in range(0, self.bubbleCount):
            self.entitylist[2].append(Bubble(True))
            self.entitylist[0].append(Bubble(False))

        self.player = Player()
        self.entitylist[1].append(self.player)
        self.background = Background()

        print('Init...')
        self.console = Console(getWidth(), getHeight())
        Console.host = self
        self.DrawPosVector = False
예제 #14
0
def solve_two(boot_code):
    console = Console(boot_code)

    # identify jmp indices
    jmps, nops = [], []
    
    i = 0
    while i < len(console.boot_code):
        instruction = console.boot_code[i]
        if instruction.operation == 'jmp':
            jmps.append(i)
        elif instruction.operation == 'nop':
            nops.append(i)
        i+= 1

    # brute force replace
    for i in (jmps + nops):
        instruction = console.boot_code[i]
        instruction.operation = 'nop 'if i in jmps else 'jmp'
        console.boot_code[i] = instruction

        if console.boot():
            logging.info(f'Accumulator: {console.accumulator}')
            return console.accumulator
        else:
            # reset console
            console.reset()
    return
예제 #15
0
 def __init__(self):
     self.console = Console()
     self.landscape = Landscape()
     self.display = Display(self.landscape, self.console)
     self.control = Controller(self.console)
     self.cursorX = 2
     self.cursorY = 2
예제 #16
0
 def __init__(self):
     self.titulo = ''
     self.recursosMaximos = []
     self.recursosAlocados = []
     self.recursosNecessarios = []
     self.__console = Console()
     self.__finalizado = False
예제 #17
0
def explore(fpath):
    _, ext = splitext(fpath)
    ftype = 'data' if ext in ('.h5', '.hdf5') else 'simulation'
    print("Using {} file: '{}'".format(ftype, fpath))
    if ftype == 'data':
        globals_def, entities = entities_from_h5(fpath)
        simulation = Simulation(globals_def, None, None, None, None,
                                entities.values(), 'h5', fpath, None)
        period, entity_name = None, None
    else:
        simulation = Simulation.from_yaml(fpath)
        # use output as input
        simulation.data_source = H5Source(simulation.data_sink.output_path)
        period = simulation.start_period + simulation.periods - 1
        entity_name = simulation.default_entity
    dataset = simulation.load()
    data_source = simulation.data_source
    data_source.as_fake_output(dataset, simulation.entities_map)
    data_sink = simulation.data_sink
    entities = simulation.entities_map
    if entity_name is None and len(entities) == 1:
        entity_name = entities.keys()[0]
    if period is None and entity_name is not None:
        entity = entities[entity_name]
        period = max(entity.output_index.keys())
    eval_ctx = EvaluationContext(simulation, entities, dataset['globals'],
                                 period, entity_name)
    try:
        c = Console(eval_ctx)
        c.run()
    finally:
        data_source.close()
        if data_sink is not None:
            data_sink.close()
예제 #18
0
 def test_run(self):
     print('test run')
     console = Console(None)
     mock_state = MockState()
     console.add_state('mock', mock_state)
     console.set_current_state('mock')
     console.run()
예제 #19
0
def main(stdscr):
    cw.init(stdscr)

    tag_manager = TagManager()
    tag_manager.__from_json__(json.load(open(FILE_DB)))

    menu = Menu(stdscr, tag_manager)
    # menu.items = [item1, item2, item3, link, file]

    console = Console(stdscr)
    console.menu = menu

    status = NEED_KEY
    while NEED_KEY == status:

        stdscr.clear()

        menu.render()
        console.render()

        menu.refresh()
        console.refresh()

        key = stdscr.get_wch()

        console.key_handle(key)
        if not console.is_handle_key:
            status = menu.key_handle(key)
예제 #20
0
def get_answer(data, part2=False):
    c = Console(data)

    if part2:
        return brute_force(c)
    else:
        return c.run()
예제 #21
0
 def _add_console(self):
     """ Adds a widget to the bottom pane for command output. """
     self._console = Console()
     self._console.set_font(self._settings.get_string("console-font"))
     panel = self.window.get_bottom_panel()
     panel.add_item_with_stock_icon(self._console, "AndroidConsole",
                                    "Console", STOCK_CONSOLE)
예제 #22
0
def server(cx=0, cy=0, tx=0, ty=0, angle=0, saved_file="model.pickle"):
    cx = request.args.get('cx', "CX")
    cy = request.args.get('cy', "CY")
    tx = request.args.get('tx', "TX")
    ty = request.args.get('ty', "TY")
    angle = request.args.get('angle', "ANG")
    if (cx == "CX" or cy == "CY" or tx == "TX" or ty == "TY" or angle == "ANG"):
        return render_template('index.html')
    cx = float(cx)
    tx = float(tx)
    cy = float(cy)
    ty = float(ty)
    angle = float(angle)
    g = None
    with open(saved_file, 'rb') as f:
        g = pickle.load(f)
    if g is None:
        return "Error - couldn't load model"
    #return ('{} | {} | {} | {}'.format(cx, angle, type(cx), type(angle)))
    result = g.predict([cx,cy,tx,ty,angle])
    
    res= {'model':'miss', 'actual':'miss'}
    if result[0]>result[1]:
        res['model']='hit';
    game = Console(Canon(x=cx, y=cy, angle=angle), Target(x=tx, y=ty, radius=3))
    result = game.shoot()
    game.display2f()
    if result:
        res['actual']='hit'
    valid = 'MODEL PREDICTION IS CORRECT!'
    if res['actual'] != res['model']:
        valid = 'MODEL PREDICTION IS INCORRECT.'
    figID = '/static/capt.png?{}{}{}{}{}'.format(cx,cy,tx,ty,angle)
    return render_template('index.html', answer=str(res), validation=str(valid), cx=str(cx), cy=cy, tx=tx, ty=ty, angle=angle, figure=figID)
예제 #23
0
def cli():
    kwargs = docopt(__doc__)
    title = kwargs.get('<title>', None).replace('+', ' ') if kwargs.get(
        '<title>', None) else None
    author = kwargs.get('<author>', None).replace('+', ' ') if kwargs.get(
        '<author>', None) else None
    console = Console()
    console.search_book(title, author)
예제 #24
0
파일: game.py 프로젝트: tjasiukiewicz/Chess
 def __init__(self, console=Console()):
     """Inicjalizacja gry"""
     self._move_count = 0
     self._console = console
     self._board = Chessboard(self._console, self._console.draw)
     self._current_player, self._next_player = PlayerMaker(
         self._console).make()
     self._shelve = shelve.open("chessboard_move_storage", flag='n')
예제 #25
0
def start_application(host, port):
    telnet = telnetlib.Telnet()
    beanstalkd = Beanstalkd(telnet, host, port)
    stats = BeanstalkdStats(beanstalkd)
    char_reader = CharReader(os, sys, termios, fcntl)
    screen_printer = ScreenPrinter(os, sys)
    console = Console(Clock(time), char_reader, screen_printer, stats)
    return beanstalkd, console
예제 #26
0
 def __init__(self):
     """
     Constructor
     """
     self.console = Console()
     self.logger = logging.getLogger(self.__class__.__name__)
     self.timestamp = None
     self.devices = {}
예제 #27
0
 def __init__(self, console=Console(), change_state_call=lambda: 0):
     """Inicjalizuje pustą szachownicę"""
     self._fields = {
         row: {col: None
               for col in 'abcdefgh'}
         for row in range(1, 9)
     }
     self._console = console
     self._change_state_call = change_state_call
예제 #28
0
 def postExploit(self, credential):
     con = Console()
     message = con.getTimeString()
     message += con.format(" Login was Successful!!! ", ['green', 'bold'])
     message += "username: %s password: %s " % (
         con.format(credential.username, ['green', 'bold']),
         con.format(credential.password, ['green', 'bold']))
     print(message)
     exit()
예제 #29
0
 def __init__(self):
     self.console = Console()
     self.recursos = []
     self.processos = []
     self.ordemDeExecucao = []
     self.tituloDosRecursos = []
     self.tituloDosProcessos = []
     self.estado = 'Seguro'
     self.executando = True
예제 #30
0
파일: rom_tests.py 프로젝트: jzerbe/Ice
    def test_name(self):
        prefix = "Any Text"
        gba = Console("Gameboy Advance")
        prefix_gba = Console("Gameboy Advance", { "prefix": prefix })
        empty_prefix_gba = Console("Gameboy Advance", {"prefix": "" })
        rom_path = "/Users/scottrice/ROMs/GBA/Pokemon Emerald.gba"

        rom = ROM(rom_path, gba)
        prefix_rom = ROM(rom_path, prefix_gba)
        empty_prefix_rom = ROM(rom_path, empty_prefix_gba)

        # With no prefix, the name should be the same as the basename
        self.assertEqual(rom.name(), "Pokemon Emerald")
        # When the prefix is the empty string, it should be treated as if no
        # prefix was given
        self.assertEqual(empty_prefix_rom.name(), "Pokemon Emerald")
        # When the console has a prefix, the ROM should begin with that string
        self.assertTrue(prefix_rom.name().startswith(prefix))