Exemplo n.º 1
0
def test_ask_string():
    with mock.patch('builtins.input') as m:
        m.side_effect = ["sugar!", ""]
        res = ui.ask_string("coffee with what?")
        assert res == "sugar!"
        res = ui.ask_string("coffee with what?", default="milk")
        assert res == "milk"
Exemplo n.º 2
0
def add_pool_ui(json_file):
    pool_list = open_pool_list(json_file)
    new_pool = {}
    new_pool['pool_API_url'] = ''
    new_pool['pool_mining_urls'] = []
    new_pool['pool_name'] = ui.ask_string("Enter new pool name")
    pool_type_list = ["node-cryptonote-pool", "nodejs-pool", "other"]
    new_pool['pool_API_type'] = ui.ask_choice("API type ?", pool_type_list)
    new_pool['config_file'] = ui.ask_string(
        "Configuration file URL (usually config.js OR global.js) ?")
    new_pool = get_config(new_pool)
    if new_pool['pool_API_url'] == '':
        new_pool['pool_API_url'] = ui.ask_string(
            "Impossible to get API URL, please provide manually for next attempt"
        )
        new_pool = get_config(new_pool)
    print("*** Output ***")
    print(json.dumps(new_pool, indent=4))
    yesno = ["no", "yes"]
    accept = ui.ask_choice("Do you want to add to the pool list ?", yesno)
    if accept == "yes":
        pool_list.append(new_pool)
        output = {}
        output["pools"] = pool_list
        with open(json_file, 'w') as pouet:
            pouet.write(json.dumps(output, indent=4))
            print("Done ...")
    else:
        print("OK nevermind ...")
Exemplo n.º 3
0
def _agent_prompt():
    """Description: Prompt the user to import their agent"""
    sys.path.append(os.getcwd())
    agent = importlib.import_module(ui.ask_string(constants.Strings.match_import.value))
    agent_class = ui.ask_string(constants.Strings.match_class_name.value)
    if agent_class not in agent.__dir__():
        ui.fatal(constants.Strings.error_invalid_class.value)
    agent = getattr(agent, agent_class)
    if getattr(agent, "act"):
        ui.info(ui.green, constants.Strings.match_agent_success.value)
    return agent
Exemplo n.º 4
0
def intent(network):
    """Description: This creates a prompt for the user where they can choose to:  
    * Play a match  
    * Create/Join a room  
    * Replay a match  
    * Exit the application  
    Arguments:   
    * network: An `network`(pommerman.network.ion_client.network) object  
    """
    i = ui.ask_choice(
        constants.Strings.intent.value,
        [
            constants.Strings.intent_match.value,
            constants.Strings.intent_room.value,
            constants.Strings.intent_replay.value,
            constants.Strings.intent_exit.value,
        ],
    )
    if i == constants.Strings.intent_match.value:
        agent = _agent_prompt()
        match(network, agent=agent, ui_en=True)
    elif i == constants.Strings.intent_room.value:
        room = str(ui.ask_string(constants.Strings.room_code.value))
        agent = _agent_prompt()
        match(network, room=room, agent=agent, ui_en=True)
    elif i == constants.Strings.intent_replay.value:
        replay(network, ui_en=True)
    elif i == constants.Strings.intent_exit.value:
        exit(0)
Exemplo n.º 5
0
def init():
    """Description: Starts up the application normally by asking the user about
    the server they want to connect to"""
    if ui.ask_yes_no(constants.Strings.server_prompt.value):
        domain = ui.ask_string(constants.Strings.server_ip.value)
        if domain is None:
            ui.fatal(constants.Exceptions.invalid_ip.value)
    else:
        domain = "play.pommerman.com:5050"
    ui.info(
        constants.Strings.server_connecting_p1.value,
        ui.yellow,
        constants.Strings.server_connecting_p2.value,
        ui.reset,
        constants.Strings.server_connecting_p3.value,
    )
    network = Network(domain)
    try:
        status = network.server_status()
    except Exception as e:
        ui.fatal(e)
    signal.signal(signal.SIGINT, _exit_handler)
    ui.info(
        constants.Strings.server_connected.value,
        ui.yellow,
        constants.Strings.server_players.value,
        str(status[0]) + ",",
        constants.Strings.server_matches.value,
        status[1],
    )
    intent(network)
