Exemplo n.º 1
0
def make_interface_choice() -> list:
    int_list = []
    for _, value in interfaces.items():
        int_string = "{:<10}".format(value.name[:8]) + " "
        int_string += "{:<10}".format(value.provider[:8]) + " "
        int_string += "{:<10}".format(value.itype[:8]) + " "
        int_string += "{:<19}".format(value.mac) + " "
        int_string += "{:<15}".format(value.status[:15]) + " "
        int_list.append(int_string)
    cli = Check(
        prompt="  Select from the interfaces below: (Using Spacebar)",
        choices=int_list,
        check_on_switch=colors.foreground["green"],
        word_on_switch=colors.foreground["green"],
        check_color=colors.foreground["green"],
        word_color=colors.foreground["white"],
        check="√",
        shift=1,
        margin=1,
    )
    temp_list = []
    for result in cli.launch():
        temp_list.append(result.split()[0])
    print("")
    return temp_list
Exemplo n.º 2
0
def run_cli() -> Options:
    """
    Run CLI and return options
    """

    cli = VerticalPrompt(
        [
            Input("Project Name? ", default="latex_project", strip=True),
            Bullet(
                "Which template to use?",
                choices=[
                    t
                    for t in os.listdir("./latex_up/templates") if "." not in t
                ],
            ),
            Check(
                "Include lists? (Press Space to check/uncheck)",
                ["Enumerate", "Itemize", "Description"],
            ),
            Check(
                "Choose other latex structures to include. (Press Space to check/uncheck)",
                ["Graphic", "Bibtex", "Equation"],
            ),
        ],
        spacing=1,
    )

    result = cli.launch()

    return Options.from_args(result[0][1], result[1][1], *result[2][1],
                             *result[3][1])
def ask_interfaces(_interfaces):
    """

    Parameters
    ----------
    _interfaces

    Returns
    -------

    """
    click.echo('\n')  # terminal new line
    choices = [f'dns[{itf["dns"]}], ip[{itf["ip"]}]' for itf in _interfaces]
    select_interfaces_cli = Check(
        prompt=f"Choose interfaces: input <space> to choose, then input <enter> to finish",
        choices=choices,
        align=4,
        margin=1,
    )
    selected_interfaces = select_interfaces_cli.launch()
    selected_interfaces = list(
        filter(
            lambda itf: f'dns[{itf["dns"]}], ip[{itf["ip"]}]' in selected_interfaces,
            _interfaces,
        ),
    )
    return selected_interfaces
Exemplo n.º 4
0
    def start_instance(self):
        ec2 = boto3.resource('ec2', region_name=self.region)
        instance_iterator = ec2.instances.all()

        instance_list = []

        for i in instance_iterator:
            if not i.tags:
                name = ""
            else:
                name_tag = [x['Value'] for x in i.tags if x['Key'] == 'Name']
                name = name_tag[0] if len(name_tag) else ''
            tmp = i.id + self.splitter + i.state['Name'] + self.splitter + name
            instance_list.append(tmp)

        if not instance_list:
            print('No EC2 instance in ' + self.region + '.')
            exit(127)

        cli = Check(prompt="Hit <Space Bar> to check instances:",
                    choices=instance_list,
                    indent=0,
                    align=3,
                    margin=2,
                    shift=1,
                    pad_right=3,
                    check='✅')
        selected = cli.launch()

        for s in selected:
            instance_id = s.split(self.splitter)[0]
            print('Starting ' + instance_id + '\n')

            res = ec2.Instance(instance_id).start()
Exemplo n.º 5
0
def file_types_prompt(prompt, valid_file_types=VigFile.ALL):
    if not prompt:
        prompt = "Select one or multiple file types from the list below:"
    choices = {f"{f}": f for f in VigFile if int(f) & valid_file_types == f}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    file_types_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    file_types = []
    while not file_types:
        subprocess.run(["clear"])
        print_message(prompt, fg="bright_yellow", bold=True, underline=True)
        result = file_types_prompt.launch()
        if not result:
            print_error("\nYou must select at least one file type!")
            pause(message="Press any key to continue...")
            continue
        file_types = [choices[sel] for sel in result]
    return file_types
