Exemple #1
0
 def learn(self):
     path = get_file(self.config.path)
     lines = [
         line.strip() for line in File(path).read().splitlines() if line
     ]
     random.shuffle(lines)
     lines = lines[:self.config.num]
     q.clear()
     for num, line in enumerate(lines, 1):
         q.echo("%s of %s" % (num, len(lines)))
         qst, ans = self._get_qst_ans(line)
         vld = Practice._get_valid(ans)
         q.alert(qst.rand)
         q.alert(ans.rand)
         talk(qst.rand, qst.lang.name.short)
         talk(ans.rand, ans.lang.name.short, slow=True)
         rsp = ""
         while rsp not in vld:
             rsp = q.ask_str("").lower().strip()
         q.clear()
         flush_input()
         talk(ans.rand, ans.lang.name.short, slow=True)
         q.echo("%s of %s" % (num, len(lines)))
         ans.lang.hint = len(ans.rand) // 4
         rsp = ""
         while rsp not in vld:
             msg = Practice._get_msg_base(qst) + Practice._get_msg_hint(ans)
             q.alert(msg)
             rsp = q.ask_str("").lower().strip()
             ans.lang.hint += 1
         q.echo("[CORRECT] " + ans.text)
         talk(ans.rand, ans.lang.name.short, wait=True)
         q.clear()
Exemple #2
0
def new_config():
    """Prompt user for config variables and generate new config.

    Returns: A new ConfigDict.
    """
    config = ConfigDict()
    config["module-path"] = qprompt.ask_str("Top-level module path",
                                            blk=False,
                                            vld=os.path.exists,
                                            hlp=MODULE_PATH_HELP)

    timeout = qprompt.ask_str(
        "Test execution timeout (seconds)",
        vld=float,
        blk=False,
        hlp="The number of seconds to let a test run before terminating it.",
    )
    config["timeout"] = float(timeout)
    config["excluded-modules"] = []

    config["test-command"] = qprompt.ask_str("Test command",
                                             blk=False,
                                             hlp=TEST_COMMAND_HELP)

    menu = qprompt.Menu()
    for at_pos, distributor_name in enumerate(distributor_names()):
        menu.add(str(at_pos), distributor_name)
    config["distributor"] = ConfigDict()
    config["distributor"]["name"] = menu.show(header="Distributor",
                                              returns="desc")

    return config
Exemple #3
0
def addPass():
    global pragma_input
    print("This will add a new set of credentials to the database.")
    website = qprompt.ask_str("Website")
    username = qprompt.ask_str("Username")
    password = qprompt.ask_str("Password")
    print("Here is what will be entered into the database:")
    print("Website: " +
          website)  #display information so user can confirm that it's correct
    print("Username: "******"Password: "******"y")  #yes/no to confirm
    if confirm == False:
        retry = qprompt.ask_yesno("Would you like to retry?")
        if retry == False:
            mainMenu()
        else:
            addPass()
    else:
        conn = sqlcipher.connect('.passman.db')
        cur = conn.cursor()
        cur.execute(pragma_input)
        #add the users input into the database as a new set of credentials
        cur.execute(
            "INSERT INTO passwords (WEBSITE, USERNAME, PASSWORD) values ('{}', '{}', '{}')"
            .format(website, username, password))
        conn.commit()
        cur.close()
        print("Credentials added successfully!")
        qprompt.pause()
        mainMenu()
Exemple #4
0
def new_config():
    """Prompt user for config variables and generate new config.

    Returns: A new ConfigDict.
    """
    config = ConfigDict()
    config["module-path"] = qprompt.ask_str("Top-level module path")

    python_version = qprompt.ask_str(
        'Python version (blank for auto detection)')
    config['python-version'] = python_version

    timeout = qprompt.ask_str('Test execution timeout (seconds)')
    config['timeout'] = float(timeout)
    config['excluded-modules'] = []

    config["test-command"] = qprompt.ask_str("Test command")

    menu = qprompt.Menu()
    for at_pos, engine_name in enumerate(execution_engine_names()):
        menu.add(str(at_pos), engine_name)
    config["execution-engine"] = ConfigDict()
    config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")

    return config
