Exemple #1
0
def main():
    account_input = Input('请输入你的学号:')
    password_input = Password('请输入你的密码:')
    slide = SlidePrompt([account_input, password_input])
    res = slide.launch()
    account = res[0][1]
    password = res[1][1]
    student = Student(account, password)
    port_confirm_input = YesNo('是否自定义教务系统端口?')
    slide = SlidePrompt([port_confirm_input])
    res = slide.launch()
    port_confirm = res[0][1]
    if port_confirm:
        port_input = Input('请输入你要自定义的端口:')
        slide = SlidePrompt([port_input])
        res = slide.launch()
        student.urp.port = res[0][1]
    while True:
        choices_list = ['成绩导出', '一键评教', '退出']
        choice_input = Bullet('请选择你要进行操作:', choices=choices_list, margin=1)
        slide = SlidePrompt([choice_input])
        res = slide.launch()
        choice = res[0][1]
        if choice == choices_list[0]:
            student.export_grade()
        elif choice == choices_list[1]:
            student.judge_all()
        elif choice == choices_list[2]:
            exit_confirm_input = YesNo('确认退出?')
            slide = SlidePrompt([exit_confirm_input])
            res = slide.launch()
            if res[0][1]:
                sys.exit()
def add_user_to_group(user_name):
    groups = iam.list_groups()
    adding_groups = True
    added_groups = []
    group_list = []
    for group in groups.get('Groups'):
        group_names = group.get('GroupName')
        group_list.append(group_names)
    while adding_groups:
        group_cli = Bullet(prompt="\nPlease choose a group: ",
                           choices=group_list,
                           indent=0,
                           align=5,
                           margin=2,
                           shift=0,
                           bullet="",
                           pad_right=5)
        group_result = group_cli.launch()
        added_groups.append(group_result)
        user_group = iam.add_user_to_group(GroupName=group_result,
                                           UserName=user_name)
        group_list.remove(group_result)
        cli = YesNo("Would you like to add the user to another group? ")
        result = cli.launch()
        if not result:
            adding_groups = False

    return added_groups
def setup_network_configurations(data):
    print()
    proceed = YesNo(prompt=_("Do you want to adjust network configurations? "
                             "(connection timeout) "),
                    default="n",
                    prompt_prefix="[yN] ").launch()
    if not proceed:
        return

    print_wrapped(_(
        "For meanings and significances of the following values, please "
        "consult the module documentations."
    ))
    print()
    print("https://etm.1a23.studio/")
    print()

    if YesNo(prompt=_("Do you want to change timeout settings? "),
             prompt_prefix="[yN] ", default="n").launch():
        if data.data.get('request_kwargs') is None:
            data.data['request_kwargs'] = {}
        data.data['request_kwargs']['read_timeout'] = \
            Numbers(prompt=_("read_timeout (in seconds): ")).launch()
        data.data['request_kwargs']['connect_timeout'] = \
            Numbers(prompt=_("connect_timeout (in seconds): ")).launch()
def programmatic_access(user_name):
    cli = YesNo("Would you like to allow programmatic access? ")
    result = cli.launch()
    if result:
        access = iam.create_access_key(UserName=user_name)
        access_key_id = access['AccessKey']['AccessKeyId']
        secret_access_key = access['AccessKey']['SecretAccessKey']
    else:
        access_key_id = None
        secret_access_key = None

    return access_key_id, secret_access_key
def ensure_secrets_basedir(
    secrets_basedir=None,
    allow_create=False,
    allow_prompt=False,
    verbose_level=1,
):
    """
    Ensure that the secrets basedir exists.

    If the path is within the user's home directory, it is OK to
    create the directory automatically if it does not exist. This was
    the original behavior. If the path does exist and contains file,
    but does not have the special marker, that will be considered
    an error the user needs to resolve.

    For paths that lie outside the user's home directory, the user
    must explicitly confirm that it is OK to create the directory
    by responding to prompts (when possible) or by using the
    `--init` option flag or `psec init` command.
    """
    if secrets_basedir is None:
        secrets_basedir = get_default_secrets_basedir()
    homedir = str(Path.home())
    allow_create = (allow_create or str(secrets_basedir).startswith(homedir))
    try:
        is_secrets_basedir(basedir=secrets_basedir, raise_exception=True)
    except BasedirNotFoundError as err:
        if verbose_level > 0:
            logger.info(str(err))
        if not allow_create:
            if allow_prompt:
                client = YesNo(f"create directory '{secrets_basedir}'? ",
                               default='n')
                result = client.launch()
                if not result:
                    sys.exit("[!] cancelled creating '%s'", secrets_basedir)
            else:
                sys.exit("[-] add the '--init' flag or use 'psec init' "
                         "to initialize secrets storage")
        secrets_basedir_create(basedir=secrets_basedir)
        if verbose_level >= 1:
            logger.info("[+] initialized secrets storage in '%s'",
                        secrets_basedir)
    except InvalidBasedirError as err:
        sys.exit(str(err))
    # else:
    #     if verbose_level >= 1:
    #         logger.info(
    #             "[+] secrets storage already initialized in '%s'",
    #             secrets_basedir
    #         )
    return Path(secrets_basedir)