Exemplo n.º 6
0
def multi_season_prompt(db_session, prompt=None, heading=None):
    if not prompt:
        prompt = "Select one or multiple seasons from the list below:"
    all_seasons = db.Season.get_all_regular_seasons(db_session)
    choices = {f"{season.year}": season.year for season in all_seasons}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    seasons_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    selected_years = []
    while not selected_years:
        subprocess.run(["clear"])
        if heading:
            print_heading(heading, fg="bright_yellow")
        print_message(prompt, wrap=True)
        result = seasons_prompt.launch()
        if not result:
            print_error("\nYou must select at least one season!")
            pause(message="Press any key to continue...")
            continue
        selected_years = [choices[sel] for sel in result]
    return selected_years
Exemplo n.º 7
0
def ask_graphs(graphs):
    """
    1つのホストに対して行う
    return graphs: [dicts]
    """
    click.echo('\n')  # terminal new line
    choices = ['all']
    choices.extend([f'{graph["host"]}: {graph["name"]}' for graph in graphs])

    # 入力のバリデーションするのでwhile回す
    while True:
        select_graphs_cli = Check(
            prompt=
            f"Choose graph: input <space> to choose, then input <enter> to finish",
            choices=choices,
            align=4,
            margin=1,
        )
        selected_graphs = select_graphs_cli.launch()
        if 'all' in selected_graphs:
            if len(selected_graphs) != 1:
                # When select all, be able to select only all.
                click.echo('Select only all.')
                continue
            else:
                return graphs

        selected_graphs = list(
            filter(
                lambda graph: f'{graph["host"]}: {graph["name"]}' in
                selected_graphs,
                graphs,
            ))
        return selected_graphs
Exemplo n.º 8
0
def mark_deletion(dir):
    if os.path.exists(dir):
        filenames = sorted(os.listdir(dir), reverse=True)
        if filenames:
            not_dotfiles = [f for f in filenames if not f.startswith(".")]
            cprint(f"Mark listened with [Space]. [Enter] to continue.", "red")
            cli = Check(choices=not_dotfiles,
                        check="X ",
                        check_color=colors.foreground["red"])
            return cli.launch()
Exemplo n.º 9
0
def list_room(client: AsyncClient):
    selection=[]
    user_id=ARGS.user
    with open(
            f"{OUTPUT_DIR}/.env/rooms_list.{user_id}.txt","w"
            ) as rlist:
        for room_id, room in client.rooms.items():
            selection.append( f"{room_id} -> {room.display_name}")
         #   print(selection)

        cli = Check(choices=selection)
        result=cli.launch()
        #rlist.write(f"{room_id}, {room.display_name}\n")
        final=""
        for val in result:
            val=re.sub(":smart4.*","",re.sub("!","",val))
            final=final + val+"\n"
        rlist.write(final)
    return client
Exemplo n.º 10
0
def ask_hosts(hosts):
    """
    host を選択する
    return selected_hosts: [dict]
    """
    click.echo('\n')  # ターミナルをリフレッシュ

    select_hostnames_cli = Check(
        prompt=
        "Choose instance: input <space> to choose, then input <enter> to finish",
        choices=[host['name'] for host in hosts],
        align=4,
        margin=1,
    )
    hostnames = select_hostnames_cli.launch()
    selected_hosts = list(filter(lambda host: host['name'] in hostnames,
                                 hosts))

    return selected_hosts
