예제 #1
0
def test_skipping_of_skipping_of_questions():
    inp = create_pipe_input()
    try:
        inp.send_text("World" + KeyInputs.ENTER + "\r")

        question = text("Hello?", input=inp,
                        output=DummyOutput()).skip_if(condition=False,
                                                      default=42)

        response = question.ask()

        assert response == "World" and not response == 42
    finally:
        inp.close()
예제 #2
0
    def filter_by_date(self):

        index = int(q.text('Name').ask())
        From = q.text('From').ask()
        to = q.text('To').ask()

        self.name = self._translate_name_by_index(index)

        From = datetime.datetime.strptime(From, '%d%m%y').date()
        to = datetime.datetime.strptime(to, '%d%m%y').date()

        expenses = ExpenseCategory.objects.get(name=self.name).expenses.filter(
            date__range=(From, to))

        self.total = expenses.aggregate(total=Sum('balance_change'))['total']

        headers = ['Index', 'Description', 'Balance Change', 'Date']

        rows = [(expense.description, expense.balance_change, expense.date)
                for expense in expenses]

        self.render(headers, rows)

        self.initial_prompt()
예제 #3
0
 def run(self) -> None:
     new_1rm = None
     for i in range(len(self.cycle_rms)):
         self.print_exercise(i)
         if i > 0:
             self._rest()
             self.print_exercise(i)
         if i == len(self.cycle_rms) - 1 and self.current_cycle == 'neural':
             new_1rm = self.calculate_new_1rm()
         else:
             termios.tcflush(sys.stdin,termios.TCIFLUSH)
             if questionary.text("Done:", qmark=" ", style=style).ask() == None:
                 exit(1)
     else:
         self.update_config(new_1rm)
예제 #4
0
def prepare_pip(venv):
    venv.ensure_pip()
    if not venv.check_pyinstaller():
        venv.ask_if_install_pyinstaller()
    while 1:
        action = questionary.select(
            'Choose action of `pip`:', choices=venv.pip_action_choices).ask()
        index = venv.pip_action_choices.index(action)
        if index == 0:
            break
        elif index == 1:
            while 1:
                cmd = questionary.text(
                    "Fill text for `pip install ` (null for exit):",
                    default='pip install ').ask()
                if cmd == 'pip install ':
                    break
                venv.pip_install(cmd=cmd)
        elif index == 2:
            while 1:
                cmd = questionary.text(
                    "Fill text for `pip uninstall -y ` (null for exit):",
                    default='pip uninstall -y ').ask()
                if cmd == 'pip uninstall -y ':
                    break
                venv.pip_uninstall(cmd=cmd)
        elif index == 3:
            venv.pip_list()
        elif index == 4:
            while 1:
                cmd = questionary.text(
                    "Fill text for `pip ` (null for exit):",
                    default='pip ').ask()
                if cmd == 'pip ':
                    break
                venv.pip_custom(cmd=cmd)
예제 #5
0
def load_extract_menu():
    """Prompts user for input on data extraction and invokes extract.batch_query().

    """
    start_year_month = questionary.text(
        "What is the start year/month for data extraction? (Please enter in YYYY-MM format):",
        validate=menu_options.YearMonthValidator,
        default='2018-06',
        style=blue).ask()
    # Store start_year_month in builtins to validate for >=12 months
    builtins.start_year_month = start_year_month
    end_year_month = questionary.text(
        "What is the cutoff year/month for data extraction? (Please enter in YYYY-MM format)\nPlease ensure that the time range is at least 12 months to account for seasonality:",
        validate=menu_options.EndYearMonthValidator,
        default='2019-05',
        style=blue).ask()
    sample_size = questionary.text(
        "What is the fraction of data you wish to extract? (Please enter a fraction between 0 and 1):",
        validate=menu_options.FractionValidator,
        default='0.2',
        style=blue).ask()
    records = extract.batch_query(start_year_month, end_year_month,
                                  sample_size)
    extract.store(records, sample_size)
    # Display menu
    while True:
        choice_after = questionary.select(
            "---Extract and preprocess shipment data from database---",
            choices=['Extract data again', 'Go back to main menu', 'Exit'],
            style=blue).ask()
        if choice_after == 'Extract data again':
            load_extract_menu()
        elif choice_after == 'Go back to main menu':
            load_main_menu()
        elif choice_after == 'Exit':
            sys.exit()