Exemple #6
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"))
def parse_config():
    cli = VerticalPrompt(
        [
            Bullet("choice env? ",
                   choices=['test', 'new-test']),
        ],
        spacing=1
    )
    result = cli.launch()
    _, subj = result[0]
    if subj == 'new-test':
        subj = 'test-next'

    log = ["  "] + get_git_log('/mnt/api-site', 'ydl', subj)
    cli = VerticalPrompt(
        [
            Bullet("choice git log: ",
                   choices=log),
            YesNo("send? "),
        ],
        spacing=1
    )
    result = cli.launch()
    _, text = result[0]
    _, yes_or_no = result[1]
    return subj, text, yes_or_no
def setup_rpc(data):
    print()
    print_wrapped(_(
        "To learn about what RPC is and what it does, please "
        "visit the module documentations."
    ))
    print()
    print("https://etm.1a23.studio/")
    print()

    proceed = YesNo(prompt=_("Do you want to enable RPC interface? "),
                    prompt_prefix="[yN] ").launch(default='n')
    if not proceed:
        return

    server = "127.0.0.1"
    port = 8000

    if 'rpc' in data.data:
        server = data.data['rpc']['server']
        port = data.data['rpc']['port']

    server = input(_("RPC server: ") + f"[{server}] ") or server
    port = int(input(_("Proxy port: ") + f"[{port}] ") or port)

    data.data['rpc'] = {
        "server": server,
        "port": port
    }
Exemple #9
0
def get_yes_or_no( prompt_str ):
    """
    Asks the user for a yes or no response.
    Args:
        (str) prompt_str - the question

    Returns:
        (boolean) yes (true) or no (false)
    """
    is_yes_or_no = VerticalPrompt(
            [
              YesNo("{}".format(prompt_str)
                    )
              ],
              spacing = 1
            )

    try:
        yes_or_no = is_yes_or_no.launch()[0][1]

    except:
        print( "{}".format("Bad keystroke - try again"))
        yes_or_no = get_yes_or_no( prompt_str )

    return yes_or_no
def setup_experimental_flags(data):
    print()
    print_wrapped(
        _("EFMS has also provided some experimental features that you can use. "
          "They are not required to be enabled for EFMS to work."))

    widget = YesNo(prompt=_("Do you want to config experimental features? "),
                   prompt_prefix="[yN] ",
                   default="n")
    if not widget.launch():
        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)
        if cat == 'bool':
            prompt_prefix = '[Yn] ' if default else '[yN] '
            print()
            print(key)
            print_wrapped(desc)

            ans = YesNo(prompt=f"{key}? ",
                        prompt_prefix=prompt_prefix,
                        default='y' if default else 'n') \
                .launch()

            data.data['flags'][key] = ans
        elif cat == 'int':
            print()
            print(key)
            print_wrapped(desc)
            ans = Numbers(prompt=f"{key} [{default}]? ", type=int) \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'choices':
            print()
            print(key)
            print_wrapped(desc)
            ans = Bullet(prompt=f"{key}?", choices=params) \
                .launch(default=default)
            data.data['flags'][key] = ans

    print(_("Saving configurations..."), end="", flush=True)
    data.save()
    print(_("OK"))