Exemplo n.º 11
0
def setup_experimental_flags(data):
    print_wrapped(
        _("EWS does not require any configuration, you only need to scan "
          "a QR code when you start up EH Forwarder Bot. It’s as simple as "
          "that.\n"
          "\n"
          "We has provided some experimental features that you can use. "
          "They are not required to be enabled for EWS to work. If you do not "
          "want to enable these feature, just press ENTER, and you are good to go."
          ))

    widget = YesNo(prompt=_("Do you want to config experimental features? "),
                   prompt_prefix="[yN] ")
    if not widget.launch(default="n"):
        return

    for key, value in flags_settings.items():
        default, cat, params, desc = value
        if data.data['flags'].get(key) is not None:
            default = data.data['flags'].get(key)
        print()
        print(key)
        print_wrapped(desc)
        if cat == 'bool':
            prompt_prefix = '[Yn] ' if default else '[yN] '
            ans = YesNo(prompt=f"{key}? ",
                        prompt_prefix=prompt_prefix) \
                .launch(default='y' if default else 'n')

            data.data['flags'][key] = ans
        elif cat == 'int':
            ans = Numbers(prompt=f"{key} [{default}]? ") \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'choices':
            ans = Bullet(prompt=f"{key}?", choices=params) \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'multiple':
            ans = Check(prompt=f"{key}?",
                        choices=params).launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'str':
            ans = input(f"{key} [{default}]: ")
            data.data['flags'][key] = ans or default
        else:
            print(_("Skipped."))

    print(_("Saving configurations..."), end="", flush=True)
    data.save()
    print(_("OK"))
Exemplo n.º 12
0
def get_user_picked_domains_to_change():
    # List Route 53 domains
    response = r53domains.list_domains()
    domain_list = []
    for domain in response["Domains"]:
        domain_list.append(domain["DomainName"])
    # Prompt user to pick which domains they want
    domains = Check(
        "Which domains would you like to update? (Press space to (de)select a domain)",
        choices=domain_list,
    ).launch()
    print("\nYou selected:")
    for d in domains:
        print(d)
    print("\n")
    return domains
Exemplo n.º 13
0
from bullet import Bullet
from bullet import Check
from bullet import styles

