Esempio n. 1
0
def init(mpy, path, name=None, template=None):
    """Create new Micropython Project.

    \b When creating a new project, all files will be placed under the
    generated <PROJECT_NAME> folder.

    """
    mpy.log.title("Creating New Project")
    if not path:
        path = Path.cwd()
        default_name = path.name
        prompt_name = prompt.text("Project Name", default=default_name).ask()
        name = prompt_name.strip()
    if not template:
        templates = modules.TemplatesModule.TEMPLATES.items()
        templ_choices = [Choice(str(val[1]), value=t) for t, val in templates]
        template = prompt.checkbox(f"Choose any Templates to Generate",
                                   choices=templ_choices).ask()
    stubs = [Choice(str(s), value=s) for s in mpy.stubs]
    if not stubs:
        mpy.log.error("You don't have any stubs!")
        mpy.log.title(
            "To add stubs to micropy, use $[micropy stubs add <STUB_NAME>]")
        sys.exit(1)
    stub_choices = prompt.checkbox(f"Which stubs would you like to use?",
                                   choices=stubs).ask()
    project = Project(path, name=name)
    project.add(modules.StubsModule(mpy.stubs, stubs=stub_choices))
    project.add(modules.PackagesModule('requirements.txt'))
    project.add(modules.DevPackagesModule('dev-requirements.txt'))
    project.add(
        modules.TemplatesModule(templates=template, run_checks=mpy.RUN_CHECKS))
    proj_relative = project.create()
    mpy.log.title(f"Created $w[{project.name}] at $w[./{proj_relative}]")
Esempio n. 2
0
def init(path, name=None, template=None):
    """Create new Micropython Project

    \b
    When creating a new project, all files will be
    placed under the generated <PROJECT_NAME> folder.
    """
    mp = MicroPy()
    mp.log.title("Creating New Project")
    if not path:
        path = Path.cwd()
        default_name = path.name
        prompt_name = prompt.text("Project Name", default=default_name).ask()
        name = prompt_name.strip()
    if not template:
        templ_choices = [Choice(str(val[1]), value=t)
                         for t, val in Project.TEMPLATES.items()]
        template = prompt.checkbox(
            f"Choose any Templates to Generate", choices=templ_choices).ask()
    stubs = [Choice(str(s), value=s) for s in mp.STUBS]
    if not stubs:
        mp.log.error("You don't have any stubs!")
        mp.log.title(
            "To add stubs to micropy, use $[micropy stubs add <STUB_NAME>]")
        sys.exit(1)
    stub_choices = prompt.checkbox(
        f"Which stubs would you like to use?", choices=stubs).ask()
    project = Project(path,
                      name=name,
                      templates=template,
                      stubs=stub_choices,
                      stub_manager=mp.STUBS)
    proj_relative = project.create()
    mp.log.title(f"Created $w[{project.name}] at $w[./{proj_relative}]")
Esempio n. 3
0
def config(file):
    """Настройки"""
    if file:
        click.echo(CFG_PATH)
    else:
        config_data = defaultdict(lambda: "")
        config_data['redmine.host'] = questionary.text('Укажите URL').ask()
        auth_method = questionary.select('Выберите метод авторизации',
                                         ['Token', 'Login']).ask()

        if auth_method == 'Token':
            config_data['redmine.token'] = questionary.password(
                'Укажите Token').ask()
        elif auth_method == 'Login':
            config_data['redmine.username'] = questionary.text(
                'Укажите Логин').ask()
            config_data['redmine.password'] = questionary.password(
                'Укажите Пароль').ask()

        rd = get_rd(config_data)

        projects = get_projects(rd)
        projects_map = {str(v): v for v in projects}
        selected_project = questionary.select('Укажите ProjectID',
                                              list(projects_map.keys())).ask()
        config_data['project.id'] = projects_map[selected_project].id
        cf_fields = get_custom_fields(rd)
        cf_fields_map = {str(v): cf_id for cf_id, v in cf_fields.items()}
        cf_filter_selected = questionary.checkbox(
            'Какие настраиваемые поля использовать?',
            choices=list(cf_fields_map.keys())).ask()
        cf_filter_selected_release = questionary.checkbox(
            'Какие настраиваемые поля использовать для релиза?',
            choices=list(cf_fields_map.keys())).ask()

        config_data['release.filter_custom_fields'] = list(
            map(str, [cf_fields_map[cf] for cf in cf_filter_selected]))
        config_data['issue.filter_custom_fields'] = list(
            map(str, [cf_fields_map[cf] for cf in cf_filter_selected_release]))

        tracker = get_trackers_project(rd, config_data['project.id'])
        statuses = get_status_project(rd)
        status_map = {str(v): v for v in statuses}
        tracker_map = {str(v): v for v in tracker}

        selected_tracker = questionary.select('Выберите трекер с релизами',
                                              list(tracker_map.keys())).ask()
        selected_status = questionary.select(
            'Выберите статус опубликованого релиза',
            list(status_map.keys())).ask()

        config_data['release.tracker_id'] = tracker_map[selected_tracker].id
        config_data['release.done_status_id'] = status_map[selected_status].id

        if questionary.confirm('Сохранить').ask():
            cfg.update(config_data.items())
            cfg.sync()
            click.secho('Сохраннено', bold=True)