예제 #6
0
def load_bank_data():
    """Ask for the file path to the latest banking data and load the CSV file.

    Returns:
        The bank data from the data rate sheet CSV file.
    """

    csvpath = questionary.text("Enter a file path to a rate-sheet (.csv):").ask()
    csvpath = Path(csvpath)
    if not csvpath.exists():
        sys.exit(f"Oops! Can't find this path: {csvpath}")



    return load_csv(csvpath)
def save_qualifying_loans(qualifying_loans):
    """Saves the qualifying loans to a CSV file.

    Args:
        qualifying_loans (list of lists): The qualifying bank loans.
    """

    save_loans = questionary.confirm("Would you like to save the loan?").ask()
    csvoutpath = questionary.text(
        "Enter a file path to save the qualifying loans sheet (.csv):").ask()
    csvoutpath = Path(csvoutpath)
    if not csvoutpath.exists():
        sys.exit(f"Oops! Can't find this path: {csvoutpath}")
    # csvoutpath = Path('c:/Users/Laptop/Documents/UC Berkeley/Module Challenges/Module 2/Starter_Code/qualifier/data/qualifying_loans.csv')
    return csvoutpath
예제 #8
0
def _correct_entities(latest_message: Dict[Text, Any],
                      endpoint: EndpointConfig,
                      sender_id: Text) -> Dict[Text, Any]:
    """Validate the entities of a user message.

    Returns the corrected entities"""

    entity_str = _as_md_message(latest_message.get("parse_data", {}))
    question = questionary.text(
        "Please mark the entities using [value](type) notation",
        default=entity_str)

    annotation = _ask_or_abort(question, sender_id, endpoint)
    # noinspection PyProtectedMember
    parsed = MarkdownReader()._parse_training_example(annotation)
    return parsed.get("entities", [])
예제 #9
0
def set_remote_credentials():
    "set remote credentials file to run the test on browserstack or saucelabs"
    platform = questionary.select("Select the remote platform on which you wish to run the test on",
                                   choices=["Browserstack","Saucelabs"]).ask()
    if platform == "Browserstack":
        platform = "BS"
    else:
        platform = "SL"
    username = questionary.text("Enter the Username").ask()
    password = questionary.password("Enter the password").ask()
    with open("conf/remote_credentials.py",'w') as cred_file:
        cred_file.write("REMOTE_BROWSER_PLATFORM = '%s'\
                         \nUSERNAME = '******'\
                         \nACCESS_KEY = '%s'"%(platform,username,password))
    questionary.print("Updated the credentials successfully",
                       style="bold fg:green")
예제 #10
0
    def calculate_new_1rm(self) -> float:
        def check(x):
            try:
                if 0 <= int(x) <= 10:
                    return True
                else:
                    return "0-10"
            except:
                return "0-10"

        reps = questionary.text("Reps lifted:", qmark=" ", validate=check, style=style).ask()
        if not reps:
            exit(1)
        ratio = self.config["percents"][self.cycle_rms[-1]
                                        ] / self.config["percents"][int(reps)]
        return round(self.one_rm * ratio, 2)
예제 #11
0
파일: projects.py 프로젝트: lichensky/gfl
    def new(self):
        id = prompt("Project ID: ", validator=UniqueID("Project", self.projects))
        key = questionary.text("Project key:").ask()
        instance_id = questionary.select(
            "Project instance:", choices=self.instances.ids()
        ).ask()
        instance = self.instances.find_by_id(instance_id)

        workflow_id = questionary.select(
            "Project workflow:", choices=self.workflows.ids()
        ).ask()
        workflow = self.workflows.find_by_id(workflow_id)


        project = Project(id, key, instance, workflow)
        self.projects.save(project)
예제 #12
0
def get_env_or_prompt(context: str, key: str) -> str:
    """Get or prompt user for chenv-specific environment variable."""
    try:
        return os.environ[key]
    except KeyError:
        pass

    emphasized_key = click.style(key, fg=Color.YELLOW.value)
    info(context, f"Environment variable {emphasized_key} is not defined.")
    value = questionary.text("Define new value:", validate=bool).ask()
    if not value:
        raise ValueError(f"Cannot set value `{value}` to `{key}`")

    settings.add(key, value)
    settings.mount()
    return value
예제 #13
0
def save_qualifying_loans(qualifying_loans):
    """Saves the qualifying loans to a CSV file.
    Args:
        qualifying_loans (list of lists): The qualifying bank loans.
    """
    # @TODO: Complete the usability dialog for savings the CSV Files.

    answer = questionary.confirm(
        'Would you like to save your qualifying loan?').ask()
    if answer == True:
        csvpath = questionary.text(
            "Enter a file path to a rate-sheet (.csv) where you want to save your copy:"
        ).ask()
        save_csv(csvpath, qualifying_loans)
    else:
        sys.exit('Thanks')