def delete_application_versions(target_apps):
    num_apps = len(target_apps)
    keys = ['ApplicationName', 'VersionLabel']
    cli = YesNo(
        f"{num_apps} application versions will be deleted, would you like to proceed? "
    )
    result = cli.launch()
    if result:
        print("deleting apps...")
        for r in target_apps:
            p = [r.get(key) for key in keys]
            delete_app = eb.delete_application_version(ApplicationName=p[0],
                                                       VersionLabel=p[1],
                                                       DeleteSourceBundle=True)
            print(delete_app)
        print("Finished request")
    else:
        quit()
    return None
def setup_experimental_flags(data):
    print()
    widget = YesNo(prompt=_("Do you want to config experimental features? "),
                   prompt_prefix="[yN] ", default="n")
    if not widget.launch():
        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)
        if cat == 'bool':
            prompt_prefix = '[Yn] ' if default else '[yN] '
            print()
            print(key)
            print_wrapped(desc)

            ans = YesNo(prompt=f"{key}? ",
                        default='y' if default else 'n',
                        prompt_prefix=prompt_prefix) \
                .launch()

            data.data['flags'][key] = ans
        elif cat == 'int':
            print()
            print(key)
            print_wrapped(desc)
            ans = Numbers(prompt=f"{key} [{default}]? ", type=int) \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'choices':
            try:
                assert isinstance(params, list)
                default = params.index(default)
            except ValueError:
                default = 0
            print()
            print(key)
            print_wrapped(desc)
            ans = Bullet(prompt=f"{key}?", choices=params) \
                .launch(default=default)
            data.data['flags'][key] = ans