Exemple #5
0
def set_buyOrder(coin_symbol):

    qprompt.wrap("\t\t\t~> SET BUY ORDER <~")
    while (1):
        puts(colored.green("\t\t\t\tAvailable BTC : " + avail_btc() + " BTC"))
        per_coin_price = qprompt.ask_str("Enter Coin Price ")
        worth_btc = qprompt.ask_str("Total worth in BTC")
        quantity_coin = int(round(float(worth_btc) / float(per_coin_price)))
        puts(colored.red("\n\t\tPlease confirm your order"))
        puts(
            colored.green("\t\tBUY " + str(quantity_coin) + " coins @" +
                          str(per_coin_price) + " (Total: " + str(worth_btc) +
                          " ) BTC"))
        q = raw_input("\t[?] Confirm : ")
        if q == 'Y' or q == 'y':
            # uncomment this code - for actual use
            '''
            # placing a buy order
            order = client.order_limit_buy(
            symbol=coin_symbol,
            quantity=quantity_coin,
            price=per_coin_price)
            '''
            puts(
                colored.yellow(
                    "\n\t********* [?] Your Order has been placed *********"))
            #break
            #return (order)
        else:
            puts(
                colored.cyan(
                    "---- [!] ALERT Something went wrong | Plz set this order again ----"
                ))
            continue
        break
Exemple #6
0
    def test_str_1(test):
        setinput("hello")
        result = ask_str()
        test.assertEqual("hello", result)

        setinput("world")
        result = ask_str()
        test.assertEqual("world", result)
Exemple #7
0
def new_config():
    """Prompt user for config variables and generate new config.

    Returns: A new ConfigDict.
    """
    config = ConfigDict()
    config["module-path"] = qprompt.ask_str("Top-level module path",
                                            blk=False,
                                            vld=os.path.exists,
                                            hlp=MODULE_PATH_HELP)

    python_version = qprompt.ask_str(
        'Python version (blank for auto detection)',
        vld=_validate_python_version,
        hlp=PYTHON_VERSION_HELP)
    config['python-version'] = python_version

    timeout = qprompt.ask_str(
        'Test execution timeout (seconds)',
        vld=float,
        blk=False,
        hlp="The number of seconds to let a test run before terminating it.")
    config['timeout'] = float(timeout)
    config['excluded-modules'] = []

    config["test-command"] = qprompt.ask_str("Test command",
                                             blk=False,
                                             hlp=TEST_COMMAND_HELP)

    menu = qprompt.Menu()
    for at_pos, engine_name in enumerate(execution_engine_names()):
        menu.add(str(at_pos), engine_name)
    config["execution-engine"] = ConfigDict()
    config['execution-engine']['name'] = menu.show(header="Execution engine",
                                                   returns="desc")

    config["cloning"] = ConfigDict()
    config['cloning']['method'] = 'copy'
    config['cloning']['commands'] = []

    config['interceptors'] = ConfigDict()
    config['interceptors']['enabled'] = [
        'spor', 'pragma_no_mutate', 'operators-filter'
    ]
    config['operators-filter'] = ConfigDict()
    config['operators-filter']['exclude-operators'] = None

    return config
    def update_value(self, value):
        """
        Prompt the user to input a new value, then save the updated config
        and return to menu.
        Determines how to prompt the user by finding the value name passed as
        argument in one of the lists in the type map.
        :param value: value name to be updated e.g. minwidth
        """
        desc_str = "Enter new {} (currently {})".format(value, self.config['user'][value])
        if value in self.type_map[int]:
            self.config['user'][value] = str(qprompt.ask_int(desc_str))
        elif value in self.type_map[float]:
            self.config['user'][value] = str(qprompt.ask_float(desc_str))
        elif value in self.type_map[str]:
            self.config['user'][value] = qprompt.ask_str(desc_str)
        elif value in self.type_map[bool]:
            desc_str += " y/n"
            if qprompt.ask_yesno(desc_str):
                self.config['user'][value] = "yes"
            else:
                self.config['user'][value] = "no"

        self.save_config()
        self.clear_screen()
        print('Config saved...')
Exemple #9
0
def ask_file(dpath, msg="File to review (blank to list)"):
    """Prompts user for a file to review. Returns the file name."""
    path = q.ask_str(msg, blk=True)
    if not path or not op.isfile(path):
        vfiles = [op.basename(f) for f in listdir(dpath) if f.endswith(".txt")]
        path = q.enum_menu(vfiles).show(returns="desc", limit=20)
        path = op.join(dpath, path)
    return path
Exemple #10
0
def program_menu():
    # Printing Menu & asking user for enter a choice
    menu = [['1', "View Account Balance"], ['2', "Place a Buy Order"],
            ['3', "Place a Sell Order"]]
    qprompt.wrap("Choose one of the following choices")
    puts(colored.yellow(tabulate(menu, tablefmt="fancy_grid")))
    choice = qprompt.ask_str("Enter your Choice")
    return (choice)