Esempio n. 4
0
def process_pr_checklist(api, console, pr_tasks):
    choices = [{'name': t.name} for t in pr_tasks]
    questionary.checkbox(
        'Complete the merge checklist',
        choices=choices,
        validate=lambda answers:
        (True if len(answers) == len(choices) else
         'All items on the checklist must be completed')).ask()
    with console.status(
            '[bold green]Completing checklist items on Todoist...') as _:
        for task in pr_tasks:
            console.print("Marking '{}' as complete".format(task.name))
            task.complete(api)
Esempio n. 5
0
def ask_for_taco():
    receipt = Receipt()
    receipt.add_parent(Constants.TACO_PARENT_KEY).set_price(
        Constants.BASE_TACO_PRICE)

    shell_args = questionary.select('choose a shell',
                                    Constants.SHELLS,
                                    use_shortcuts=True).ask().split('+', 1)
    handle_additional_price_selection(
        receipt, shell_args, prefix_keys=(Constants.TACO_PARENT_KEY, ))

    meat_args = questionary.select('choose your meat',
                                   Constants.MEATS,
                                   use_shortcuts=True).ask().split('+', 1)
    handle_additional_price_selection(
        receipt, meat_args, prefix_keys=(Constants.TACO_PARENT_KEY, ))

    toppings = questionary.checkbox('choose your toppings',
                                    Constants.TOPPINGS,
                                    validate=topping_validator).ask()
    for topping in toppings:
        receipt.append(topping, prefix_keys=(Constants.TACO_PARENT_KEY, ))

    print('\n\n')
    total = 0
    for item in receipt.iter_items():
        if item.has_price:
            total += item.price
            print(
                f'{"  " * item.depth}{item.name} {f"(${item.price})" if item.has_price else ""}'
            )
        else:
            print(f'{"  " * item.depth}{item.name}')
    print(f'\nTOTAL: ${total}')
Esempio n. 6
0
def ask_for_region(self):
    """ask user for region to select (2-step process)"""

    selection = ["BACK"]
    choices = []
    while "BACK" in selection:
        response = questionary.select(
            "Select area by (you can go back and combine these choices):",
            choices=["continents", "regions", "countries"],
        ).ask()

        selection_items = getattr(self, response)
        if response == "regions":
            choices = (
                [Choice(r) for r in selection_items if "EU" in r]
                + [Separator()]
                + [Choice(r) for r in selection_items if "EU" not in r]
            )
        else:
            choices = [Choice(r) for r in selection_items.keys()]

        # preselect previous choices
        for choice in choices:
            if choice.value in selection:
                choice.checked = True

        current_selection = questionary.checkbox("Please select", choices=choices).ask()
        selection = selection + current_selection
        if "BACK" not in current_selection:
            selection = clean_results(selection)
        print(f"Selection: {clean_results(selection)}")

    selection = list(set(clean_results(selection)))

    return self.extract_countries(selection)