Exemplo n.º 6
0
def replay(network, id=False, ui_en=False):
    """Description: This replays a particular match  
    Arguments:  
    * network: An `network`(pommerman.network.ion_client.network) object  
    * id: The ID of a match to be played. If False, the user is prompted about \
it.  
    * ui_en: If the UI is enabled or disabled (This also controls if exception are\
raised or not)"""
    if not id and ui_en:
        id = ui.ask_string(constants.Strings.replay_prompt.value)
        if id is None:
            ui.fatal(constants.Strings.error_invalid_id.value)
        id = str(id)
    if id[0] == "#":
        id = id[1:]
    ui.info(
        constants.Strings.server_replay_p1.value,
        ui.yellow,
        "#" + str(id),
        ui.reset,
        constants.Strings.server_replay_p2.value,
    )
    try:
        replay_obj = network.get_replay(id)
    except Exception as e:
        if ui_en:
            ui.fatal(e)
        raise e
    if ui_en:
        ui.info(constants.Strings.replay_start.value, ui.yellow, "#" + str(id))
    env = pommerman.make(
        replay_obj["mode"],
        [
            pommerman.agents.BaseAgent(),
            pommerman.agents.BaseAgent(),
            pommerman.agents.BaseAgent(),
            pommerman.agents.BaseAgent(),
        ],
    )
    env.reset()
    env._board = numpy.array(replay_obj["board"])
    # Note: Render FPS is set to 30 as it'll be smoother
    env._render_fps = 30
    for i in replay_obj["actions"]:
        env.render()
        reward, done = env.step(i)[1:3]
        if done:
            break
    if reward != replay_obj["reward"]:
        if ui_en:
            ui.info(ui.yellow, constants.Exceptions.replay_no_reward.value)
        else:
            raise Exception(constants.Exceptions.replay_no_reward.value)
    env.close()
    if ui_en:
        ui.info(ui.yellow, constants.Strings.replay_end.value)
    intent(network)
Exemplo n.º 7
0
def init():
    """Description: Initiate the application by asking questions."""
    ui.info(ui.yellow, constants.Strings.sever_starting.value)
    port = int(ui.ask_string(constants.Strings.server_port.value))
    max_players = int(ui.ask_string(constants.Strings.server_maxp.value))
    if max_players < 4:
        # If the maximum players allowed on the server is less than 4
        # which is the minimum required for a pommerman match then
        # notify the user about that and quit.
        ui.fatal(ui.yellow, constants.Strings.server_playercount_too_low.value)
    modes = []
    for i in pommerman.configs.__dir__():
        if i[-4:] == "_env":
            id = getattr(pommerman.configs, i)()["env_id"]
            if id[-2:] != "v2":
                modes.append(id)
    timeout = float(ui.ask_string(constants.Strings.server_timeout.value))
    mode = str(ui.ask_choice(constants.Strings.server_mode.value, modes))
    run(port, max_players, timeout, mode, ui_en=True, exit_handler=True)
Exemplo n.º 8
0
def change_filter():
    """Changes the search filter for myStream.filter(track=[trump])
    :param:
    :return trump: New keyword or DEFAULT keyword 'trump'"""
    trump = 'trump'  # A variable named trump.
    ui.info_1(ui.yellow, "SEARCH:", ui.blue, ui.standout, "'trump'")
    ans_filter = ui.ask_yes_no("Change search keyword? [Ctrl-C Quits] >>>",
                               default=False)
    if ans_filter == False:
        return trump
    else:
        ui.info_1(ui.red, "Really change?")
        ans_really = ui.ask_yes_no("[ENTER] for No >>>", default=False)
        if ans_really == False:
            return trump
        else:
            trump = ui.ask_string("Enter new search keyword")
            ui.info_3("Starting search for new keyword:", ui.blue, trump)
            return trump