예제 #14
0
파일: console.py 프로젝트: zoovu/rasa
def _get_user_input(previous_response: Optional[Dict[str, Any]]) -> Optional[Text]:
    button_response = None
    if previous_response is not None:
        button_response = _print_bot_output(previous_response, is_latest_message=True)

    if button_response is not None:
        response = cli_utils.payload_from_button_question(button_response)
        if response == cli_utils.FREE_TEXT_INPUT_PROMPT:
            # Re-prompt user with a free text input
            response = _get_user_input({})
    else:
        response = questionary.text(
            "",
            qmark="Your input ->",
            style=Style([("qmark", "#b373d6"), ("", "#b373d6")]),
        ).ask()
    return response.strip() if response is not None else None
예제 #15
0
def cli_server_new(name, environment, system_folders):
    """Create new configuration file."""

    if not name:
        name = q.text("Please enter a configuration-name:").ask()

    # check that this config does not exist
    if util.ServerContext.config_exists(name, environment, system_folders):
        raise FileExistsError(f"Configuration {name} and environment"
                              f"{environment} already exists!")

    # create config in ctx location
    cfg_file = configuration_wizard("server",
                                    name,
                                    environment=environment,
                                    system_folders=system_folders)
    click.echo(f"New configuration created: {cfg_file}")
예제 #16
0
    def returnBook(self):
        """Return Method.
        Provides return functionality for both Student & Teacher Class."""
        with open(self.borrowPath, "r") as fileObject:
            reader = csv.reader(fileObject)
            data = [row for row in reader if len(row) == 4]
            fileObject.close()

        admNos = [row[1] for row in data]

        admNo = questionary.text(
            "Enter your adm No:",
            validate=lambda x: x in admNos,
        ).ask()

        dateBorrowed = date(2020, 1, 1)
        for row in data:
            if row[1] == admNo:
                dateBorrowed = row[3]
                comps = dateBorrowed.split("-")
                dateBorrowed = date(int(comps[0]), int(comps[1]), int(comps[2]))
                data.remove(row)

        today = date.today()

        daysBorrowed: int = (today - dateBorrowed).days

        if daysBorrowed <= 7:
            print("Amount to be Paid is Rs. 100")

        elif 7 < daysBorrowed < 50:
            print("-" * os.get_terminal_size().columns)
            print(
                f"Amount to Be Paid: {daysBorrowed*35}".center(
                    os.get_terminal_size().columns
                )
            )
            print("-" * os.get_terminal_size().columns)
        else:
            print("You have exceeded the number of days to return the book!")
            print("You must pay a fine of Rs. 500")

        with open(self.borrowPath, "w", newline="") as fileObject:
            writer = csv.writer(fileObject)
            writer.writerows(data)
            fileObject.close()
예제 #17
0
def ui_create_root_dev_investigation_task(api,
                                          project_id,
                                          work_type,
                                          extra_labels=[]):
    task_name = questionary.text(
        'Provide a name for the investigation to carry out:',
        validate=lambda answer: True
        if len(answer) > 0 else 'A name for the task must be provided').ask()
    root_task = create_parent_task(api,
                                   task_name,
                                   project_id,
                                   DevTaskType.INVESTIGATION,
                                   work_type,
                                   extra_labels=extra_labels)
    root_task_id = root_task['id']
    print()
    return root_task_id
예제 #18
0
def generate_choices(makefile_targets, keyword):
    base_choices = ['Quit MakeMe (ctrl+c)']
    if makefile_targets:
        title = f"Targets matching '{keyword}'" if keyword else 'Choose a target'
        answer = questionary.select(
            title,
            choices=base_choices + makefile_targets,
            style=style,
        ).ask()
        if not answer or answer == base_choices[0]:
            sys.exit()  # Bail out
        print(answer)
        if '%' in answer:
            follow_up_answer = questionary.text(
                f'Replace % in {answer} with:').ask()
            answer = answer.replace('%', follow_up_answer, 1)
        return answer
예제 #19
0
    def get_rice_amount(self) -> int:
        """"Asks the user how much rice they want to cook.

        PARAMETERS:
        None

        RETURNS:
        Amount of rice wanted as an int.
        """
        try:
            return int(
                questionary.text(
                    "Thank you! Now tell me how much you want to cook in grams\n"
                ).ask())
        except Exception:
            print("Please input a number (without decimal points!)")
            return self.get_rice_amount()