Esempio n. 7
0
 def interact(self):
     choices = []
     for key, group in FILE_GROUP.items():
         choices.append(
             questionary.Choice(f'{key} ({", ".join(group)})',
                                key,
                                checked=key in self.allowed_group))
     choices.append(
         questionary.Choice(f'Allow all',
                            'All',
                            checked='All' in self.allowed_group))
     choices.append(
         questionary.Choice(
             f'Custom',
             'custom',
             disabled=
             'Please set extra allowed extensions in `allowed_extra` config'
         ))
     while True:
         self.allowed_group = questionary.checkbox(
             'Select allowed extensions', choices).unsafe_ask()
         if len(self.allowed_group) == 0:
             print('At least one extension group must be selected.')
         elif 'All' in self.allowed_group and len(self.allowed_group) != 1:
             print('Invalid choice.')
         else:
             break
Esempio n. 8
0
 def search_stickers(self, query):
     sticker_pages = self.loop.run_until_complete(
         self.spider.crawl_search(query))
     selections = questionary.checkbox('Select stickers:',
                                       choices=list(sticker_pages)).ask()
     ids = [sticker_pages[s] for s in selections]
     return ids
Esempio n. 9
0
def remove_overflow_run_folders(path, date):
    """Cleans up unneeded run folders"""
    run_folders = sorted(
        [folder for folder in os.listdir(path) if folder.startswith("run_")])
    logger.info("The following run folders were detected:")
    for run_folder in run_folders:
        logger.info(f"* {run_folder}")
    run_folder_dict = {}
    for run_folder in run_folders:
        run_date = run_folder.replace("run_",
                                      "").split("-")[0].replace("0101", "")
        run_folder_dict[int(run_date)] = run_folder
    remove_list = []
    for run_date, run_folder in run_folder_dict.items():
        if run_date >= date:
            remove_list.append(run_folder)
    if remove_list:
        logger.info(
            f"The following will be removed, as they are beyond {date}.")
        for delete in remove_list:
            logger.info(f"* {path}/{delete}")
        logger.info(
            "You can select which ones to keep, but bear in mind that this might cause the run to crash."
        )
        logger.info("Which of the following do you want to keep?")
        runs_to_keep = questionary.checkbox(
            "Select and then push Enter, or just Enter to erase all:",
            choices=remove_list,
        ).ask()
        for keep in runs_to_keep:
            remove_list.remove(keep)
        for delete in remove_list:
            logger.info(f"Deleting {path}/{delete}")
            shutil.rmtree(f"{path}/{delete}")
Esempio n. 10
0
def filesCheckbox(files):
    '''
    Returns a checkbox of the available files.
    '''
    files_listed = [Choice(name) for name in files]
    return checkbox('Which instances do you want to load?',
                    files_listed,
                    qmark='~')
Esempio n. 11
0
    def confirm_for_conversion(self, files):
        if self.cfg.automated:
            return files

        msg = f"We found {len(files)} files, deselect to omit."
        choices = [questionary.Choice(f, checked=True) for f in files]

        return questionary.checkbox(msg, choices=choices).ask()
Esempio n. 12
0
def main(dry_run):
    action = q.select(
        "What do you want to do?",
        choices=[
            {
                "name": "init boilerplate",
                "value": INIT_BOILERPLATE
            },
            {
                "name": "create a new challenge",
                "value": NEW_CHALLENGE
            },
        ],
    ).ask()

    init_boilerplate = q.select(
        "Which boilerplate do you want to use?",
        choices=[
            q.Separator("---API---"),
            *APIS,
            q.Separator("---langs---"),
            *LANGS,
            q.Separator("---SPA---"),
            *SPAS,
        ],
    ).ask()

    api_choices = [q.Choice(x, checked=True)
                   for x in APIS] if init_boilerplate in APIS else APIS
    lang_choices = [q.Choice(x, checked=True)
                    for x in LANGS] if init_boilerplate in LANGS else LANGS
    spa_choices = [q.Choice(x, checked=True)
                   for x in SPAS] if init_boilerplate in SPAS else SPAS

    while action == NEW_CHALLENGE:
        allowed_boilerplates = q.checkbox(
            "Which boilerplates are candidates allowed to use?",
            choices=[
                q.Separator("---API---"),
                *api_choices,
                q.Separator("---langs---"),
                *lang_choices,
                q.Separator("---SPA---"),
                *spa_choices,
            ],
        ).ask()

        confirm_none = q.confirm(
            "No allowed boilerplates. Are you sure?",
            default=False,
        ).skip_if(len(allowed_boilerplates)).ask()

        if len(allowed_boilerplates) or confirm_none:
            break

    validate_bp_dir(init_boilerplate)
    sync_bp_dir(init_boilerplate, dry_run)