client = Check(prompt="Choose from a list: ", **styles.Example, **styles.Exam)
print('\n', end='')
result = client.launch()
print(result)
Exemplo n.º 14
0
 def rlaunch(self, key, depth):
   results = {}
   section_config = self.configuration[key]
   if section_config["prompt_type"] == "Check":
     ui = Check(section_config["prompt"],
                choices=section_config["choices"],
                check=" √",
                margin=2,
                check_color=colors.bright(colors.foreground["red"]),
                check_on_switch=colors.bright(colors.foreground["red"]),
                background_color=colors.background["black"],
                background_on_switch=colors.background["white"],
                word_color=colors.foreground["white"],
                word_on_switch=colors.foreground["black"],
                indent=depth * 2)
     choices = ui.launch()
     branching = section_config.get("branching")
     if branching is not None:
       for sub_key in choices:
         branching_key = branching.get(sub_key)
         if branching_key is not None:
           if branching_key.startswith("."):
             results[sub_key] = self.rlaunch("{}{}".format(key, branching_key), depth)
           else:
             results[sub_key] = self.rlaunch(branching_key, depth)
         else:
           raise ValueError("the key {} is not in branching {}".format(sub_key, branching.keys()))
       return results
     else:
       return results
   if section_config["prompt_type"] == "ListInput":
     ui = ListInput(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "Input":
     ui = Input(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "YesNo":
     ui = YesNo(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       default=section_config["default"] if "default" in section_config else 'y',
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "Bullet":
     ui = Bullet(section_config["prompt"],
           choices=section_config["choices"],
           bullet=" >",
           margin=2,
           bullet_color=colors.bright(colors.foreground["cyan"]),
           background_color=colors.background["black"],
           background_on_switch=colors.background["black"],
           word_color=colors.foreground["white"],
           word_on_switch=colors.foreground["white"],
           indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "GoTo":
     for sub_key in section_config["goto"]:
       if sub_key.startswith("."):
         sub_value = self.rlaunch("{}{}".format(key, sub_key), depth)
         sub_key = sub_key[1:]
       else:
         sub_value = self.rlaunch(sub_key, depth)
       if isinstance(sub_value, bool) or sub_value:
         # If True/False or other non-empty data (! "", [], {})
         results[sub_key] = sub_value
     return results
Exemplo n.º 15
0
def canvas_git_map_table_wizard(course : Course) -> Table:
    """Create a Canvas-Git map CSV file."""
    students = course.students()

    if len(students) <= 0:
        warn((f"No students found for course '{course.name}'."))
        return Table([])

    number_of_students  = len(students)
    head                = min(number_of_students, HEAD)
    number_shown        = head if head < number_of_students else "all"
    table               = tabulate([s.fields() for s in students[:head]], headers = "keys")

    inform((f"Found {len(students)} students for this course. "
            f"Showing available data for {number_shown} of them: \n\n"
            f"{table}\n"))

    canvas_id_key = CANVAS_LOGIN_ID
    inform((f"The column '{canvas_id_key}' contains students' Canvas ID."))

    cli = VerticalPrompt([
        Bullet(
            prompt  = ASK_GIT_ID,
            choices = PUBLIC_USER_FIELDS,
            bullet  = " >",
            margin  = 2,
            align   = 1,
            shift   = 1,
        ),
        Check(
            prompt  = ASK_EXTRA_COLUMNS,
            choices = PUBLIC_USER_FIELDS,
            check   = " >",
            margin  = 2,
            align   = 1,
            shift   = 1,
        ),
    ])

    git_id_key, extra_columns = [r for (p, r) in cli.launch()]

    data = []

    for student in students:
        row = {}
        fields = student.fields()

        if canvas_id_key in fields:
            row[CANVAS_ID] = fields[canvas_id_key]
        else:
            row[CANVAS_ID] = ""

        if git_id_key in fields:
            row[GIT_ID] = fields[git_id_key]
        else:
            row[GIT_ID] = ""

        for column in extra_columns:
            if column in fields:
                row[column] = fields[column]
            else:
                row[column] = ""

        data.append(row)

    return Table(data)
Exemplo n.º 16
0
            margin = 2,
            bullet_color = colors.bright(colors.foreground["cyan"]),
            background_color = colors.background["black"],
            background_on_switch = colors.background["black"],
            word_color = colors.foreground["white"],
            word_on_switch = colors.foreground["white"]
        ),
        Check("What food do you like? ",
            choices = ["🍣   Sushi", 
                       "🍜   Ramen",
                       "🌭   Hotdogs", 
                       "🍔   Hamburgers", 
                       "🍕   Pizza",
                       "🍝   Spaghetti",
                       "🍰   Cakes",
                       "🍩   Donuts"],
            check = " √",
            margin = 2,
            check_color = colors.bright(colors.foreground["red"]),
            check_on_switch = colors.bright(colors.foreground["red"]),
            background_color = colors.background["black"],
            background_on_switch = colors.background["white"],
            word_color = colors.foreground["white"],
            word_on_switch = colors.foreground["black"]
        ),
    ]
)

print('\n')
result = cli.launch()
cli.summarize()
Exemplo n.º 17
0
# -*- coding: utf-8 -*-
"""
A module for adding shebang and encoding to python files
"""
from os import listdir

from bullet import Check

SHEBANG = "#!/usr/bin/env python3\n"
ENCODING = "# -*- coding: utf-8 -*-\n"

ALL_FILES = listdir(path=".")

PYTHON_FILES = [file for file in ALL_FILES if file.endswith(".py")]

CLI = Check(prompt="Choose an option:", choices=PYTHON_FILES)

RESULT = CLI.launch()

NEEDED = None
for file in RESULT:
    with open(file=file, mode="r") as f:
        FIRST_LINE = f.readline()
        SECOND_LINE = f.readline()
        if FIRST_LINE == SHEBANG and SECOND_LINE == ENCODING:
            print(f"Shebang and encoding present in {file}.")
        elif FIRST_LINE == SHEBANG and SECOND_LINE != ENCODING:
            print(f"Shebang present in {file}, but not encoding.")
            NEEDED = "encoding"
        else:
            print(f"Shebang and encoding not present in {file}.")