예제 #20
0
def load_bank_data():
    """Ask for the file path to the latest banking data and load the CSV file.

    Returns:
        The bank data from the data rate sheet CSV file.
    """
    # Questioning user and storing answer to a variable.
    csvpath = questionary.text(
        "Enter a file path './data/daily_rate_sheet.csv':").ask()
    # Removing space and normalizing data input to lower case.
    csvpath = csvpath.replace(" ", "").lower()
    csvpath = Path(csvpath)
    # Validates input file daily_rate_sheet.csv location.
    if not csvpath.exists():
        sys.exit(f"Oops! Can't find this path: {csvpath}")

    return load_csv(csvpath)
예제 #21
0
파일: scaffold.py 프로젝트: ChenHuaYou/rasa
def run(args: argparse.Namespace) -> None:
    import questionary

    print_success("Welcome to Rasa! 🤖\n")
    if args.no_prompt:
        print(f"To get started quickly, an "
              f"initial project will be created.\n"
              f"If you need some help, check out "
              f"the documentation at {DOCS_BASE_URL}.\n")
    else:
        print(f"To get started quickly, an "
              f"initial project will be created.\n"
              f"If you need some help, check out "
              f"the documentation at {DOCS_BASE_URL}.\n"
              f"Now let's start! 👇🏽\n")

    if args.init_dir is not None:
        path = args.init_dir
    else:
        path = (questionary.text(
            "Please enter a path where the project will be "
            "created [default: current directory]").skip_if(args.no_prompt,
                                                            default="").ask())
        # set the default directory. we can't use the `default` property
        # in questionary as we want to avoid showing the "." in the prompt as the
        # initial value. users tend to overlook it and it leads to invalid
        # paths like: ".C:\mydir".
        # Can't use `if not path` either, as `None` will be handled differently (abort)
        if path == "":
            path = "."

    if args.no_prompt and not os.path.isdir(path):
        print_error_and_exit(f"Project init path '{path}' not found.")

    if path and not os.path.isdir(path):
        _ask_create_path(path)

    if path is None or not os.path.isdir(path):
        print_cancel()

    if not args.no_prompt and len(os.listdir(path)) > 0:
        _ask_overwrite(path)

    telemetry.track_project_init(path)

    init_project(args, path)
예제 #22
0
    def _ask_tag_format(self, latest_tag) -> str:
        is_correct_format = False
        if latest_tag.startswith("v"):
            tag_format = r"v$version"
            is_correct_format = questionary.confirm(
                f'Is "{tag_format}" the correct tag format?',
                style=self.cz.style).ask()

        if not is_correct_format:
            tag_format = questionary.text(
                'Please enter the correct version format: (default: "$version")',
                style=self.cz.style,
            ).ask()

            if not tag_format:
                tag_format = "$version"
        return tag_format
예제 #23
0
    def playlist_download(self):
        playlists = self.spotify.get_user_playlists()

        choices = [questionary.Choice("Saved Music", value=0)]
        choices.extend(
            [
                questionary.Choice(playlists[i].name, value=i + 1)
                for i in range(len(playlists))
            ]
        )

        answers = questionary.form(
            filename=questionary.text("What should the file be named?"),
            playlist_idx=questionary.select(
                "Which playlist would you like to download?", choices=choices
            ),
        ).ask()

        playlist_idx = answers["playlist_idx"]

        tracklist: List[tekore.model.FullTrack]

        if playlist_idx == 0:
            # Saved music
            tracklist = self.spotify.get_user_library()
        else:
            # Other playlist
            paging_tracks = playlists[playlist_idx - 1].tracks
            tracklist = [
                track.track for track in paging_tracks.items if not track.is_local
            ]

        processed_tracks = [
            {
                "Title": track.name,
                "Album Artist": ", ".join(
                    [artist.name for artist in track.album.artists]
                ),
                "Album": track.album.name,
            }
            for track in tracklist
        ]

        pyexcel.save_as(
            records=processed_tracks, dest_file_name=answers["filename"] + ".xlsx"
        )
