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
def prompt_pipeline_release_branch(wf_releases, wf_branches): """Prompt for pipeline release / branch Args: wf_releases (array): Array of repo releases as returned by the GitHub API wf_branches (array): Array of repo branches, as returned by the GitHub API Returns: choice (str): Selected release / branch name """ # Prompt user for release tag choices = [] # Releases if len(wf_releases) > 0: for tag in map(lambda release: release.get("tag_name"), wf_releases): tag_display = [("fg:ansiblue", f"{tag} "), ("class:choice-default", "[release]")] choices.append(questionary.Choice(title=tag_display, value=tag)) # Branches for branch in wf_branches.keys(): branch_display = [("fg:ansiyellow", f"{branch} "), ("class:choice-default", "[branch]")] choices.append(questionary.Choice(title=branch_display, value=branch)) if len(choices) == 0: return False return questionary.select("Select release / branch:", choices=choices, style=nfcore_question_style).unsafe_ask()
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)
def interact(self, courses): choices = [ questionary.Choice('All courses', 'all'), questionary.Choice('Filter by term', 'term'), questionary.Choice('Select individual courses', 'per') ] current_id = ['all', 'term', 'per'].index(self.filter_name) self.filter_name = questionary.select( 'Select course filter mode', choices, default=choices[current_id]).unsafe_ask() self.get_filter().interact(courses)
def ask(self): self.answer = questionary.select( "Instance type", choices=[ questionary.Choice(title="m5a.4xlarge | 16 CPU, 64Gb", value="m5a.4xlarge"), questionary.Choice(title="r5a.2xlarge | 8 CPU, 64Gb", value="r5a.2xlarge"), questionary.Choice(title="r5a.4xlarge | 16 CPU, 128Gb", value="r5a.4xlarge"), ], style=custom_style).ask() return self.answer
def prompt_module_version_sha(module, modules_repo, installed_sha=None): older_commits_choice = questionary.Choice(title=[ ("fg:ansiyellow", "older commits"), ("class:choice-default", "") ], value="") git_sha = "" page_nbr = 1 try: next_page_commits = get_module_git_log(module, modules_repo=modules_repo, per_page=10, page_nbr=page_nbr) except UserWarning: next_page_commits = None except LookupError as e: log.warning(e) next_page_commits = None while git_sha == "": commits = next_page_commits try: next_page_commits = get_module_git_log(module, modules_repo=modules_repo, per_page=10, page_nbr=page_nbr + 1) except UserWarning: next_page_commits = None except LookupError as e: log.warning(e) next_page_commits = None choices = [] for title, sha in map( lambda commit: (commit["trunc_message"], commit["git_sha"]), commits): display_color = "fg:ansiblue" if sha != installed_sha else "fg:ansired" message = f"{title} {sha}" if installed_sha == sha: message += " (installed version)" commit_display = [(display_color, message), ("class:choice-default", "")] choices.append(questionary.Choice(title=commit_display, value=sha)) if next_page_commits is not None: choices += [older_commits_choice] git_sha = questionary.select( f"Select '{module}' commit:", choices=choices, style=nf_core.utils.nfcore_question_style).unsafe_ask() page_nbr += 1 return git_sha
def ask(self): self.answer = questionary.select( "Tableau Server Authentication Type?", choices=[ questionary.Choice(title="Local"), questionary.Choice( title="LDAP", disabled="Only Local Auth is currently supported"), questionary.Choice( title="ActiveDirectory", disabled="Only Local Auth is currently supported") ], style=custom_style).ask() return self.answer
def select_configuration_questionaire(type_, system_folders): """Ask which configuration the user wants to use It shows only configurations that are in the default folder. """ context = NodeContext if type_ == "node" else ServerContext configs, f = context.available_configurations(system_folders) # each collection (file) can contain multiple configs. (e.g. test, # dev) choices = [] for config_collection in configs: envs = config_collection.available_environments for env in envs: choices.append( q.Choice(title=f"{config_collection.name:25} {env}", value=(config_collection.name, env))) if not choices: raise Exception("No configurations could be found!") # pop the question name, env = q.select("Select the configuration you want to use:", choices=choices).ask() return name, env
def resume_prompt(): '''Get the resume project_id. Users can select from exist progress files or input the project_id manually. Returns: pid - id of the selected project ''' # read resume files choices = [] for f in PCACHE_DIR.glob('*'): with open(f) as fh: pcache_dict = json.load(fh) if pcache_dict['status'] != 'running': continue pid = pcache_dict['pid'] name = pcache_dict['name'] n_trial = pcache_dict['n_trial'] progress = pcache_dict['progress'] create_time = pcache_dict['create_time'] choices.append( questionary.Choice( title= f'[Project {pid}: {name}] progress: {progress}/{n_trial} (created at {create_time})', value=int(pid))) if len(choices) == 0: print("There are no running projects!") sys.exit(1) return questionary.select("Which project would you like to resume?", choices=choices).ask()
def select_dashboard(self, force=False) -> str: """ Select from a list of discovered dashboards """ selection = list() dashboard_id = None for dashboard in self.dashboards.values(): if dashboard.health: health = 'healthy' else: health = 'unhealthy' selection.append( questionary.Choice( title= f'{dashboard.name} ({dashboard.arn}, {health}, {dashboard.status})', value=dashboard.id, # Disable if broken or no update available and not forced disabled=((dashboard.latest or not dashboard.health) and not force))) try: dashboard_id = questionary.select( "Please select installation(s) from the list", choices=selection).ask() except: print( '\nNo updates available or dashboard(s) is/are broken, use --force to allow selection\n' ) finally: return dashboard_id
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()
def artist_handler(results): choices = [] for result in results: provider = result.provider.name name = result.name label = f"{name} [{provider}]" choices.append(questionary.Choice(label, value=result)) return choices
def playlist_download(self): playlists = self.spotify.get_user_playlists() choices = [questionary.Choice("Saved Music", value=0)] choices.extend( [ questionary.Choice(playlists[i].name, value=i + 1) for i in range(len(playlists)) ] ) answers = questionary.form( filename=questionary.text("What should the file be named?"), playlist_idx=questionary.select( "Which playlist would you like to download?", choices=choices ), ).ask() playlist_idx = answers["playlist_idx"] tracklist: List[tekore.model.FullTrack] if playlist_idx == 0: # Saved music tracklist = self.spotify.get_user_library() else: # Other playlist paging_tracks = playlists[playlist_idx - 1].tracks tracklist = [ track.track for track in paging_tracks.items if not track.is_local ] processed_tracks = [ { "Title": track.name, "Album Artist": ", ".join( [artist.name for artist in track.album.artists] ), "Album": track.album.name, } for track in tracklist ] pyexcel.save_as( records=processed_tracks, dest_file_name=answers["filename"] + ".xlsx" )
def select(self, target_group=None, exploit=None, prompt=False): if prompt: import questionary exploit = questionary.select( '选择启动的攻击脚本', [questionary.Choice('all', value='')] + list(self._config['exploits'].keys())).ask() target_group = questionary.select( '选择目标组', [questionary.Choice('all', value='')] + list(self._config['target_groups'].keys())).ask() for name, prop in self._config['exploits'].items(): if exploit and name != exploit: continue for tg in prop['target']: if target_group and target_group != tg: continue for target in self._config['target_groups'][tg]: yield name, target
def _fill_up_instances_choices(states: list, region): choices_list = [ questionary.Choice(title=i['title'], value=i['value']) for i in aws_account_util.get_ec2_instances(states, region) ] if choices_list: choices_list.append(CancelAnswer) return choices_list
def prompt_group(self, group_id, group_obj): """ Prompt for edits to a group of parameters (subschema in 'definitions') Args: group_id: Paramater ID (string) group_obj: JSON Schema keys (dict) Returns: Dict of param_id:val answers """ while_break = False answers = {} while not while_break: question = { "type": "list", "name": group_id, "message": group_obj.get("title", group_id), "choices": ["Continue >>", questionary.Separator()], } for param_id, param in group_obj["properties"].items(): if not param.get("hidden", False) or self.show_hidden: q_title = param_id if param_id in answers: q_title += " [{}]".format(answers[param_id]) elif "default" in param: q_title += " [{}]".format(param["default"]) question["choices"].append( questionary.Choice(title=q_title, value=param_id)) # Skip if all questions hidden if len(question["choices"]) == 2: return {} self.print_param_header(group_id, group_obj) answer = questionary.unsafe_prompt([question], style=nfcore_question_style) if answer[group_id] == "Continue >>": while_break = True # Check if there are any required parameters that don't have answers for p_required in group_obj.get("required", []): req_default = self.schema_obj.input_params.get( p_required, "") req_answer = answers.get(p_required, "") if req_default == "" and req_answer == "": log.error("'--{}' is required.".format(p_required)) while_break = False else: param_id = answer[group_id] is_required = param_id in group_obj.get("required", []) answers.update( self.prompt_param(param_id, group_obj["properties"][param_id], is_required, answers)) return answers
def interact(self): choices = [ questionary.Choice('Organize by module, only download files', 'module'), questionary.Choice( 'Organize by module, download files, links and pages', 'module_link'), questionary.Choice('As-is in file list', 'file'), questionary.Choice('As-is in file list, plus pages', 'file_link'), questionary.Choice('Custom', 'custom', disabled='not supported yet') ] self.mode = questionary.select('Select default file organization mode', choices, default=find_choice( choices, self.mode)).unsafe_ask() choices = [ questionary.Choice( "Delete local files if they disappears on Canvas", True), questionary.Choice("Always keep local files", False) ] self.delete_file = questionary.select( 'How to handle deleted files on Canvas', choices, default=find_choice(choices, self.delete_file)).unsafe_ask()
def run(self): response = questionary.select( "What would you like to do?", choices=[ questionary.Choice( "Download playlist as CSV", value=self.playlist_download ), questionary.Choice( "Reorder existing playlist based on BPM", value=self.reorder_playlist_bpm, ), questionary.Choice( "Generate Fitness Playlist", value=self.generate_fitness_playlist ), ], ).ask() response()
def album_handler(results): choices = [] for result in results: provider = result.provider.name name = result.name artist = ", ".join([artist.name for artist in result.artists]) indent = constants.INDENT + " " * 3 year = result.year label = (f"{name} ({year})\n{indent}{artist} [{provider}]\n" if year else f"{name}\n{indent}{artist} [{provider}]\n") choices.append(questionary.Choice(label, value=result)) return choices
def interact(self, courses): groups = group_by(courses, lambda course: course.enrollment_term_id) choices = [] for (term, courses) in groups.items(): choices.append( questionary.Choice( f'Term {term}: {summarize_courses(courses)}', term, checked=term in self.terms)) choices = sorted(choices, key=lambda choice: choice.value) choices.append( questionary.Choice('Latest term only', -1, checked=-1 in self.terms)) choices.reverse() while True: self.terms = questionary.checkbox('Select terms to download', choices).unsafe_ask() if len(self.terms) == 0: print('At least one term must be selected.') elif -1 in self.terms and len(self.terms) != 1: print('Invalid choice') else: break
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
def ask(self): self.answer = questionary.select( "Modify Action?", choices=[ self.main_menu, self.report, self.start, self.stop, self.reboot, self.terminate, self.change_region, questionary.Choice(title="Upgrade Tableau Server", disabled="not yet supported"), ], style=custom_style).ask() return self.answer
def run_prompt(config: Config, session: Session, old_album: Album, new_album: Album) -> Optional[Album]: """Runs the interactive prompt for the given album changes. Args: config: Moe config. session: Current db session. old_album: Original album to be added. new_album: New album with all metadata changes. Will be compared against ``old_album``. Returns: The album to be added to the library. """ if old_album == new_album: return old_album existing_album = new_album.get_existing(session) old_album.merge(existing_album, overwrite_album_info=False) print(_fmt_album_changes(old_album, new_album)) # noqa: WPS421 prompt_choices: List[PromptChoice] = [] config.plugin_manager.hook.add_prompt_choice(prompt_choices=prompt_choices) prompt_choices.sort(key=operator.attrgetter("shortcut_key")) questionary_choices: List[questionary.Choice] = [] for prompt_choice in prompt_choices: questionary_choices.append( questionary.Choice( title=prompt_choice.title, shortcut_key=prompt_choice.shortcut_key, value=prompt_choice.func, )) prompt_choice_func = questionary.rawselect( "What do you want to do?", choices=questionary_choices).ask() if prompt_choice_func: return prompt_choice_func( config=config, session=session, old_album=old_album, new_album=new_album, ) return None
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
def ask(self, vpcs: list): vpc_choices = [] for v in vpcs: tags = utils.convert_tags(v.get("Tags")) vpc_name = tags.get('Name', '') + (" (default)" if v['IsDefault'] else "") qc = questionary.Choice(title=f"{v['VpcId']} | {vpc_name}", value=v['VpcId']) if v['IsDefault']: vpc_choices.insert(0, qc) else: vpc_choices.append(qc) self.answer = questionary.select( "Choose AWS VPC to place the servers?", choices=vpc_choices, style=custom_style).ask() return self.answer
def ask(self): region = self.params['region'] vpc_id = self.params['vpc_id'] subnets_choices = [] for item in aws_account_util.get_available_subnets(region, vpc_id): tag_value = " | " + item["Tags"][0]["Value"] if item.get( "Tags") else "" subnets_choices.append( questionary.Choice(title=f"{item['SubnetId']}{tag_value}", value=item['SubnetId'])) if not subnets_choices: subnets_choices = [self.no_subnets] self.answer = questionary.checkbox("Which Subnet ID(s)?", choices=subnets_choices, style=custom_style).ask() return self.answer
def select_metadata_collection_method(self) -> str: """ Selects the method to collect metadata """ logger.info('Metadata source selection') # Ask user which method to use to retreive account list selection = list() account_map_sources = { 'csv': 'CSV file (relative path required)', 'organization': 'AWS Organizations (one time account listing)', 'dummy': 'Dummy (CUR account data, no names)' } for k, v in account_map_sources.items(): selection.append(questionary.Choice(title=f'{v}', value=k)) selected_source = questionary.select( "Please select account metadata collection method", choices=selection).ask() if selected_source in account_map_sources.keys(): logger.info(f'Selected {selected_source}') self._metadata_source = selected_source # Collect account list from different sources of user choice if self._metadata_source == 'csv': finished = False while not finished: mapping_file = click.prompt("Enter file path", type=str) finished = self.check_file_exists(mapping_file) if not finished: click.echo('File not found, ', nl=False) click.echo('\nCollecting account info...', nl=False) self._accounts = self.get_csv_accounts(mapping_file) logger.info(f'Found {len(self._accounts)} accounts') click.echo(f' {len(self.accounts)} collected') elif self._metadata_source == 'organization': click.echo('\nCollecting account info...', nl=False) self._accounts = self.get_organization_accounts() logger.info(f'Found {len(self._accounts)} accounts') click.echo(f' {len(self.accounts)} collected') elif self._metadata_source == 'dummy': click.echo('Notice: Dummy account mapping will be created') else: print('Unsupported selection') return False
def user(self) -> dict: if not self._user: self._user = self.describe_user('/'.join( self.awsIdentity.get('Arn').split('/')[-2:])) if not self._user: # If no user match, ask userList = self.use1Client.list_users( AwsAccountId=self.account_id, Namespace='default').get('UserList') selection = list() for user in userList: selection.append( questionary.Choice( title= f"{user.get('UserName')} ({user.get('Email')}, {user.get('Role')})", value=user)) try: self._user = questionary.select( "Please select QuickSight to use", choices=selection).ask() except: return None logger.info(f"Using QuickSight user {self._user.get('UserName')}") return self._user
""" Generadores de números pseudoaleatorios. """ from os import system import questionary from Productomedio import numeros_pseudoaleatorios from Cuadrado_medio import cuadrado_medio from mcml import mcml option = questionary.select('¿Cuál método desea probar?', [ questionary.Choice('Producto medio', 1), questionary.Choice('Cuadrados medios', 2), questionary.Choice('Método congruencial mixto o lineal', 3) ]).ask() if option == 1: numeros_pseudoaleatorios() elif option == 2: seed = questionary.text('Ingresa la semilla:').ask() random = cuadrado_medio(int(seed)) print('Número aleatorio:', random) elif option == 3: n = int(input('Inserte el limite de numeros aleatorios a desear ->')) while True: mod = int(input('Inserte el valor del modulo ->')) print( 'Los siguientes valores deben cumplir con la condicion de ser menores al modulo' )
custom_style = Style([ ("qmark", "fg:#02abab bold"), ("question", "bold"), ("answer", "fg:#02abab bold"), ("pointer", "fg:#02abab bold"), ("highlighted", "fg:#02abab bold"), ("selected", "fg:#02abab"), ("separator", "fg:#02abab"), ("instruction", ""), ("text", ""), ]) AWS_OS_TYPES = {"AmazonLinux2": "linux", "AmazonWindows2019": "windows"} CancelAnswer = questionary.Choice(title="Cancel") class Question: answer: str = None params: dict = None def asking(self, **kwargs): if kwargs: self.params = kwargs self.ask() while not self.validate_and_print(): self.ask() return self.answer