Exemple #11
0
def updatePass():
    global pragma_input
    conn = sqlcipher.connect('.passman.db')
    cur = conn.cursor()
    cur.execute(pragma_input)
    print(pd.read_sql_query(
        "SELECT * FROM passwords",
        conn))  #display all passwords so user can easily see its ID
    print("Select the ID of the credentials you wish to EDIT")
    try:
        ID = qprompt.ask_int("ID")  #ask user for ID of credential to edit
    except:
        qprompt.error("ID NOT FOUND")  #error if ID is not found
        retry = qprompt.ask_yesno(
            "Retry?")  #prompt user to retry or exit to main menu
        if retry == False:
            mainMenu()
        else:
            updatePass()

    print(
        "Credential set selected! What would you like to change?"
    )  #ask user what about the chosen set of credentials they would like to change
    qprompt.alert("HINT: Use '?' for a list of options")
    selection = qprompt.ask_str("Edit",
                                valid=["website", "username", "password"])
    if selection.lower() == "website":
        new = qprompt.ask_str("Enter new value")
        cur.execute(
            "UPDATE passwords SET WEBSITE = '{}' WHERE ID = '{}'".format(
                new, ID))  #updates record with new info
    elif selection.lower() == "username":
        new = qprompt.ask_str("Enter new value")
        cur.execute(
            "UPDATE passwords SET USERNAME = '******' WHERE ID = '{}'".format(
                new, ID))
    elif selection.lower() == "password":
        new = qprompt.ask_str("Enter new value")
        cur.execute(
            "UPDATE passwords SET PASSWORD = '******' WHERE ID = '{}'".format(
                new, ID))
    conn.commit()
    cur.close()
    mainMenu()
Exemple #12
0
    def _ask(self, line):
        if not line: return
        qst, ans = self._get_qst_ans(line)
        msg = Practice._get_msg_base(qst)
        if ans.lang.hint or ans.lang.dynamic:
            if ans.lang.dynamic:
                Record = Query()
                results = self.db.search(Record.ln == line)
                # Get most recent results.
                num_results = 3
                results = sorted(results, key=lambda r: r['dt'],
                                 reverse=True)[:num_results]
                oks = [r['ok'] for r in results]
                while len(oks) < num_results:
                    oks.append(0.7)
                ratio = 0
                if results:
                    ratio = statistics.mean(oks)
                ans.lang.hint = dynamic_hintnum(ans.rand, ratio)
            if ans.lang.hint:
                msg += Practice._get_msg_hint(ans)
        talk_qst = callstop(talk)
        tries = 0
        while True:
            q.alert(msg)
            if qst.lang.talk:
                talk_qst(qst.rand, qst.lang.name.short)
            t_start = time.time()
            rsp = q.ask_str("").lower().strip()
            sec = time.time() - t_start
            vld = Practice._get_valid(ans)
            record = self._prep_record(line, rsp, qst, ans, sec, tries)
            closest_orig, _ = guess_similarity(rsp,
                                               Practice._get_valid_orig(ans))
            if rsp in vld:
                record['ok'] = 1.0
                q.echo("[CORRECT] " + ans.text)
                if self.config.record:
                    self.db.insert(record)
            else:
                tries += 1
                _, record['ok'] = guess_similarity(rsp, vld)
                q.error(closest_orig)
                if self.config.record:
                    self.db.insert(record)
                if self.config.redo:
                    continue

            if tries > 0:
                self.miss.add(line)
            else:
                self.okay.add(line)
            if ans.lang.talk:
                say, _ = guess_similarity(rsp, Practice._get_valid_orig(ans))
                talk(say, ans.lang.name.short, wait=True)
            return
Exemple #13
0
 def show_create_user_menu(self):
     # TODO: uncomment it: qprompt.ask_captcha(length=6)
     username = qprompt.ask_str("Enter username",
                                valid=lambda x: len(x) > 3)
     password = qprompt.ask_str("Enter password",
                                valid=lambda x: len(x) > 4,
                                shw=False)
     create_user_callback = self.opts.get(self.OPTS_CREATE_USER, None)
     if create_user_callback is not None:
         status, msg = create_user_callback(username, password)
         if status:
             qprompt.status("Creating user succeeded.", time.sleep, [2])
             self.username = username
             self.password = password
             self.login_status = (True, self.username)
         else:
             qprompt.error("Creating user failed: {}".format(msg))
     else:
         qprompt.error("Cannot proceed with creating user - internal error")
Exemple #14
0
def get_choice(vecs):
    menu = qprompt.Menu()
    for vec in vecs:
        menu.add(vec["short_name"], vec['vec'])
    choice = menu.show(returns="desc")
    key_phrase = ''
    if choice != generic_vec_name:
        while key_phrase == '':
            key_phrase = qprompt.ask_str("enter key phrase: ")
    return choice, key_phrase.lower()