예제 #24
0
def run(args: argparse.Namespace) -> None:
    import questionary

    print_success("Welcome to Rasa! 🤖\n")
    if args.no_prompt:
        print(
            "To get started quickly, an "
            "initial project will be created.\n"
            "If you need some help, check out "
            "the documentation at {}.\n".format(DOCS_BASE_URL)
        )
    else:
        print(
            "To get started quickly, an "
            "initial project will be created.\n"
            "If you need some help, check out "
            "the documentation at {}.\n"
            "Now let's start! 👇🏽\n".format(DOCS_BASE_URL)
        )

    if args.init_dir is not None:
        path = args.init_dir
    else:
        path = (
            questionary.text(
                "Please enter a path where the project will be "
                "created [default: current directory]",
                default=".",
            )
            .skip_if(args.no_prompt, default=".")
            .ask()
        )

    if args.no_prompt and not os.path.isdir(path):
        print_error_and_exit(f"Project init path '{path}' not found.")

    if path and not os.path.isdir(path):
        _ask_create_path(path)

    if path is None or not os.path.isdir(path):
        print_cancel()

    if not args.no_prompt and len(os.listdir(path)) > 0:
        _ask_overwrite(path)

    init_project(args, path)
예제 #25
0
파일: node.py 프로젝트: tim-hendriks/ppDLI
def cli_node_new_configuration(name, environment, system_folders):
    """Create a new configation file.
    
    Checks if the configuration already exists. If this is not the case
    a questionaire is invoked to create a new configuration file.
    """
    # select configuration name if none supplied
    if not name:
        name = q.text("Please enter a configuration-name:").ask()

    # check that this config does not exist
    if util.NodeContext.config_exists(name, environment, system_folders):
        raise FileExistsError(f"Configuration {name} and environment"
                              f"{environment} already exists!")

    # create config in ctx location
    cfg_file = configuration_wizard("node", name, environment=environment)
    click.echo(f"New configuration created: {cfg_file}")
예제 #26
0
def create_new_entity():

    entity_class = dialoge_entity_type()
    dir_name = questionary.text("directory name?",
                                default="unnamed_entity").ask()

    try:
        os.mkdir(dir_name)
    except FileExistsError:
        print(yellow(f"directory `{dir_name}` already exists!"))
        q = input("Write into it? (y|N)")
        if q != "y":
            print(bred("aborted."))

    field_values = dialoge_field_values(entity_class)

    path = os.path.join(dir_name, "metadata.yml")
    core.convert_dict_to_yaml(field_values, target_path=path)
예제 #27
0
def get_mobile_os_version(mobile_os_name):
    "Get mobile OS version"
    if mobile_os_name == "Android":
        mobile_os_version = questionary.select("Select the Mobile OS version",
                                                choices=["6.0","7.0","7.1",
                                                "8.0","8.1","9.0",
                                                "Other versions"]).ask()

    elif mobile_os_name == "iOS":
        mobile_os_version = questionary.select("Select the Mobile OS version",
                                                choices=["8.0","9.0","10.0","11.0",
                                                "12.0","13.0","14.0",
                                                "Other versions"]).ask()

    if mobile_os_version == "Other versions":
        mobile_os_version = questionary.text("Enter the OS version").ask()

    return mobile_os_version
예제 #28
0
def get_value(client_var, question):
    """
    Retrieve a specific client input value.

    :param client_var: Clientele financial variable.
    :param question: Question to be asked.
    :type client_var: float
    :type question: str
    """
    while True:
        try:
            client_var = float(questionary.text(question).ask())
            break
        except:
            print("Please enter numerical values only. ")

    # Return client variable.
    return client_var
예제 #29
0
def get_pr_title(body):
    # The regex matches these types of lines in the body:
    # - 72988e92f **feat: extend `nrs register` with more output**
    # It's parsing the text between the opening and closing ** characters.
    matches = re.findall(r'-.*\*\*(.*)\*\*', body, re.MULTILINE)
    selected = questionary.checkbox(
        'Select ONE of the following commit messages for the PR title. \n' \
        'If none of these choices are appropriate, do not select any of them.',
        choices=matches
    ).ask()
    if selected:
        title = selected[0]
    else:
        title = questionary.text(
            'Please supply the title for the PR:',
            validate=lambda answer:
            (True if len(answer) > 5 else
             'Please provide a title with at least 5 characters')).ask()
    return title
예제 #30
0
def grid(action):
    """
        List all Grids / Update Grid name
    """
    if action == 'ls':
        db_id = choose_database()
        response = api.get_grids(db_id)
        for grid in response:
            click.echo(grid["name"])
    elif action == 'u':
        grid_id = choose_grid()

        grid_name = questionary.text("New Grid name:").ask()
        data = {"name": grid_name}
        api.update_grid(grid_id, data)

        click.echo("Your Grid has been changed")
    else:
        gridly()