Exemple #13
0
def setup_proxy(data):
    if YesNo(prompt=_("Do you want to run ETM behind a proxy? "),
             prompt_prefix="[yN] ").launch(default='n'):
        if data.data.get('request_kwargs') is None:
            data.data['request_kwargs'] = {}
        proxy_type = Bullet(prompt=_("Select proxy type"),
                            choices=['http', 'socks5']).launch()
        host = input(_("Proxy host (domain/IP): "))
        port = input(_("Proxy port: "))
        username = None
        password = None
        if YesNo(prompt=_("Does it require authentication? "),
                 prompt_prefix="[yN] ").launch(default='n'):
            username = input(_("Username: "******"Password: "******"http://{host}:{port}/"
            if username is not None and password is not None:
                data.data['request_kwargs']['username'] = username
                data.data['request_kwargs']['password'] = password
        elif proxy_type == 'socks5':
            try:
                import socks
            except ModuleNotFoundError as e:
                print_wrapped(
                    _("You have not installed required extra package "
                      "to use SOCKS5 proxy, please install with the "
                      "following command:"))
                print()
                print("pip install 'python-telegram-bot[socks]'")
                print()
                raise e
            protocol = input(_("Protocol [socks5]: ")) or "socks5"
            data.data['request_kwargs'][
                'proxy_url'] = f"{protocol}://{host}:{port}"
            if username is not None and password is not None:
                data.data['request_kwargs']['urllib3_proxy_kwargs'] = {
                    "username": username,
                    "password": password
                }
        data.request = Request(**data.data['request_kwargs'])
Exemple #14
0
def update_domains(selected_domains, contact_details):
    # Show the domains and details and have the user confirm
    print("Your contact information will be updated to the following: ")
    print("\n")
    pprint(contact_details)
    print("\n")
    if not YesNo("Does the above look correct? (y/n) ").launch():
        print("Ok! Go ahead and try again.")
        return
    print("The domains to be updated are: ")
    for domain in selected_domains:
        print(domain)
    print("\n")
    if not YesNo("Does the above look correct? (y/n) ").launch():
        print("Ok! Go ahead and try again.")
        return
    for domain in selected_domains:
        result = r53domains.update_domain_contact(
            DomainName=domain,
            AdminContact=contact_details,
            RegistrantContact=contact_details,
            TechContact=contact_details)
Exemple #15
0
def gif_path_option(image_filepath):
    path = Path(image_filepath)
    default_choice = YesNo(
        # Prompt for the user to see
        prompt="Do you want to use the default folder {0} ? ".format(
            path.parent), )
    default = default_choice.launch()

    if default:
        return str(path.parent)
    else:
        while True:
            folder_choices = Input(
                # Prompt for the user to see
                prompt="What is the folder you want to use for the ASCII gif? ",
                strip=True)

            menu = folder_choices.launch()
            if os.path.exists(menu):
                return menu
            else:
                msg = f'Error: The folder \'{menu}\' doesnt seem to exists'
                print(color.error(msg))
Exemple #16
0
    def create_target_folder(self):
        target_folder = self.ctx["target_folder"]

        if target_folder.exists():
            should_continue = YesNo(
                prompt=
                f"{target_folder} already exist. Do you want to delete it ? "
            ).launch()

            if not should_continue:
                sys.exit(0)

            rmtree(target_folder)

        target_folder.mkdir()
Exemple #17
0
def setup_network_configurations(data):
    print()
    proceed = YesNo(prompt=_("Do you want to adjust network configurations? "
                             "(connection timeout and proxy) "),
                    prompt_prefix="[yN] ").launch(default='n')
    if not proceed:
        return

    print_wrapped(
        _("For meanings and significances of the following values, please "
          "consult the module documentations."))
    print()
    print("https://github.com/blueset/efb-telegram-master/")
    print()

    if YesNo(prompt=_("Do you want to change timeout settings? "),
             prompt_prefix="[yN] ").launch(default='n'):
        if data.data.get('request_kwargs') is None:
            data.data['request_kwargs'] = {}
        data.data['request_kwargs']['read_timeout'] = \
            Numbers(prompt=_("read_timeout (in seconds): ")).launch()
        data.data['request_kwargs']['connect_timeout'] = \
            Numbers(prompt=_("connect_timeout (in seconds): ")).launch()

    if YesNo(prompt=_("Do you want to run ETM behind a proxy? "),
             prompt_prefix="[yN] ").launch(default='n'):
        if data.data.get('request_kwargs') is None:
            data.data['request_kwargs'] = {}
        proxy_type = Bullet(prompt=_("Select proxy type"),
                            choices=['http', 'socks5']).launch()
        host = input(_("Proxy host (domain/IP): "))
        port = input(_("Proxy port: "))
        username = None
        password = None
        if YesNo(prompt=_("Does it require authentication?"),
                 prompt_prefix="[yN] ").launch(default='n'):
            username = input(_("Username: "******"Password: "******"http://{host}:{port}/"
            if username is not None and password is not None:
                data.data['request_kwargs']['username'] = username
                data.data['request_kwargs']['password'] = password
        elif proxy_type == 'socks5':
            try:
                import socks
            except ModuleNotFoundError as e:
                print_wrapped(
                    _("You have not installed required extra package "
                      "to use SOCKS5 proxy, please install with the "
                      "following command:"))
                print()
                print("pip install python-telegram-bot[socks]")
                print()
                raise e
            data.data['request_kwargs'][
                'proxy_url'] = f"socks5://{host}:{port}"
            if username is not None and password is not None:
                data.data['request_kwargs']['urllib3_proxy_kwargs'] = {
                    "username": username,
                    "password": password
                }
Exemple #18
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
Exemple #19
0
from bullet import YesNo

client = YesNo("Are you a good student? ", default='y')

res = client.launch()
print(res)
Exemple #20
0
from bullet import Bullet, SlidePrompt, Check, Input, YesNo, Numbers
from bullet import styles
from bullet import colors

cli = SlidePrompt(
    [
        YesNo("Are you a student? ",
            word_color = colors.foreground["yellow"]),
        YesNo("Are you a good student? ",
            default = 'y',
            word_color = colors.foreground["yellow"]),
        Input("Who are you? ",
            default = "Batman",
            word_color = colors.foreground["yellow"]),
        Input("Really? ",
            word_color = colors.foreground["yellow"]),
        Numbers("How old are you? ", 
            word_color = colors.foreground["yellow"], 
            type = int),
        Bullet("What is your favorite programming language? ",
            choices = ["C++", "Python", "Javascript", "Not here!"],
            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"]
        ),
        Check("What food do you like? ",
            choices = ["🍣   Sushi", 
 cp = Input(f"Enter a folder name ({channel}): ", default=channel)
 c_folder = cp.launch()
 details, plp = playlist_prompt(channels[channel])
 clear()
 title = plp.launch()
 while title in ["[Next Page]", "[Previous Page]"]:
     page = details.next_page if title == "[Next Page]" else details.prev_page
     details, plp = playlist_prompt(channels[channel], page)
     clear()
     title = plp.launch()
 playlist = [pl for pl in details.items if pl.title == title][0]
 fp = Input(f"Enter a folder name ({playlist.title}): ",
            default=playlist.title)
 f_folder = fp.launch()
 addp = YesNo(prompt="Add this playlist to be monitored? (y/N)",
              default="N",
              prompt_prefix="")
 should_monitor = addp.launch()
 if should_monitor:
     regp = Input(
         prompt="What should the regex be for the videos in this playlist?\n"
     )
     reg = regp.launch()
     cfg_path = os.path.join(yt_utils.BASE_SHARE, "channels.json")
     with open(cfg_path, "r") as inf:
         current_cfg = json.load(fp=inf)
     for i in range(len(current_cfg)):
         if current_cfg[i]["name"] != channel:
             continue
         current_cfg[i]["series_to_check"].append({
             "folder": f_folder,
Exemple #22
0
from bullet import Bullet, Check, YesNo, Input, SlidePrompt
from bullet import colors
import datetime
import csv
from tensorflow.keras.callbacks import TensorBoard
from cliparser import n_split, epochs, model_nom, pathData, optimizer, dropout1, dropout2, batch_size, learningrate, momentum, nesterov, beta1, beta2, amsgrad, tflite
import sklearn.metrics as metrics
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import itertools

# add prompt line for model noun to crush it if it's already existent or exit if not
if model_nom + '.h5' in os.listdir('Models/'):
    cli = SlidePrompt([
        YesNo("file already exist, do you want to overwrite it :",
              word_color=colors.foreground["yellow"])
    ])
    choice = cli.launch()
    if choice[0][1] == True:
        os.remove("Models/" + model_nom + ".h5")
    else:
        exit()

# create a folder of logs including models in orther to visualize them with tensorboard tool
tensorboard = TensorBoard(log_dir='logs/{}'.format(model_nom))

# create path data
PATH = os.path.join(pathData)

# define training and validation paths
train_dir = os.path.join(PATH, 'train')
Exemple #23
0
from bullet import Bullet, SlidePrompt, Check, Input, YesNo, Numbers
from bullet import styles
from bullet import colors

cli = SlidePrompt(
    [
        YesNo("Are you a student? ", 
            word_color = colors.foreground["yellow"]),
        Input("Who are you? ",
            default = "Batman",
            word_color = colors.foreground["yellow"]),
        Input("Really? ",
            word_color = colors.foreground["yellow"]),
        Numbers("How old are you? ", 
            word_color = colors.foreground["yellow"], 
            type = int),
        Bullet("What is your favorite programming language? ",
            choices = ["C++", "Python", "Javascript", "Not here!"],
            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"]
        ),
        Check("What food do you like? ",
            choices = ["🍣   Sushi", 
                       "🍜   Ramen",
                       "🌭   Hotdogs", 
                       "🍔   Hamburgers", 
Exemple #24
0
 def take_action(self, parsed_args):
     self.LOG.debug('[*] creating secrets')
     # Does an environment already exist?
     if not stdin.isatty():
         raise RuntimeError(
             '[-] this command only works when a TTY is available')
     se = self.app.secrets
     env = se.environment
     if not se.environment_exists():
         if parsed_args.update:
             raise RuntimeError(f"[!] environment '{env}' does not exist'")
         client = YesNo(f"create environment '{env}'? ", default='n')
         res = client.launch()
         if not res:
             self.LOG.info('[!] cancelled creating environment')
             return 1
         se.environment_create()
         self.LOG.info(f"[+] environment '{env}' "
                       f"({se.environment_path()}) created")
     if parsed_args.update and len(parsed_args.arg) > 1:
         # TODO(dittrich): Refactor to loop over parsed_arg.arg
         # from here (not farther down).
         raise RuntimeError(
             "[!] only one variable can be updated at a time")
     se.read_secrets_and_descriptions()
     groups = se.get_groups()
     group = parsed_args.group
     if group is None:
         if not parsed_args.update:
             # Default group to same name as environment identifier
             group = env
         else:
             group = se.get_group(parsed_args.arg[0])
     if group not in groups:
         if parsed_args.update:
             raise RuntimeError(f"[!] group '{group}' does not exist'")
         client = YesNo(f"create new group '{group}'? ", default='n')
         res = client.launch()
         if not res:
             self.LOG.info('[!] cancelled creating group')
             return 1
         descriptions = list()
         variables = list()
     else:
         descriptions = se.read_descriptions(group=group)
         variables = [item['Variable'] for item in descriptions]
     args = parsed_args.arg
     changed = False
     for arg in args:
         arg_row = find(descriptions, 'Variable', arg)
         if parsed_args.update:
             if arg not in variables:
                 self.LOG.info(
                     f"[-] can't update nonexistent variable '{arg}'")
                 continue
             self.LOG.info(
                 f"[+] updating variable '{arg}' in group '{group}'")
             new_description = get_description(
                 name=arg, defaults=descriptions[arg_row])
         else:
             if arg in variables:
                 self.LOG.info(f"[-] variable '{arg}' already exists")
                 continue
             self.LOG.info(
                 f"[+] creating variable '{arg}' in group '{group}'")
             new_description = get_description(name=arg,
                                               defaults={
                                                   'Variable': arg,
                                                   'Prompt':
                                                   f"Value for '{arg}'",
                                                   'Options': "*",
                                                   'Export': " ",
                                               })
         if len(new_description):
             table = PrettyTable()
             table.field_names = ('Key', 'Value')
             table.align = 'l'
             for k, v in new_description.items():
                 table.add_row((k, v))
             print(table)
             client = YesNo("commit this description? ", default='n')
             res = client.launch()
             if not res:
                 continue
             if arg_row is not None:
                 descriptions[arg_row] = new_description
             else:
                 descriptions.append(new_description)
                 se.set_secret(arg)
             changed = True
     if changed:
         se.write_descriptions(
             data=descriptions,
             group=group,
             mirror_to=os.getcwd() if parsed_args.mirror_locally else None)
Exemple #25
0
def yes_no(prompt, default_yes=False):
    cli = SlidePrompt([YesNo(prompt, default="y" if default_yes else "n")])
    result = cli.launch()
    for p, ans in result:
        if prompt in p:
            return ans
Exemple #26
0
from bullet import Bullet, Prompt, Check, Input, YesNo, Numbers
from bullet import styles
from bullet import colors

cli = Prompt(
    [
        YesNo("Are you a student? "),
        Input("Who are you? "),
        Numbers("How old are you? "),
        Bullet("What is your favorite programming language? ",
              choices = ["C++", "Python", "Javascript", "Not here!"]),
    ],
    spacing = 1,
    separator = "-",
    separator_color = colors.foreground["cyan"]
)

result = cli.launch()
cli.summarize()
Exemple #27
0
TITLE_LAYOUT = 0
BLANK = 10
FONT = "Calibri"
FILE_LOC = ""
SERMON_SERIES = "Signs of Life Series in John’s Gospel"

cli = VerticalPrompt(
    [
        Input("What is the reference for Call to Worship?"),
        Input("Filename?"),
        Input("What is the reference for Confession of Sin?"),
        Input("Filename?"),
        Input("What is the reference for Assurance of Worship?"),
        Input("Filename?"),
        YesNo("Is it prayers of the people? "),
        Input("Sermon title?"),
        Input("Sermon reference?"),
        #Bullet("What is your favorite programming language? ",
        #     choices = ["C++", "Python", "Javascript", "Not here!"]),
    ],
    spacing=1)

result = cli.launch()


class LiturgyElem:
    def __init__(self, f_name):
        self.title = ""
        self.lyrics = []
        self.f_name = f_name
Exemple #28
0
                 choices=list(downloadable_models.keys()),
                 **ocean_style_dolphin)
    model2download = cli.launch()

    alt_model_name_cli = Input(
        prompt="\n There's already a \'{}\' in your disk.\
        \n Please, type a different name: \n\n ".format(model2download),
        strip=True,
        indent=alignment['indent'])

    if model2download in available_models:
        alt_model_name = alt_model_name_cli.launch()
    else:
        cli = YesNo(
            prompt="\n The model to download is going to be named \'{}\'. \
                \n Do you want to change this name? [y/n] ".format(
                model2download),
            prompt_prefix="",
            indent=alignment['indent'])
        if cli.launch():
            alt_model_name_cli = Input(prompt="\n Type a new name: \n ",
                                       strip=True,
                                       indent=alignment['indent'])
            alt_model_name = alt_model_name_cli.launch()

else:
    model2resume = model

print(' Loading model...')
training_dir, _, base_pipeline_config_path = load_model_paths(
    model2resume, model2download, alt_model_name)