Exemplo n.º 9
0
def ask_table(db_file=TWEETS_DB,
              conn=create_conection(),
              table_name=TABLE_NAME):
    """Default table or new table.  Checks if table exists,
    creates one if not with name from user and calls user_ans_tweets().
    :param db_file: DEFAULT database
    :param conn: creates connection()
    :param table_name: name of table
    """
    def ploting(tweets_db=TWEETS_DB, csv_file=CSV_FILE):
        table_name = MyStreamListener.table_name
        plot_question = ui.ask_yes_no("Plot?", default=True)
        if plot_question:
            ui.info(ui.green, "Populating csv file with {}".format(table_name))
            q_four.db_into_csv(TWEETS_DB, CSV_FILE, table_name)
            ui.info_3("Ploting...")
            q_four.frecuency()
            q_four.senti()
        else:
            ui.info(ui.turquoise, "Program Finished")
            exit()

    tables_list = list()
    conn = create_conection()
    cur = conn.cursor()
    cur.execute("SELECT name FROM sqlite_master")
    for table in cur:
        tables = str(table).strip('(').strip(')').strip(',').strip("'")
        tables_list.append(tables)
    if "trump" in tables_list:
        ui.info_1(ui.yellow, ui.bold, "DEFAULT TABLE FOUND! =>", ui.blue,
                  ui.standout, "'trump'")
        new_db_ans = ui.ask_yes_no("Add tweets to table 'trump'?",
                                   default=True)
        if new_db_ans:
            ui.warning("Creating database (If it doesn't exist)")
            create_conection()
            ui.info_2(ui.green, "Accessing Database")
            MyStreamListener.table_name = TABLE_NAME
            user_ans_tweets()
            ploting()
        else:
            choices = ["Create New Table", "Load table", "Plot", "Quit"]
            new = ui.ask_choice("Select: ", choices)
            if new == "Create New Table":
                ui.warning("Tables with the same name will not be created")
                new_table_name = ui.ask_string("Enter new table name:")
                new_table_name = new_table_name.lower()
                new_table_name = new_table_name.replace(" ", "_")
                ui.info("Table name with format:", ui.blue, new_table_name)
                create_ans = ui.ask_yes_no("Create?")
                if create_ans:
                    tweets_table_create(create_conection(), TWEETS_DB,
                                        new_table_name)
                    insert_new_tbl = ui.ask_yes_no(
                        "Insert new tweets into {}?".format(new_table_name))
                    if insert_new_tbl:
                        MyStreamListener.table_name = new_table_name
                        user_ans_tweets()
                        ploting()
                    else:
                        ui.info(ui.bold, ("Program Finished"))
                else:
                    ui.info(ui.bols, "Program Finished")
            elif new == "Load table":
                new_table_name = ui.ask_choice("Select Table to load:",
                                               tables_list)
                MyStreamListener.table_name = new_table_name
                user_ans_tweets()
                ploting()

            elif new == "Plot":
                new_table_name = ui.ask_choice("Select Table to plot:",
                                               tables_list)
                MyStreamListener.table_name = new_table_name
                ploting()

            elif new == "Quit":
                ui.warning("Program Finished")
                exit()
Exemplo n.º 10
0
     exit()
 if out == 'compiler':
     ui.info_2('installing')
     os.system(
         f'bash -c "cd  {   os.path.dirname(os.path.abspath(__file__))  }/compiler++ && source compile.sh" '
     )
     #subprocess.run(['sh','./compiler++/compile.sh'],)
     ui.info_2(
         'Zainstalowano - od teraz można w terminalu uzyć komendy c [nazwaprogramu]'
     )
 if out == 'backup-client':
     ui.info_2('installing')
     os.system(
         f'bash -c "cd  { os.path.dirname(os.path.abspath(__file__))  }/backup/client"'
     )
     ip = ui.ask_string(
         'podaj ip serwera backupowego, dla lokalnego wpisz 127.0.0.1')
     port = ui.ask_string('podaj port serwera backupowego')
     pswd = ui.ask_password(
         'podaj haslo do serwera backupowego (ustawisz je przy instalacji serwera)'
     )
     f = open(
         os.path.dirname(os.path.abspath(__file__)) +
         '/backup/client/settings.json', 'w+')
     f.write(
         f'{{ \n  "server":"{ip}", \n "port":{port}, \n "pass":"******" \n }}'
     )
     f.close()
     os.system(
         f'bash -c "cd  {   os.path.dirname(os.path.abspath(__file__))  }/backup/client && source compile.sh"'
     )
     #subprocess.run(['sh','./compiler++/compile.sh'],)