def main() : # f = Figlet(font='small',) # print(f.renderText('Are you ready for your exams ?')) questions = [ { 'type': 'list', 'name': 'mode', 'message': 'What do you want to do?', 'choices': [ Separator(), 'Show', 'Calendar', Separator(), 'Add', 'Remove', 'Edit' ] }, ] answers = prompt(questions, style=custom_style_2) mode_run(answers['mode']) return answers
def actions(): options = [{ 'type': 'list', 'message': 'Select action', 'name': 'action', 'choices': [ Separator('=== Line Items ==='), { 'name': 'Create Line Items', 'value': CREATE_LINE_ITEMS }, Separator('=== Users ==='), { 'name': 'Create Users', 'value': CREATE_USERS }, { 'name': 'Aggregate Real Users', 'value': AGGREGATE_REAL_USERS }, { 'name': 'Check User Slugs', 'value': CHECK_USER_SLUGS }, { 'name': 'Check Duplicated Usernames', 'value': CHECK_DUPLICATED_USERNAMES }, ], }] return prompt(options, style=style).get('action')
def _interact(): question = [{ 'type': 'list', 'name': 'action', 'message': 'Include or Exclude?', 'default': 'Exclude', 'choices': [ 'Exclude', 'Include', Separator(), 'Export', Separator(), 'Stop' ], 'filter': lambda val: val.lower() }] action = prompt(question).get("action", "stop") if action == "stop" and ask_stop: question = [{ 'type': 'confirm', 'message': "Are you sure you want to stop?", 'name': 'stop', 'default': 'false', }] stopping = prompt(question).get("stop", True) if stopping: return None else: return _interact() elif action == "export": self._export() return _interact() return action
def timetable_overview_menu_generator(timeable_overview, page_size) -> Dict: title_temp = [] fss_temp = [] choice_list = [] for group, title, fs in timeable_overview: if not fs in fss_temp: choice_list.append(Separator(fs)) fss_temp.append(fs) if not title in title_temp: choice_list.append(Separator(title)) title_temp.append(title) choice_list.append({ "name": group.replace("&semester=", " ") }) return [ { 'type': 'checkbox', 'qmark': 'x', 'message': 'Auswahl Stundenplan', 'name': 'timetable_selection', 'choices': choice_list, 'validate': lambda answer: 'You must choose at least one time table.' if len(answer) == 0 else True, 'pageSize': page_size, } ]
def action_choices(answers): choices = ['Nenhuma opção encontrada ):'] if answers['action'] == 'Realizar Busca de Tweets': choices = [ Separator('= Algoritmos ='), 'Buscar por termo', 'Buscar por hashtag' ] return choices elif answers['action'] == 'Buscar Usuário': choices = [ # Separator('= Isso irá abrir seu navegador ='), # 'Link: ...' Separator('= EM BREVE =') ] return choices elif answers['action'] == 'Dicas para Gráficos e Análises': message = '' choices = [ Separator('= Links e tutoriais que podem ajudar ='), 'Link1: ...', 'Link2: ...' ] return choices elif answers['action'] == 'Sair': print('Obrigada por utilizar o Scraper, até logo!') raise SystemExit return choices
def question_items_list(item_list, key): choices = [Separator('')] itemq = { 'name': 'Go back', 'value': 'back' } choices.append(itemq) choices.append(Separator()) for item in item_list: itemq = { 'name': '{}'.format(item[key]), 'value': '{}'.format(item['_id']) } choices.append(itemq) choices.append(Separator()) question = { 'type': 'list', 'name': 'list', 'qmark': '😃', 'message': '{} by name'.format(key), 'choices': choices } return question
def exam_mode(): """ run the exam mode""" # Welcome Text("exams_db.sqlite") text = "Are you ready for your exams ?" cprint(figlet_format(text, font="small"), "green", attrs=['bold']) # Exam Show - then as for next mode func_run("Show", Exam) questions = [ { 'type': 'list', 'name': 'mode', 'message': 'What do you want to do?', 'choices': [ Separator(), 'Show', 'Calendar', 'Record Study Time', Separator(), 'Add', 'Remove', 'Edit', Separator(), 'Exit' ] }, ] while True: answers = prompt(questions, style=custom_style_2) if answers['mode'] == 'Exit': break # Run func func_run(answers['mode'], Exam) print("Done exam operations.")
def ask_for_components(services: dict, topics: dict, actions: dict): services_choices = component_options(services) topics_choices = component_options(topics) actions_choices = component_options(actions) all_choices = services_choices + topics_choices + actions_choices there_are_valid_choices = any("disabled" not in choice for choice in all_choices) if not there_are_valid_choices: logging.error( "There are no available components to fuzz!\n" "Check for TODOs in the fuzz.yaml file." ) exit(-1) choices = [ Separator("Topics"), *topics_choices, Separator("Services"), *services_choices, Separator("Actions"), *actions_choices, ] questions = [ { "type": "checkbox", "message": "What do you want to fuzz?", "name": "to_fuzz_components", "choices": choices, } ] return prompt(questions)["to_fuzz_components"]
def select(sg1: common.stargate): running = True while running: common.header(sg1, '3 star verification') print('star 1: ' + str(sg1.mytarget.get_star1()) + ' -> ', end='') common.print_status(sg1.mytarget.star1_ok) print('star 2: ' + str(sg1.mytarget.get_star2()) + ' -> ', end='') common.print_status(sg1.mytarget.star2_ok) print('star 3: ' + str(sg1.mytarget.get_star3()) + ' -> ', end='') common.print_status(sg1.mytarget.star3_ok) print('') questions = [{ 'type': 'checkbox', 'qmark': '?', 'message': 'please select 3 stars', 'name': 'tasks', 'choices': [ Separator('= star ='), { 'name': sg1.mytarget.get_star1(), }, { 'name': sg1.mytarget.get_star2(), }, { 'name': sg1.mytarget.get_star3(), }, Separator('= Options ='), { 'name': 'debug mode', }, { 'name': 'exit' } ] }] answers = prompt(questions, style=custom_style_2) pprint(answers) print(len(answers["tasks"])) if (len(answers["tasks"]) > 1) and not 'exit' in answers["tasks"]: print('### Please choose 3 stars ###') elif (len(answers["tasks"]) < 1) and not 'exit' in answers["tasks"]: print('### Please choose 3 stars ###') elif not 'exit' in answers["tasks"]: print(answers.values()) A = answers["tasks"][0] print(str(A)) sg1.mytarget.target = (answers["tasks"][0]) time.sleep(1) running = False observe.main(sg1, answers["tasks"][0]) else: running = False
def choose_devices(devices, query=False): """ Create list of menu choices from devices with category separators Optional param query: query and display device version numbers """ # Style for selection interface style = style_from_dict({ Token.Separator: '#FF00AA', Token.QuestionMark: '#00AAFF bold', Token.Selected: '#00AAFF', # default Token.Pointer: '#00FF00 bold', Token.Instruction: '#FFAA00', # default Token.Answer: '#00AAFF bold', Token.Question: '#FF00AA', }) choice_list = [] current_type = None name_len = max([len(dev.f_name) for dev in devices]) + 1 if query: print('Querying all devices for version numbers. ' 'This may take a minute...') choice_list.append( Separator('Name'.center(name_len) + 'Firmware'.center(15) + 'Core'.center(7) + 'State')) for device in devices: if device.type != current_type: current_type = device.type sep_str = ' {} '.format(current_type).center(name_len + 29, '=') choice_list.append(Separator(sep_str)) menu_text = device.f_name.ljust(name_len) if query and device.software == 'tasmota': device.query_tas_status() if 'tas_version' in device.reported: menu_text += device.reported['tas_version'].ljust(15) menu_text += device.reported['core_version'].ljust(7) if device.reported['power'] is not None: menu_text += device.reported['power'] else: menu_text += 'Offline' choice_list.append({'name': menu_text, 'value': device.f_name}) # Ask the user to choose which devices to flash questions = [{ 'type': 'checkbox', 'message': 'Select Devices', 'name': 'device_selection', 'choices': choice_list, }] answers = prompt(questions, style=style) selected_devices = [device for device in devices if device.f_name \ in answers['device_selection']] return selected_devices
def select_pokemon(api_handler: APIHandler) -> str: """ Displays the input field for the user to select and view a pokemon list or search for a pokemon Parameters: api_handler: APIHandler The APIHandler object used to make api calls Returns: String of the users input from the PyInquirer prompts """ print( "\nIf you are unsure of what Pokémon you would like to search for, select a Pokémon generation to view the list of Pokémon " "from that generation.\n\nOnce you know what Pokémon you would like to search for, select the Search option and enter the " "Pokémon's name or Pokédex number. If the Pokémon you are searching for has different forms, enter the Pokémon's name " "followed by -<form> where <form> is the Pokémon's form you are interested in, some generation lists will show examples.\n" ) select_pokemon_options: list = [{ "type": "list", "name": "select_pokemon_option", "message": "What would you like to do?", "choices": [ Separator("-= View Pokémon list for: =-"), "Generation 1", "Generation 2", "Generation 3", "Generation 4", "Generation 5", "Generation 6", "Generation 7", "Generation 8", Separator("-= Search for a Pokémon =-"), "Search" ] }] selection: str = prompt( select_pokemon_options)["select_pokemon_option"] if selection == "Search": search_pokemon: list = [{ "type": "input", "name": "search_pokemon", "message": "What is the name or Pokédex # you would like to search for?", "validate": lambda val: api_handler.get_pokemon(val.lower().strip(" ")). status_code != 404 or # noqa: W504 "Pokémon not found, please check you have input the correct name/number" }] return prompt(search_pokemon)["search_pokemon"].lower().strip(" ") else: return selection
def GetRowEntry(self, ident, questions): ret = [{},questions] ret[1][0]["choices"] = [Separator("Time(s) (% of execution time)")] alwaysDisplay = [Separator(), "Back/Previous", "Exit"] assert ident in self._data for x in self._data[ident]: ret[0][x.GenerateRow()] = x.GetLinkID() ret[1][0]["choices"].append(x.GenerateRow()) ret[1][0]["choices"] += alwaysDisplay for x in ret[1][0]["choices"]: self._debugFile.write(str(x) +"\n") return ret
def test_get_questions_not_selected(): src = 'test_data/ssg-fedora-ds-arf.xml' regex = r'_package_\w+_removed' client = get_client_with_option_show_not_selected_rules(src, regex) from PyInquirer import Separator out = client.get_questions(Separator('= The rules ID ='), Separator('= The not selected rules ID =')) rule1 = 'xccdf_org.ssgproject.content_rule_package_setroubleshoot_removed' rule2 = 'xccdf_org.ssgproject.content_rule_package_mcstrans_removed' assert out[0]['choices'][-2]['name'] == rule1 assert out[0]['choices'][-1]['name'] == rule2
def test_get_questions(): src = 'test_data/ssg-fedora-ds-arf.xml' regex = r'_package_\w+_removed' client = get_client(src, regex) from PyInquirer import Separator out = client.get_questions(Separator('= The rules ID ='), Separator('= The not selected rules ID =')) rule1 = 'xccdf_org.ssgproject.content_rule_package_abrt_removed' rule2 = 'xccdf_org.ssgproject.content_rule_package_sendmail_removed' assert out[0]['choices'][1]['name'] == rule1 assert out[0]['choices'][2]['name'] == rule2
def test_get_questions_with_option_show_fail_rules(): src = 'test_data/ssg-fedora-ds-arf.xml' regex = r'_package_\w+_removed' client = get_client_with_option_show_fail_rules(src, regex) from PyInquirer import Separator out = client.get_questions(Separator('= The rules ID ='), Separator('= The not selected rules ID =')) rule1 = 'xccdf_org.ssgproject.content_rule_package_abrt_removed' assert out[0]['choices'][1]['name'] == rule1 with pytest.raises(Exception, match="list index out of range"): assert out[0]['choices'][2]['name'] is None
def __init__(self): self.questions = [ { 'number': 0, 'type': 'list', 'name': 'menu principal', 'message': 'Que souhaitez-vous faire?', 'choices': [ 'Recherche efficace (I\'m lucky)', Separator(), 'Recherche efficace par frequence', Separator(), 'Recherche à mots succesifs exacts', Separator(), 'Recherche à mots partiels', Separator(), 'Créer mon propre index', Separator(), 'Informations sur le moteur de recherche', Separator(), "Quitter" ] }, { 'number': 1, 'type': 'list', 'name': 'Menu', 'message': 'Bienvenue dans BZ-Search !!!', 'choices': [ 'Faire une recherche', Separator(), 'Quitter', ] }, { 'number': 2, 'type': 'list', 'name': 'continue', 'message': 'Sur quel critère souhaitez-vous effectuer votre recherche?', 'choices': [ 'Continuer à lire', Separator(), 'Retour', Separator(), 'Revenir au menu', Separator(), 'Quitter', ] }, ]
def editprompt(gh, repo): existing_projects = [ dict(name=proj.name, value=proj) for proj in repo.get_projects(state="all") ] select_project = { "type": "list", "name": "project", "message": "Which project?", "choices": existing_projects + [ Separator(), "New Project", ], } project = prompt(select_project)["project"] if project == "New Project": console.print("Creating a new Project") question = { "type": "input", "name": "version", "message": "What release version", } version = prompt(question)["version"] project = newproject(gh, repo, version) question = { "type": "list", "name": "action", "message": "What would you like to do", "choices": [ { "name": "Sync new pull requests", "value": lambda: syncprs(gh, repo, project), }, { "name": "Triage existing PRs", "value": lambda: triage_proj(gh, repo, project), }, Separator(), { "name": "Done", "value": lambda: None, }, ], } action = prompt(question)["action"] return action()
def prompt_checkbox(choices="", style="", message="", name="", validator=""): choices = ([ Separator("= The Meats ="), { "name": "Ham" }, { "name": "Ground Meat" }, Separator("= The Cheeses ="), { "name": "Mozzarella", "checked": True }, Separator("= The usual ="), { "name": "Mushroom" }, Separator("= The extras ="), { "name": "Olives", "disabled": "out of stock" }, ] if not choices else choices) style = ( style_from_dict({ Token.Separator: "#cc5454", Token.QuestionMark: "#673ab7 bold", Token.Selected: "#cc5454", # default Token.Pointer: "#673ab7 bold", Token.Instruction: "", # default Token.Answer: "#f44336 bold", Token.Question: "", }) if not style else style) message = "message" if not message else message name = "repos" if not name else name validator = ((lambda answer: "You must choose at least one." if len(answer) == 0 else True) if not validator else validator) questions = [{ "type": "checkbox", "message": message, "name": name, "choices": choices, "validate": validator, }] answers = prompt(questions, style=style) return answers
def menu(self): # Get a list of all existing separators separators = self.CONFIG["separators"] separators_menu = [ { 'type': 'checkbox', 'qmark': '⚙️ ', 'message': 'Select separators', 'name': 'separators', 'choices': [] } ] for separator, value in separators.items(): separators_menu[0]["choices"].append(Separator("{} - Exemple : john{}doe".format(separator, value))) separators_menu[0]["choices"].append({"name": value}) self.separators = prompt(separators_menu)["separators"] modules_list = sorted([module for module in self.CONFIG["plateform"]]) categories = sorted(list(set([content["type"] for module, content in self.CONFIG["plateform"].items()]))) services_menu = [ { 'type': 'checkbox', 'qmark': '⚙️ ', 'message': 'Select services', 'name': 'modules', 'choices': [ ], 'validate': lambda answer: 'You must choose at least one service !' \ if len(answer) == 0 else True } ] for category in categories: # Category title services_menu[0]["choices"].append(Separator(category.upper())) # Append category items for module in modules_list: if self.CONFIG["plateform"][module]["type"] == category: services_menu[0]["choices"].append( { 'name': module, # Checked by default 'checked': module in self.CONFIG["report_elements"] }) modules = prompt(services_menu)["modules"] self.modules_update(modules)
def select_entities(people, places, organizations): choices = [] choices.append(Separator('- People -')) for person in people: choices.append({'name': person}) choices.append(Separator('- Places -')) for place in places: choices.append({'name': place}) choices.append(Separator('- Organizations -')) for org in organizations: choices.append({'name': org}) questions = [{'type': 'checkbox', 'qmark': '😃', 'message': 'Select entitites to process', 'name': 'entities', 'choices': choices}] return prompt(questions)
def prompt_toggles(self, layer_ordered): if not self.load_config(): for layer in self.registered_layers.keys(): self.stack_toggle_status[layer] = False layer_list = [{ 'name': layer, 'checked': self.stack_toggle_status[layer] } for layer in layer_ordered] mode_list = [{ 'name': mode, 'checked': self.stack_mode_status[mode] } for mode in self.registered_modes.keys()] questions = [{ 'type': 'checkbox', 'qmark': '⦾', 'message': 'Configuration', 'name': 'enabled', '' 'choices': [Separator('\n--LAYERS--')] + layer_list + [Separator('\n--MODES--')] + mode_list, }] answers = prompt(questions) enabled_options = answers['enabled'].copy() for option in enabled_options: if option in self.registered_modes.keys(): self.stack_mode_status[option] = True enabled_options.remove(option) for layer in layer_ordered: self.stack_toggle_status[layer] = False for layer in enabled_options: self.stack_toggle_status[layer] = True self.update_stack_status(layer, symbol='◌', status='Pending') self.logger.debug(f'Toggles: {self.stack_toggle_status}') self.logger.debug(f'Modes: {self.stack_mode_status}') self.update_config_file() return answers
def prompt_list(choices="", style="", message="", name="", default=""): choices = ([ Separator("= The Meats ="), { "name": "Ham" }, { "name": "Ground Meat" }, Separator("= The Cheeses ="), { "name": "Mozzarella", "checked": True }, Separator("= The usual ="), { "name": "Mushroom" }, Separator("= The extras ="), { "name": "Olives", "disabled": "out of stock" }, ] if not choices else choices) style = ( style_from_dict({ Token.Separator: "#cc5454", Token.QuestionMark: "#673ab7 bold", Token.Selected: "#cc5454", # default Token.Pointer: "#673ab7 bold", Token.Instruction: "", # default Token.Answer: "#f44336 bold", Token.Question: "", }) if not style else style) message = "message" if not message else message name = "environment" if not name else name questions = [{ "type": "list", "message": message, "name": name, "choices": choices, }] answers = prompt(questions, style=style) return answers
def pyir_execute(): questions = [ { 'type': 'list', 'name': 'content_type', 'message': 'MAIN PAGE >> ', 'choices': [ 'create', 'search', { 'name': 'update', 'disabled': 'Unavailable yet' }, { 'name': 'delete', 'disabled': 'Unavailable yet' }, Separator("\n * * * * * * * * * \n"), 'excel-processing', Separator("\n * * * * * * * * * \n"), 'exit' ], 'filter': lambda val: val.lower() }, { 'type': 'list', 'name': 'resource_type', 'message': 'Select FHIR-Resource Type', 'choices': list(EXCEL_SHEETNAME.keys()), 'when': lambda answers: getContentType(answers, "create") or getContentType(answers, "search"), }, { 'type': 'list', 'name': 'resource_type', 'message': 'Select FHIR-Resource Type', 'choices': list(EXCEL_SHEETNAME.values()), 'when': lambda answers: getContentType(answers, "excel-processing"), }, { 'type': 'confirm', 'name': 'exit_confirm', 'message': 'Do you want to exit from ETRI PYIR Client?', 'when': lambda answers: getContentType(answers, "exit") }, ] answers = prompt(questions, style=style) return answers
def hostselector(ctx, message): if len(config.items("HOSTS")) == 0: log( ("No hosts have been added yet." "To add a host, select 'Add/Update Host > Add Host' command."), "red", ) return [] host_choices = [ Separator("== Honeypots =="), ] for host in list(config["HOSTS"]): host_choices.append({"name": host}) try: return prompt( [{ "type": "checkbox", "name": "hosts", "message": message, "choices": host_choices, }], style=style(), )["hosts"] except EOFError: log("Action cancelled by user", "red") return []
def inquire_course(course_name, label_results, course_results, course_model_results, conn, man_label_fp): question_labelled = label_results.get("questions", {}) answer_labelled = label_results.get("answers", {}) print("Labelled {}/{} questions. ({} useful)".format( len(question_labelled), len(course_results["question_results"]), len([ val for val in label_results.get("questions", {}).values() if int(val) >= 0 ]))) print("Labelled {}/{} answers.".format( len(answer_labelled), len(course_results["answer_results"]))) inquiry_choices = ["questions", "answers", Separator(), "back"] inquiry_questions = [{ "type": "list", "name": "q_or_a", "message": "Label questions or answers?", "choices": inquiry_choices }] answers = prompt(inquiry_questions) q_or_a = answers.get("q_or_a", None) if not q_or_a: exit() elif q_or_a == "questions": inquire_questions(course_name, label_results, course_results, course_model_results, conn, man_label_fp) elif q_or_a == "answers": # inquire_answers() pass
def askPasswordInformation(): questions = [ { 'type': 'input', 'name': 'password length', 'message': 'How many digit password do you want to generate?:', 'validate': PasswordLengthValidator }, { 'type': 'checkbox', 'qmark': '\U0001F600', 'message': 'Select options ', 'name': 'password options', 'choices': [ Separator('=== Menu ==='), { 'name': 'Numbers' }, { 'name': 'Lowercase Alphabets' }, { 'name': 'Uppercase Alphabets' }, { 'name': 'Special characters' } ] # checkbox doesn't have a Validator implementation yet } ] answers = prompt(questions, style=style) return answers
def category_choice(self): """ choose a category using PyInquirer list prompt - get all categories in database - put them into the list - prompt the user and catch the exception :return: the category id or 0 if error (no 0 category in database) """ # get all categories category = Category() list_cat = category.list_categories() list_choices = [] # building the display list for cat in list_cat: choice = "%02d - %s" % (cat[0], cat[1]) list_choices.append(choice) list_choices.append(Separator()) list_choices.append("00 - retour") question = [ { 'type': 'list', 'name': 'menu2', 'message': "Choisissez la catégorie du produit", 'choices': list_choices, 'carousel': True }, ] # prompt and return id or catch the error and return 0 try: response = prompt(question, style=custom_style_1) ind = response['menu2'].split() rc = int(ind[0]) except KeyError: rc = 0 return rc
def choose_branch_name(jira): issues = jira.search_issues( 'project = CATV AND statusCategory = 2 AND assignee in (currentUser()) ORDER BY priority DESC, updated DESC' ) choises = list( map(lambda issue: '%s - %s' % (issue.key, issue.fields.summary), issues)) choises.extend([Separator(), 'Add custom branch']) questions = [{ 'type': 'list', 'name': 'task', 'message': 'Choose a task for branch source', 'choices': choises }, { 'type': 'list', 'name': 'branch_type', 'message': 'Branch type', 'choices': ['Feature', 'Bugfix', 'Hotfix', 'Release'], 'when': lambda x: x['task'] != 'Add custom branch' }, { 'type': 'input', 'name': 'branch_name', 'message': 'Enter a branch name', 'when': lambda x: x['task'] == 'Add custom branch' }] answers = prompt(questions) if 'branch_name' in answers.keys(): return answers['branch_name'] else: return '%s/%s' % (answers['branch_type'].lower(), answers['task'].split(' ', 1)[0])
def get_dev_mode(): dev_mode_q = { 'type': 'checkbox', 'name': 'dev_mode', 'message': 'Which functions would you like to run?', 'choices': [{ 'name': '*Default', 'checked': True }, Separator('= Developer Mode ='), { 'name': "Hedless mode - don't show browser page" }, { 'name': "Detached mode - don't close browser page when interrupted" }] } answer = prompt(dev_mode_q, style=custom_style_2) # assign value Constants.DEVELOPER_MODE = 0 if sum([box.startswith(('H', 'D')) for box in answer['dev_mode']]) == 2: Constants.DEVELOPER_MODE = 2 elif any(box.startswith('H') for box in answer['dev_mode']): Constants.DEVELOPER_MODE = 3 elif any(box.startswith('D') for box in answer['dev_mode']): Constants.DEVELOPER_MODE = 1 print(answer['dev_mode']) print(Constants.DEVELOPER_MODE)
def main_menu(): style = style_from_dict({ Token.Separator: '#cc5454', Token.QuestionMark: '#673ab7 bold', Token.Selected: '#cc5454', # default Token.Pointer: '#673ab7 bold', Token.Instruction: '', # default Token.Answer: '#f44336 bold', }) option1 = 'Enter a Book Name' option2 = 'Upload a file with Book Names' questions = [ { 'type': 'list', 'message': '', 'name': 'option', 'choices': [ Separator('How do you want to add your book/s to Goodread?'), { 'name': option1 }, { 'name': option2 }, ], 'validate': lambda answer: 'You must choose at least one.' \ if len(answer) == 0 else True } ] answers = prompt(questions, style=style) return answers['option']