Esempio n. 13
0
def start():
    question = questionary.checkbox(
        "Selecteer de tafels die je wilt oefenen:",
        choices=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
    )
    tafels = question.ask()
    tafels = [int(tafel) for tafel in tafels]
    print(tafels)
    return tafels
Esempio n. 14
0
def heuristicsCheckbox():
    '''
    Returns a checkbox to select a heuristic.
    '''
    return checkbox('Which heuristic techniques do you want to use?', [
        Choice('Pick the most valuable items', 1),
        Choice('Pick the lightest items', 2),
        Choice('Pick the items with the highest value-weight ratio', 3)
    ],
                    qmark='~')
Esempio n. 15
0
def select_playlists():
    files = glob.glob('playlists/*.m3u')
    files = list(map(lambda x: {'name': x}, files))
    answers = questionary.checkbox(
        'Select Playlists',
        choices=files,
        validate=lambda val: len(val) > 0
    ).ask()

    return ask_for_order(answers)
Esempio n. 16
0
def checkbox(message, choices):
    checks = [{
        'name': choice,
        'value': idx
    } for idx, choice in enumerate(choices)]

    question = questionary.checkbox(message, choices=checks)

    answer_ids = _ask(question, _validate_empty_list)
    return [choices[idx] for idx in answer_ids]
Esempio n. 17
0
def record(action):
    """
        List all records of a view / Delete records
    """
    if action == 'ls':
        view_id = choose_view()

        response_columns = api.get_view(view_id)

        columns = response_columns.get("columns")

        response_records = api.get_records(view_id)

        # Set up column keys before add value to each column
        ls_cell = {}  # ls_cell is a dictionary
        for cell in response_records:
            unique_cell = cell["cells"]
            for value in unique_cell:
                ls_cell.setdefault(value["columnId"], [])

        # Map value to column
        for cell in response_records:
            unique_cell = cell["cells"]
            for value in unique_cell:
                if value["columnId"] in ls_cell and "value" in value:
                    ls_cell[value["columnId"]].append(value["value"])
                elif value["columnId"] in ls_cell and "value" not in value:
                    ls_cell[value["columnId"]].append("")
                else:
                    continue

        for column in columns:
            if column["id"] in ls_cell:
                ls_cell[column["name"]] = ls_cell.pop(column["id"])
            else:
                continue

        click.echo(tabulate(ls_cell, headers="keys", tablefmt="grid"))
    elif action == 'd':
        view_id = choose_view()
        response_records = api.get_records(view_id)

        ls_record_id = []
        for record in response_records:
            ls_record_id.append(record["id"])

        ls_chosen_record = questionary.checkbox(
            'Select records which you want delete',
            choices=ls_record_id).ask()

        data = {"ids": ls_chosen_record}

        api.delete_records(view_id, data)
    else:
        gridly()
Esempio n. 18
0
def pick_tasks(items, service_task):
    # Allow users to select the task lists to move tasks from
    todo_lists = []
    for item in items:
        todo_lists.append(item['title'])

    selected_lists = (questionary.checkbox(
        "Select List",
        choices=todo_lists,
    ).ask() or ['My List'])

    print(f"Moving tasks from {' and '.join(selected_lists)}.")

    #Add a date range
    min_date = questionary.text(
        "Enter minimum date in format (yyyy-mm-dd)").ask()
    min_date = min_date + 'T00:00:00.00Z'
    print(min_date)

    max_date_options = ['Now', 'Custom date']
    selected_maxDate = (questionary.rawselect(
        "Select maximum date of date range",
        choices=max_date_options,
    ).ask() or "do nothing")
    if selected_maxDate == 'Now':
        max_date = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.00Z')

    else:
        max_date = questionary.text(
            "Enter maximum date in format (yyyy-mm-dd)").ask()
        max_date = max_date + 'T00:00:00.00Z'
    print(max_date)

    #Filter completed tasks only
    completed_tasks = dict()
    for item in items:
        if item['title'] in selected_lists:
            task = service_task.tasks().list(tasklist=item['id'],
                                             showHidden=1,
                                             completedMin=min_date,
                                             completedMax=max_date).execute()

            # Filter tasks based on date range
            for i in task['items']:
                # We are concerned with date only, not time, hence splicing the date string to only include date
                if str(i['updated'])[0:10] in completed_tasks:
                    completed_tasks[str(i['updated'])[0:10]].append(i['title'])
                else:
                    completed_tasks[str(i['updated'])[0:10]] = [i['title']]

    #Sorting the tasks in ascending order of updated date
    completed_tasks = collections.OrderedDict(sorted(completed_tasks.items()))
    #print(completed_tasks)
    return completed_tasks