Exemple #15
0
def new_config():
    """Prompt user for config variables and generate new config.

    Returns: A new ConfigDict.
    """
    config = ConfigDict()
    config["module-path"] = qprompt.ask_str(
        "Top-level module path",
        blk=False,
        vld=os.path.exists,
        hlp=MODULE_PATH_HELP)

    python_version = qprompt.ask_str(
        'Python version (blank for auto detection)',
        vld=_validate_python_version,
        hlp=PYTHON_VERSION_HELP)
    config['python-version'] = python_version

    timeout = qprompt.ask_str(
        'Test execution timeout (seconds)',
        vld=float,
        blk=False,
        hlp="The number of seconds to let a test run before terminating it.")
    config['timeout'] = float(timeout)
    config['excluded-modules'] = []

    config["test-command"] = qprompt.ask_str(
        "Test command",
        blk=False,
        hlp=TEST_COMMAND_HELP)

    menu = qprompt.Menu()
    for at_pos, engine_name in enumerate(execution_engine_names()):
        menu.add(str(at_pos), engine_name)
    config["execution-engine"] = ConfigDict()
    config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")

    config["cloning"] = ConfigDict()
    config['cloning']['method'] = 'copy'
    config['cloning']['commands'] = []

    return config
Exemple #16
0
def new_config():
    """Prompt user for config variables and generate new config.

    Returns: A new configuration as a single string.
    """
    conf = {'module': qprompt.ask_str("Top-level module")}

    menu = qprompt.Menu()
    test_runners = test_runner_names()
    for at_pos, test_runner in enumerate(test_runners):
        menu.add(str(at_pos), test_runner)
    conf['test_runner'] = menu.show(header="Test runner", returns="desc")

    conf['test_args'] = qprompt.ask_str('Test args')

    menu = qprompt.Menu()
    for at_pos, engine_name in enumerate(execution_engine_names()):
        menu.add(str(at_pos), engine_name)
    conf['engine'] = menu.show(header="Execution engine", returns="desc")
    return TEMPLATE.format(**conf)
Exemple #17
0
def show_prompt(verchk, pause=True):
    """Shows the standard prompt for handling version numbers in a project."""
    import qprompt
    verchk.run()
    if qprompt.ask_yesno("Update version?", dft="n"):
        newver = qprompt.ask_str("New version string")
        if newver:
            verchk.update(newver)
            verchk.run()
            if pause:
                qprompt.pause()
Exemple #18
0
def set_sellOrder():
    qprompt.wrap("\t\t\t~> SET SELL ORDER <~")
    coin_symbol = coin_data()
    coin = coin_symbol.replace('BTC', '')
    while (1):
        puts(colored.blue("\n[***] SET YOUR ORDER [***]"))
        puts(
            colored.red("\t\t\t\tAvailable " + coin + " : " +
                        coin_quantity(coin)))
        per_coin_price = qprompt.ask_str("Enter Coin Price ")
        quantity = qprompt.ask_str("Enter quantity")
        worth_btc = float(quantity) * float(per_coin_price)
        puts(colored.green("\n\t\tPlease confirm your order"))
        puts(
            colored.red("\t\tSELL " + str(quantity) + " coins @" +
                        str(per_coin_price) + " (Total: " + str(worth_btc) +
                        " ) BTC"))
        q = raw_input("\t[?] Confirm : ")
        if q == 'Y' or q == 'y':
            # uncomment this code - for actual use
            '''
            # placing a buy order
            order = client.order_limit_sell(
            symbol=coin_symbol,
            quantity=quantity_coin,
            price=per_coin_price)
            '''
            puts(
                colored.yellow(
                    "\n\t********* [?] Your Order has been placed *********"))
            #break
            #return (order)
        else:
            puts(
                colored.cyan(
                    "---- [!] ALERT Something went wrong | Plz set this order again ----"
                ))
            continue
        break
Exemple #19
0
def edition_menu(flaw):
    """
    Edit the flaw and return it with the corresponding changes

    :return Flaw
    """
    # print(flaw)
    choice = qprompt.ask_str(
        inline_yellow("Enter property to edit with '_' \
to separate subfields. Some examples include \
'title', 'flaw_phase' or 'severity_rvss-score'\n"))
    new_flaw = None
    try:
        # differentiate options and edit value
        if len(choice.split("_")) == 1:
            current_value = flaw.document()[choice]
            new_value = qprompt.ask_str("Current value is: '" +
                                        inline_magenta(str(current_value)) +
                                        "'\n")
            new_document = flaw.document()
            new_document[choice] = new_value
        else:
            current_value = flaw.document()[choice.split("_")[0]][choice.split(
                "_")[1]]
            new_value = qprompt.ask_str("Current value is: '" +
                                        inline_magenta(str(current_value)) +
                                        "'\n")
            new_document = flaw.document()
            new_document[choice.split("_")[0]][choice.split("_")
                                               [1]] = new_value
        validated, errors = validate_document(new_document)
        new_flaw = Flaw(new_document)
        return new_flaw
    except KeyError:
        yellow("Warning, subfield not found, no change applied")
        return flaw