Esempio n. 19
0
def seed(arguments):
    print("Ingesting catalog dumps into a running Kowalski instance")

    if (not arguments.local) and (not arguments.gcs):
        raise ValueError("Source not set, aborting")

    # check configuration
    print('Checking configuration')
    check_configs(cfgs=["config.*yaml"])

    with open(pathlib.Path(__file__).parent.absolute() / "config.yaml") as cyaml:
        config = yaml.load(cyaml, Loader=yaml.FullLoader)["kowalski"]

    if arguments.local:
        path = pathlib.Path(arguments.local).absolute()

        dumps = [p.name for p in path.glob("*.dump")]

        if len(dumps) == 0:
            print(f"No dumps found under {path}")
            return False

        answer = questionary.checkbox(
            f"Found the following collection dumps. Which ones would you like to ingest?",
            choices=dumps
        ).ask()

        command = [
            "docker",
            "exec",
            "-i",
            "kowalski_mongo_1",
            "mongorestore",
            f"-u={config['database']['admin_username']}",
            f"-p={config['database']['admin_password']}",
            "--authenticationDatabase=admin",
            "--archive"
        ]

        if arguments.drop:
            command.append("--drop")

        for dump in answer:
            with open(f"{path / dump}") as f:
                subprocess.call(
                    command,
                    stdin=f
                )

    if arguments.gcs:
        # print("Make sure gsutil is properly configured")
        raise NotImplementedError()
Esempio n. 20
0
def choose_columns(view_id):
    view = api.get_view(view_id)
    options = ['All']
    columns = view["columns"]
    for column in columns:
        options.append(column["id"])

    ls_chosen_columns = questionary.checkbox('Select columns to export',
                                             choices=options).ask()
    if 'All' in ls_chosen_columns:
        return options
    else:
        return ls_chosen_columns
Esempio n. 21
0
def channels(vids):
    channels = get_all_channels()
    channel_choices = questionary.checkbox(
        "Select channels to watch",
        [channel["name"] for channel in channels]).ask()
    selected_channels = [
        channel for channel in channels if channel["name"] in channel_choices
    ]
    videos = []
    videos = get_videos(
        [channel["channel_id"] for channel in selected_channels], vids)
    videos = [video for video in videos if not have_watched(video)]
    watch(videos)
Esempio n. 22
0
    def selection_ui() -> None:
        selection = questionary.checkbox(
            "Select fabrication elements to place:",
            [
                f"{i:03} (id {elem.id_}), marked placed: {bool(elem.placed)}"
                for i, elem in enumerate(fab_elems)
            ],
        ).ask()
        selection_idx = [int(elem.split()[0]) for elem in selection]

        for i, elem in enumerate(fab_elems):
            elem.skip = i not in selection_idx
            log.debug(
                f"Element with index {i} and id {elem.id_} marked {elem.skip}")
Esempio n. 23
0
def pick(msg, options, alpha_options=None):
    choices = OrderedDict()
    for i, option in enumerate(options):
        choice_text = text_type(option)
        choices[choice_text] = option
    if alpha_options is not None:
        for k, v in alpha_options.items():
            choices[v] = k

    answer = questionary.checkbox(msg, choices=[
        {'name': x} for x in choices.keys()
    ]).ask()

    return [choices[x] for x in answer]
Esempio n. 24
0
    def showMain(self):
        questionary.text("What's your first name").ask()
        questionary.password("What's your secret?").ask()
        questionary.confirm("Are you amazed?").ask()

        questionary.select(
            "What do you want to do?",
            choices=[
                "Order a pizza", "Make a reservation", "Ask for opening hours"
            ],
        ).ask()

        questionary.rawselect(
            "What do you want to do?",
            choices=[
                "Order a pizza", "Make a reservation", "Ask for opening hours"
            ],
        ).ask()

        questionary.checkbox("Select toppings", choices=["foo", "bar",
                                                         "bazz"]).ask()

        questionary.path("Path to the projects version file").ask()
Esempio n. 25
0
def pick(msg, options, alpha_options=None):
    choices = OrderedDict()
    for i, option in enumerate(options):
        choice_text = text_type(option)
        choices[choice_text] = option
    if alpha_options is not None:
        for k, v in alpha_options.items():
            choices[v] = k

    answer = questionary.checkbox(msg,
                                  choices=[{
                                      'name': x
                                  } for x in choices.keys()]).ask()

    return [choices[x] for x in answer]
Esempio n. 26
0
def ask_pystyle(**kwargs):
    # create the question object
    question = questionary.checkbox('Select toppings',
                                    qmark='😃',
                                    choices=[
                                        Choice("foo", checked=True),
                                        Separator(),
                                        Choice("bar", disabled="nope"), 'bazz',
                                        Separator("--END--")
                                    ],
                                    style=custom_style_dope,
                                    **kwargs)

    # prompt the user for an answer
    return question.ask()
Esempio n. 27
0
    def ask(self):
        region = self.params['region']
        vpc_id = self.params['vpc_id']

        sg_choices = [
            questionary.Choice(title=s["GroupId"] + " | " + s["GroupName"],
                               value=s["GroupId"])
            for s in aws_account_util.get_available_security_groups(
                region, vpc_id)
        ]

        self.answer = questionary.checkbox("Which Security Group ID(s)?",
                                           choices=sg_choices,
                                           style=custom_style).ask()
        return self.answer
Esempio n. 28
0
    def selection_ui():
        not_placed_selection = questionary.checkbox(
            "Select fabrication elements to place:",
            [
                f"{i:03} (id {elem.id_}), marked placed: {bool(elem.placed)}"
                for i, elem in enumerate(fab_elems)
            ],
        ).ask()
        mark_not_placed_idx = [int(elem.split()[0]) for elem in not_placed_selection]

        for i, elem in enumerate(fab_elems):
            if i in mark_not_placed_idx:
                elem.placed = False
            else:
                elem.placed = True
            log.debug(f"Element with index {i} and id {elem.id_} marked {elem.placed}")
Esempio n. 29
0
def patch(count, vids):

    channels = get_all_channels()
    gumbo = random.sample(channels,
                          count if count <= len(channels) else len(channels))

    videos = []
    videos = get_videos([channel["channel_id"] for channel in gumbo], vids)
    videos = [video for video in videos if not have_watched(video)]
    if len(videos) > 0:
        vid_choices = questionary.checkbox(
            "Select Videos", [video["title"] for video in videos]).ask()
        to_watch = [video for video in videos if video["title"] in vid_choices]
        watch(to_watch)
    else:
        click.echo("All Videos watched")
Esempio n. 30
0
    def get_lambda_functions(self, args):
        if args.lambdas:
            return args.lambdas.split(',')

        lambda_list = list(self.lambda_function_generator())

        while True:
            selection = questionary.checkbox(
                "Select the bucket which contains the files to be replayed:",
                choices=sorted([f['FunctionArn'] for f in lambda_list])).ask()
            if len(selection) == 0:
                print("No selection.. try again!")
            elif len(selection) > 0:
                lambdas = selection
                break

        return lambdas
Esempio n. 31
0
 def interact(self, courses):
     choices = []
     sorted_courses = sorted(courses,
                             key=lambda course: course.enrollment_term_id)
     sorted_courses.reverse()
     for course in sorted_courses:
         choices.append(
             questionary.Choice(
                 f'{course.name} (Term {course.enrollment_term_id})',
                 course.id,
                 checked=course.id in self.course_id))
     while True:
         self.course_id = questionary.checkbox('Select courses to download',
                                               choices).unsafe_ask()
         if len(self.course_id) == 0:
             print('At least one course must be selected.')
         else:
             break