Exemple #20
0
def searchByWebsite():
    global pragma_input
    query = qprompt.ask_str("Query")  #get query input from user
    conn = sqlcipher.connect('.passman.db')
    cur = conn.cursor()
    cur.execute(pragma_input)
    conn.commit()
    print(
        pd.read_sql_query(
            "SELECT * FROM passwords WHERE WEBSITE LIKE '%{}%'".format(query),
            conn)
    )  #select all records containing user input display it in a pretty way
    cur.close()
    qprompt.pause()  #pause program and prompt user for continue
    mainMenu()  #return to main menu
Exemple #21
0
def searchByUsername():
    global pragma_input
    query = qprompt.ask_str("Query")
    conn = sqlcipher.connect('.passman.db')
    cur = conn.cursor()
    cur.execute(pragma_input)
    cur.execute(
        "SELECT * FROM passwords WHERE USERNAME LIKE '%{}%'".format(query))
    conn.commit()
    print(
        pd.read_sql_query(
            "SELECT * FROM passwords WHERE USERNAME LIKE '%{}%'".format(query),
            conn))
    cur.close()
    qprompt.pause()
    mainMenu()
Exemple #22
0
def main():
    while (1):
        choice = program_menu()
        if choice == '1':
            view_portfolio()

        if choice == '2':
            coin_symbol = coin_data()
            order_book(coin_symbol)
            order = set_buyOrder(coin_symbol)

        if choice == '3':
            order = set_sellOrder()

        # +++++ asking for returing to menu or to quit the program ++++
        choice = qprompt.ask_str(
            "Return to Main Menu ( Y for YES ) & ( q for quit)")
        if choice == 'q' or choice == 'Q':
            exit()
        else:
            printLine()
            continue
Exemple #23
0
 def __new__(cls, msg):
     return str.__new__(cls, qprompt.ask_str(msg))
Exemple #24
0
 def __new__(cls, msg):
     return str.__new__(cls, qprompt.ask_str(msg))
Exemple #25
0
import qprompt
name = qprompt.ask_str("Name", blk=False)
age = qprompt.ask_int("Age", vld=range(130))
if qprompt.ask_yesno("Say hello?", dft="y"):
    print("Hi %s! You are %u years old!" % (name, age))
    qprompt.pause()
Exemple #26
0
            conslt = qprompt.Menu()
            conslt.add("A", "Insertar")
            conslt.add("B", "Buscar anime por puntuación")
            conslt.add("C", "Eliminar")
            conslt.add("D", "Imprimir Arbol")
            conslt.add("E", "Mejor Anime")
            conslt.add("F", "Peor Anime")
            conslt.add("G", "Volver")
            qprompt.echo("\nElija una de las consultas disponibles")
            choice = conslt.show()

            #Insert
            if choice == "A":
                title = ""
                while title.strip() == "":
                    title = qprompt.ask_str(
                        "Ingrese el titulo del anime que desea agregar")
                score = qprompt.ask_float(
                    "Ingrese el score del anime que desea agregar")
                info.insert(info.root, title, score)
                qprompt.echo(
                    "\nSe ha agregado el anime {} de forma exitosa\n".format(
                        title))

            #Serch
            elif choice == "B":
                score = qprompt.ask_float(
                    "Ingrese el score del anime que desea buscar")
                node = info.find(info.root, score)
                if not node:
                    qprompt.echo(
                        "No se ha encontrado ningun anime con ese puntaje\n")
Exemple #27
0
import qprompt
while True:
    cmd = qprompt.ask_str("command", vld=["help", "run", "quit"], blk=False)
    if "help" == cmd:
        print("DO HELP")
    if "run" == cmd:
        print("DO RUN")
    if "quit" == cmd:
        exit()
Exemple #28
0
import os
import qprompt
path = qprompt.ask_str("Enter path to file", vld=lambda x: os.path.isfile(x))
size = qprompt.ask_int("Enter number less than 10", vld=lambda x: x < 10)
Exemple #29
0
def set_electron():
    global ELECTRON
    ELECTRON = qprompt.ask_str("Path to electron", blank=False)