示例#1
0
def main():
    git.exit_if_cwd_not_git_repo()
    git.dotfiles_private_pull_latest()

    profile_name = profiles.get_current_name(exit_if_not_set=True)
    workspace = os.path.basename(
        os.path.abspath(os.path.join(os.curdir, os.pardir)))
    dirname = os.path.basename(os.path.abspath(os.curdir))

    puts(colored.blue('Profile: %s' % profile_name))
    puts(colored.blue('Workspace: %s' % workspace))
    puts(colored.blue('Repo: %s' % dirname))
    answers = prompt([
        {
            'name': 'name',
            'type': 'input',
            'message': 'Remote name to remove:',
        }
    ])
    if 'name' not in answers:
        exit(1)

    remote_name = answers['name']

    git.remove_remote(remote_name, exit_on_error=True)
    profiles.update_profile_git_workspace_remove_git_remote(
        profile_name, workspace, dirname, remote_name)
    git.dotfiles_private_commit_and_push_changes(
        'Git Remote: %s > %s > %s' % (workspace, dirname, remote_name))
示例#2
0
def run(brew_command):
    git.dotfiles_private_pull_latest()

    profile = profiles.get_current_name(exit_if_not_set=True)
    profile_names = profiles.read_names()
    profile_choices = [{'name': n, 'checked': n == profile}
                       for n in profile_names]
    answers = prompt([
        {
            'name': 'input',
            'type': 'input',
            'message': '%s:' % brew_command.input_name,
        },
        {
            'name': 'profiles',
            'type': 'checkbox',
            'message': 'Which profiles should this affect:',
            'choices': profile_choices,
        },
    ])

    if 'input' not in answers or 'profiles' not in answers:
        exit(1)

    selected_profiles = answers['profiles']
    input = answers['input']

    if brew_command.command_runner(input):
        for profile_name in selected_profiles:
            brew_command.json_updater(profile_name, input)
        git.dotfiles_private_commit_and_push_changes(
            'Brew %s: %s' % (brew_command.input_name, input))
示例#3
0
def ask_file(files, student, spec, basedir):
    style = style_from_dict({
        Token.QuestionMark: '#e3bd27 bold',
        Token.Selected: '#e3bd27',
        Token.Pointer: '#e3bd27 bold',
        Token.Answer: '#e3bd27 bold',
    })

    while True:
        questions = [
            {
                'type': 'list',
                'name': 'file',
                'message': 'Choose file',
                'choices': ['BACK'] + files,
            }
        ]
        file = prompt(questions, style=style)

        if file and file['file'] != 'BACK':
            file_spec = {}
            for f in spec['files']:
                if f['filename'] == file['file']:
                    file_spec = f
                    break
            if file_spec:
                with chdir('{}/{}'.format(student, spec['assignment'])):
                    # prepare the current folder
                    inputs = spec.get('inputs', [])
                    supporting = os.path.join(basedir, 'data', 'supporting')
                    # write the supporting files into the folder
                    for filename in inputs:
                        with open(os.path.join(supporting, spec['assignment'], filename), 'rb') as infile:
                            contents = infile.read()
                        with open(os.path.join(os.getcwd(), filename), 'wb') as outfile:
                            outfile.write(contents)
                    process_file(file_spec['filename'],
                                 steps=file_spec['commands'],
                                 options=file_spec['options'],
                                 spec=spec,
                                 cwd=os.getcwd(),
                                 supporting_dir=os.path.join(basedir, 'data', 'supporting'),
                                 interact=False,
                                 basedir=basedir,
                                 spec_id=spec['assignment'],
                                 skip_web_compile=False)
                    # and we remove any supporting files
                    try:
                        for inputfile in inputs:
                            os.remove(inputfile)
                    except FileNotFoundError:
                        pass
        else:
            return
示例#4
0
def link_file(src, dest):
    global link_dotfiles_overwrite_all
    global link_dotfiles_backup_all
    global link_dotfiles_skip_all
    overwrite, backup, skip = (False, False, False)

    if os.path.isfile(dest) or os.path.islink(dest):
        if not link_dotfiles_overwrite_all and not link_dotfiles_backup_all and not link_dotfiles_skip_all:
            short_file_path = dest.replace(PATHS.HOME, '~')
            answers = prompt([
                {
                    'name': 'action',
                    'type': 'list',
                    'message': '%s already exists' % short_file_path,
                    'choices': [
                        'overwrite',
                        'overwrite all',
                        'backup',
                        'backup all',
                        'skip',
                        'skip all',
                    ]
                }
            ])

            if 'action' not in answers:
                exit(1)

            action = answers['action']
            overwrite = action == 'overwrite'
            link_dotfiles_overwrite_all = action == 'overwrite all'
            backup = action == 'backup'
            link_dotfiles_backup_all = action == 'backup all'
            skip = action == 'skip'
            link_dotfiles_skip_all = action == 'skip all'

        if overwrite or link_dotfiles_overwrite_all:
            os.remove(dest)
            puts(colored.yellow('deleted %s' % dest))

        if backup or link_dotfiles_backup_all:
            os.rename(dest, '%s.bak' % dest)
            puts(colored.cyan('moved %s to %s.bak' % (dest, dest)))

    if skip or link_dotfiles_skip_all:
        puts(colored.cyan('skipped %s' % dest))
    else:
        os.symlink(src, dest)
        puts('linked %s -> %s' % (src, dest))
示例#5
0
def salesman(name):
    salesman = Salesman(name)
    position_helper = PositionsHelper()
    salesmans_list = position_helper.get_all_salesmans()
    if name not in salesmans_list:
        raise Exception(f"There is no {name} in list of salesmans")
    coffee_with_price_list = salesman.get_all_coffee_with_price()
    additional_ingridients = salesman.get_all_additional_ingredients()

    answers = prompt(questions=coffee_questions(coffee_with_price_list, additional_ingridients),
                     style=custom_style_1)#how to add some(2) latte?
    # pprint(answers)
    position_helper.update_summary_table_by_name("total", name, answers)
    position_helper.update_summary_table_by_name("number_of_sales", name, answers)

    if answers[const.BILL] == const.YES:
        salesman.get_bill(answers)
示例#6
0
def main():
    git.dotfiles_private_pull_latest()
    current_profile_name = profiles.get_current_name(exit_if_not_set=True)
    puts(colored.blue('Profile: %s' % current_profile_name))

    num_brew_casks = len(profiles.read_brew_casks())
    num_brew_formulae = len(profiles.read_brew_formulae())
    num_brew_taps = len(profiles.read_brew_taps())
    num_brew_items = num_brew_casks + num_brew_formulae + num_brew_taps

    workspace_names = profiles.read_git_workspace_names()
    workspace_info = []
    for workspace_name in workspace_names:
        num_repos = len(profiles.read_git_workspace_repos(workspace_name))
        workspace_info.append('%s: %d repos' % (workspace_name, num_repos))

    answers = prompt([
        {
            'name': 'jobs',
            'type': 'checkbox',
            'message': 'What would you like to sync:',
            'choices': [
                {
                    'name': 'Brew (%d items)' % num_brew_items,
                    'checked': True,
                },
                {
                    'name': 'Git workspaces (%s)' % ', '.join(workspace_info),
                    'checked': True,
                },
            ],
        },
    ])
    if 'jobs' not in answers:
        exit(1)

    for job in answers['jobs']:
        if job.startswith('Brew'):
            brew.update()
            brew.tap_all_repos(profiles.read_brew_taps())
            brew.install_or_upgrade_all_formulae(profiles.read_brew_formulae())
            brew.install_or_upgrade_all_casks(profiles.read_brew_casks())

        if job.startswith('Git workspaces'):
            git_sync.run()
示例#7
0
def get_answers(defaults: dict):
    # Input prompts
    questions = [
        {
            'type': 'password',
            'name': constants.BITBUCKET_PASS,
            'message': 'What\'s yout BitBucket password?'
        },
        {
            'type': 'input',
            'name': constants.BITBUCKET_USERNAME,
            'message': 'What\'s your BitBucket username?',
            'default': defaults.get(constants.BITBUCKET_USERNAME, '')
        },
        {
            'type': 'input',
            'name': constants.SSH_DIR,
            'message': 'Where do you want to store the new ssh keys? eg.. /home/<username>/.ssh',
            'default': defaults.get(constants.SSH_DIR, '')
        },
        {
            'type': 'input',
            'name': constants.REPO_DIR,
            'message': 'Where do you want to checkout the twx-scm-monitoring repo? eg.. /home/<username>/repo',
            'default': defaults.get(constants.REPO_DIR, '')
        },
        {
            'type': 'input',
            'name': constants.BRANCH_NAME,
            'message': 'What is your branch name in twx-scm-monitoring repo?',
            'default': defaults.get(constants.BRANCH_NAME, '')
        },
        {
            'type': 'input',
            'name': constants.EMAIL,
            'message': 'What is your Email id?',
            'default': defaults.get(constants.EMAIL, '')
        }
    ]
    answers = prompt(questions)
    return answers
示例#8
0
def main():
    git.exit_if_cwd_not_git_repo()
    git.dotfiles_private_pull_latest()

    profile_name = profiles.get_current_name(exit_if_not_set=True)
    workspace = os.path.basename(
        os.path.abspath(os.path.join(os.curdir, os.pardir)))
    dirname = os.path.basename(os.path.abspath(os.curdir))

    puts(colored.blue('Profile: %s' % profile_name))
    puts(colored.blue('Workspace: %s' % workspace))
    puts(colored.blue('Repo: %s' % dirname))
    answers = prompt([
        {
            'name': 'url',
            'type': 'input',
            'message': 'Git url:',
        },
        {
            'name': 'name',
            'type': 'input',
            'message': 'Remote name:',
        }
    ])
    if 'url' not in answers or 'name' not in answers:
        exit(1)

    remote_url = answers['url']
    remote_name = answers['name']

    ssh_config = profiles.read_git_workspace_ssh_config(workspace)
    mapped_url = remote_url.replace(ssh_config['hostname'], ssh_config['host'])

    git.add_remote(remote_name, mapped_url, exit_on_error=True)
    git.fetch(remote_name, exit_on_error=True)
    profiles.update_profile_git_workspace_add_git_remote(
        profile_name, workspace, dirname, remote_name, remote_url)
    git.dotfiles_private_commit_and_push_changes(
        'Git Remote: %s > %s > %s' % (workspace, dirname, remote_name))
示例#9
0
def ask_student(usernames):
    style = style_from_dict({
        Token.QuestionMark: '#959ee7 bold',
        Token.Selected: '#959ee7',
        Token.Pointer: '#959ee7 bold',
        Token.Answer: '#959ee7 bold',
    })
    questions = [
        {
            'type': 'list',
            'name': 'student',
            'message': 'Choose student',
            'choices': ['QUIT', 'LOG and QUIT', *usernames]
        }
    ]

    student = prompt(questions, style=style)

    if not student:
        return None

    return student['student']
示例#10
0
def main():
    git.dotfiles_private_pull_latest()

    profile_name = profiles.get_current_name(exit_if_not_set=True)
    puts(colored.blue('Profile: %s' % profile_name))
    answers = prompt([
        {
            'name': 'workspace',
            'type': 'list',
            'message': 'Workspace:',
            'choices': profiles.read_git_workspace_names(),
        },
        {
            'name': 'dirname',
            'type': 'input',
            'message': 'Directory name:',
        },
    ])

    if 'workspace' not in answers or 'dirname' not in answers:
        exit(1)

    workspace = answers['workspace']
    dirname = answers['dirname']

    if not profiles.read_git_workspace_repo(workspace, dirname):
        puts_err(colored.red(
            '! the given workspace does not include that repo: %s' % dirname))
        exit(1)

    profiles.update_profile_git_workspace_remove_git_repo(
        profile_name, workspace, dirname)
    git.dotfiles_private_commit_and_push_changes('Remove Git Repo: %s > %s' %
                                                 (workspace, dirname))
    puts(colored.yellow('This repo has been removed from your profile,'))
    puts(colored.yellow('but you must remove the cloned repo from your local filesystem.'))
示例#11
0
def pokeDetector_func(*args):
	username = args[1]['username']
	dbSession = orm()
	usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
	usrObj = utilisateur(*usrSQL)
	myZone = int(usrObj.zone[0])
	pokSQLArr = dbSession.filterBy.get(tablename="pokemon", zone=myZone, state='Wild')

	options, pokObjArr = [], []
	pok_uuid = []
	for pok_ in pokSQLArr:
		pokObj_tmp = pokemon(*pok_)
		pokObjArr.append(pokObj_tmp)
		options.append(pokObj_tmp.name[0])
		pok_uuid.append(pokObj_tmp.id[0])

	usrObj.pokedex[0] = json.dumps(pok_uuid)
	updateObj(usrObj)

	pyMenus_pokArr = args[0]['targetpokeMenu']
	pyMenus_pokArr[0]['choices'] = options

	answers_1 = prompt(pyMenus_pokArr)

	pyMenus_action = args[0]['fightPok']
	answers_2 = prompt(pyMenus_action)
	if answers_2['currentQ'] == 'Info':
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]
		pokProfile_tree(targetPok_)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]

	elif answers_2['currentQ'] == 'Capture':
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]
		usrObj.Capture(targetPok_)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]

	elif answers_2['currentQ'] == 'Fight':
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]

		combatObj = combat(userObj=usrObj, enemyPokObj=targetPok_)
		resp = [1, 'pass']
		while resp[0]:
			
			if resp[1] == 'Capture':
				usrObj.Capture(targetPok_)
				if targetPok_.state[0] == 'Not Wild':
					input("Cliquez sur [Entrée] pour Go back to the main menu")
					return [1, "pass", ""]
			elif resp[1] == 'Escape':
				return [1, "pass", "You run out of the fight"]
			elif resp[1] == 'Print':
				print(resp[2])
			elif resp[1] == 'Table':
				fightStats = PrettyTable()
				fightStats.field_names = ['Name', 'Experience', 'Health']
				_  = [fightStats.add_row(r) for r in resp[2]]
				print(fightStats)
			resp = combatObj.call_menus_and_controle_comabt_flow()

		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]

	else:
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]
		usrObj.Capture(targetPok_)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]
示例#12
0
 def ask(self):
     return prompt(self.widget)['pass']
示例#13
0
def healingPotion():
    global DGPlayer
    theResult = 0

    if DGPlayer.Inventory.basicHealingPotion != 0:
        DGText.printScan(DGText.success +
                         "You have {amount} basic healing potions.".format(
                             amount=DGPlayer.Inventory.basicHealingPotion))

    if DGPlayer.Inventory.advancedHealingPotion != 0:
        DGText.printScan(DGText.success +
                         "You have {amount} advanced healing potions.".format(
                             amount=DGPlayer.Inventory.advancedHealingPotion))

    if DGPlayer.Inventory.basicHealingPotion == 0 and DGPlayer.Inventory.advancedHealingPotion == 0:
        DGText.printScan(DGText.error + "You don't have any potions!")
        askLoop = False
        return "notUsed"

    # Adds a new line
    print("")

    questions = [{
        'type':
        'list',
        'name':
        'itemChoice',
        'choices': ["Basic Healing Potion", "Advanced Healing Potion", 'Exit'],
        'message':
        'What potion would you like to use?',
    }]

    askLoop = True
    while askLoop:
        print(Style.RESET_ALL)
        theAnswer = prompt(questions)
        userInput = theAnswer['itemChoice']

        if userInput == "Exit":
            DGText.printScan("")
            askLoop = False
            return theResult

        elif userInput == "Basic Healing Potion":
            if DGPlayer.Inventory.basicHealingPotion > 0:
                theResult = theResult + 1
                DGText.printScan(DGText.rip +
                                 "You used up 1 basic healing potion")
                DGPlayer.Inventory.basicHealingPotion = DGPlayer.Inventory.basicHealingPotion - 1
                DGPlayer.heal(20)
                time.sleep(0.4)

            else:
                DGText.printScan(DGText.error +
                                 "You don't have any basic healing potions!\n")

        elif userInput == "Advanced Healing Potion":
            if DGPlayer.Inventory.advancedHealingPotion > 0:
                theResult = theResult + 1
                DGText.printScan(DGText.rip +
                                 "You used up 1 advanced healing potion")
                DGPlayer.Inventory.advancedHealingPotion = DGPlayer.Inventory.advancedHealingPotion - 1
                DGPlayer.heal(50)
                time.sleep(0.4)

            else:
                DGText.printScan(
                    DGText.error +
                    "You don't have any advanced healing potions!\n")
示例#14
0
def main():
    print('''
    ____                _          _     _                 _     _          
   / ___|__ _ _ __ ___ | |__  _ __(_) __| | __ _  ___  ___| |__ (_)_ __ ___ 
  | |   / _` | '_ ` _ \| '_ \| '__| |/ _` |/ _` |/ _ \/ __| '_ \| | '__/ _ \\
  | |__| (_| | | | | | | |_) | |  | | (_| | (_| |  __/\__ \ | | | | | |  __/
   \____\__,_|_| |_| |_|_.__/|_|  |_|\__,_|\__, |\___||___/_| |_|_|_|  \___|
  |  _ \(_) __ _(_) |_ __ _| |             |___/                            
  | | | | |/ _` | | __/ _` | |                                              
  | |_| | | (_| | | || (_| | |                                              
  |____/|_|\__, |_|\__\__,_|_|                                              
           |___/                                                            

  Cambridgeshire Digital Sharepoint Downloader 0.4
  This tool can download the Excel exports from Sharepoint Views.

  https://github.com/CCCandPCC/sharepoint-view-save
  ''')

    xlsx = [
        f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.xlsx')
    ]

    questions = [{
        'type': 'list',
        'name': 'source_file',
        'message': "Select the Excel file containing the Sharepoint export",
        'choices': xlsx
    }]

    if (len(xlsx) == 0):
        input(
            '\nERROR: You must place the .xlsx file you want to import in the same directory as this application.'
        )
        exit()

    setup = prompt(questions)
    ws = download.DownloadSharepoint()
    sheets = ws.open_xl(setup['source_file'])

    if len(sheets) > 1:
        questions2 = [{
            'type': 'list',
            'name': 'worksheet',
            'message': "Select the worksheet containing the data",
            'choices': sheets
        }]
        ws_name = prompt(questions2)['worksheet']
    else:
        ws_name = sheets[0]

    ws.select_ws(ws_name)

    # authentication
    ws.do_auth = login

    # headers
    selected_folders = prompt([{
        'type':
        'checkbox',
        'name':
        'folders',
        'message':
        "Select the headers you'd like to use as folders",
        'choices':
        map(lambda x: {'name': str(x[0])}, ws.headers)
    }])['folders']

    ordered_folders = folder_order(selected_folders, True)

    out = prompt([{
        'type': 'input',
        'name': 'output',
        'message': "Which folder would you like to output downloaded files to",
        'default': "output"
    }])['output']

    path_str = [out] + list(map(lambda x: '[' + x + ']', ordered_folders))
    msg = "Save files into " + '\\'.join(path_str) + "?"
    confirm = [{'type': 'confirm', 'name': 'conf', 'message': msg}]

    if prompt(confirm)['conf']:
        ws.download_sharepoint_xl(out, ordered_folders)

    input('\nComplete. Press Enter to exit.')
示例#15
0
文件: inplace.py 项目: horta/inplace
def entry(path, regex):
    """Find and replace files interactively.

    """
    if not os.path.exists(path):
        click.echo("{} does not exist.".format(path))
        return 1

    click.echo("Compiling the file list... ", nl=False)
    files = check_output(["find", path, "-type", "f", "-print0"])
    click.echo("done.")

    files = files.split(b"\0")[:-1]
    matched_files = []
    max_matches = -1
    click.echo("Finding matches... ", nl=False)
    for f in files:
        f = f.decode()

        arg = 'my $number = $_ =~ {}; print scalar "$number "'.format(regex)
        try:
            o = check_output(["perl", "-ne", arg, f])
        except CalledProcessError as e:
            return e.returncode

        o = b" ".join(o.strip().split()).split()
        if len(o) > 0:
            n = sum(int(i) for i in o)
            matched_files.append((f, n))
            max_matches = max(max_matches, n)

    click.echo("done.")
    import pdb
    pdb.set_trace()

    if max_matches < 0:
        click.echo("No match has been found.")
        return 0

    num_siz = len(str(max_matches))
    left_siz = num_siz + len(" match(es): ")
    for m in matched_files:
        fmt = "{:" + str(num_siz) + "d}"
        msg = fmt.format(m[1]) + " match(es): {}".format(m[0])
        question["choices"].append({"name": msg})

    answers = prompt(question)
    if "files" not in answers:
        # click.echo("Completed successfully.")
        return 0

    nfails = 0
    for a in answers["files"]:
        filepath = a[left_siz:]
        click.echo(filepath + "... ", nl=False)
        e = call(["perl", "-p", "-i", "-e", regex, filepath])
        if e == 0:
            click.echo("done.")
        else:
            click.echo("FAILED!")
            nfails += 1

    if nfails == 0:
        click.echo("Completed successfully.")
        return 0
    else:
        click.echo("Failed to change {} files!".format(nfails))
        return 1
示例#16
0
        if not result[0][0]:
            raise ValidationError(message='Ticket doesn\'t exist in database',
                                  cursor_position=len(
                                      document.text))  # Move cursor to end


questions00 = [{
    'type': 'input',
    'message': 'Enter your username: '******'name': 'username'
}, {
    'type': 'password',
    'message': 'Enter your password',
    'name': 'password'
}]
answers00 = prompt(questions00, style=custom_style_2)
if (answers00['username'] == "admin" and answers00['password'] == "adminpass"):
    bAdmin = True
    while bAdmin:
        print("Welocme ", answers00['username'])
        questions01 = [{
            'type':
            'list',
            'name':
            'Admin Menu',
            'message':
            'What do you want to do?',
            'choices': [
                'Add a new flight record',
                'Update details of an existing flight record',
                'Cancel a flight record',
示例#17
0
def create_module(args):
    print('Witaj w narzędziu tworzącym moduł mapy Mrucznik Role Play')

    questions = [{
        'type': 'input',
        'name': 'name',
        'message': 'Jak ma nazywać się moduł?',
        'validate': ComponentNameValidator
    }, {
        'type': 'input',
        'name': 'description',
        'message': 'Uzupełnij opis modułu:',
    }, {
        'type': 'input',
        'name': 'author',
        'message': 'Kto jest autorem modułu?',
        'default': getpass.getuser()
    }, {
        'type': 'confirm',
        'name': 'timers',
        'message': 'Czy moduł będzie posiadał timery?'
    }, {
        'type': 'confirm',
        'name': 'callbacks',
        'message': 'Czy moduł posiadał callbacki?'
    }, {
        'type': 'confirm',
        'name': 'mysql',
        'message': 'Czy moduł będzie korzystał z mysql?'
    }, {
        'type': 'confirm',
        'name': 'files',
        'message': 'Czy moduł będzie posiadał dodatkowe pliki?'
    }, {
        'type': 'confirm',
        'name': 'commands',
        'message': 'Czy chcesz dodać komendy do modułu?'
    }]

    answers = prompt(questions)
    answers['date'] = datetime.datetime.now().strftime("%d.%m.%Y")

    custom_files = []
    if answers['files']:
        next_element = True
        while next_element:
            custom_files.append(
                prompt([{
                    'type':
                    'input',
                    'name':
                    'file',
                    'message':
                    'Wpisz nazwę dodatkowego pliku razem z rozszerzeniem:'
                }])['file'])
            next_element = prompt([{
                'type': 'confirm',
                'name': 'next',
                'message': 'Czy chcesz dodać kolejny plik?'
            }])['next']
    answers['files'] = custom_files

    os.mkdir(answers['name'])
    with cd(answers['name']):
        with open('module.json', 'w', encoding='windows-1250') as file:
            json.dump(answers, file, indent=4, ensure_ascii=False)
            print('Moduł pomyślnie utworzony jako plik module.json')

        if answers.pop('commands'):
            os.mkdir('commands')
            with cd('commands'):
                next_element = True
                while next_element:
                    create_command(args)
                    next_element = prompt([{
                        'type':
                        'confirm',
                        'name':
                        'next',
                        'message':
                        'Czy chcesz dodać kolejną komendę?'
                    }])['next']
                print('Pomyślnie utworzono pliki konfiguracyjne komendy')

        if args.build:
            print('Uruchamiam generator modułu...')
            generate_module()

    if args.build:
        print('Generowanie modules.pwn')
        generate_modules_inc()
    print('Gotowe. Możesz zacząć skrypcić ;)')
示例#18
0
def key_prompt(questions):
    """ prompt wrapper to handle ctrl+c """
    resp = prompt(questions)
    if len(resp) != len(questions):
        raise KeyboardInterrupt
    return resp
    def main(self):
        # Main function to call

        main_menu_questions = [{
            'type':
            'list',
            'name':
            'todo',
            'message':
            'What do you want to do?',
            'choices': [
                'Insert', 'Update', 'Summary', 'Calculate GPA',
                'Save and Close', 'Close'
            ]
        }]

        main_menu_answers = prompt(main_menu_questions, style=custom_style_2)
        while (main_menu_answers['todo'] !=
               "Save and Close") and (main_menu_answers['todo'] != "Close"):
            if main_menu_answers['todo'] == "Insert":
                insert_questions = [
                    {
                        'type': 'input',
                        'name': 'Course Id',
                        'message': 'Course Id:',
                        'validate': lambda text: len(text) == 9,
                    },
                    {
                        'type': 'input',
                        'name': 'Course Name',
                        'message': 'Course Name:',
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type':
                        'input',
                        'name':
                        'Year',
                        'message':
                        'Year:',
                        'validate':
                        lambda text: len(text) > 0 and self.check_int(text),
                    },
                    {
                        'type': 'input',
                        'name': 'Semester',
                        'message': 'Semester:',
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type': 'input',
                        'name': 'Credit',
                        'message': 'Credit:',
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type': 'input',
                        'name': 'Section',
                        'message': 'Section:',
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type': 'list',
                        'name': 'Grade',
                        'message': 'Grade:',
                        'choices': [
                            'A',
                            'B+',
                            'B',
                            'C+',
                            'C',
                            'D+',
                            'D',
                            'F',
                        ]
                    },
                ]
                insert_answers = prompt(insert_questions,
                                        style=custom_style_2)  # Get the answer
                insert_answers["Grade(Score)"] = self.grade_table[
                    insert_answers['Grade']]  # Map Grade to score

                self.db = self.db.append(
                    insert_answers,
                    ignore_index=True)  # Append the new course to DB

            elif main_menu_answers['todo'] == "Update":
                print(tabulate(self.db, headers='keys',
                               tablefmt='psql'))  # Show current DB
                update_questions = [{
                    'type':
                    'input',
                    'name':
                    'course',
                    'message':
                    'Which course do you want to update?',
                    'validate':
                    lambda text: int(text) <= self.db.tail(1).index.item(),
                }]

                update_answers = prompt(update_questions, style=custom_style_2)
                course_info = self.db.iloc[int(
                    update_answers['course']
                )]  # Find selected course from answer

                default_grade = {
                    'A': 0,
                    'B+': 1,
                    'B': 2,
                    'C+': 3,
                    'C': 4,
                    'D+': 5,
                    'D': 6,
                    'F': 7
                }

                update_course_questions = [
                    {
                        'type': 'input',
                        'name': 'Course Id',
                        'message': 'Course Id:',
                        'default': course_info['Course Id'],
                        'validate': lambda text: len(text) == 9,
                    },
                    {
                        'type': 'input',
                        'name': 'Course Name',
                        'message': 'Course Name:',
                        'default': course_info['Course Name'],
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type':
                        'input',
                        'name':
                        'Year',
                        'message':
                        'Year:',
                        'default':
                        course_info['Year'],
                        'validate':
                        lambda text: len(text) > 0 and self.check_int(text),
                    },
                    {
                        'type': 'input',
                        'name': 'Semester',
                        'message': 'Semester:',
                        'default': course_info['Semester'],
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type': 'input',
                        'name': 'Credit',
                        'message': 'Credit:',
                        'default': str(course_info['Credit']),
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type': 'input',
                        'name': 'Section',
                        'message': 'Section:',
                        'default': str(course_info['Section']),
                        'validate': lambda text: len(text) > 0,
                    },
                    {
                        'type': 'list',
                        'name': 'Grade',
                        'message': 'Grade:',
                        'choices': [
                            'A',
                            'B+',
                            'B',
                            'C+',
                            'C',
                            'D+',
                            'D',
                            'F',
                        ],
                        'default': 5,
                    },
                ]

                update_course_answers = prompt(update_course_questions,
                                               style=custom_style_2)
                update_course_answers["Grade(Score)"] = self.grade_table[
                    update_course_answers['Grade']]  # Map Grade from score

                self.update_row_with_dict(
                    update_course_answers,
                    int(update_answers['course']))  # Update DB from answer

            elif main_menu_answers['todo'] == "Summary":
                # Show DB
                print(tabulate(self.db, headers='keys', tablefmt='psql'))

            elif main_menu_answers['todo'] == "Calculate GPA":

                year_semester = self.db[[
                    "Year", "Semester"
                ]]  # Select only Year and Semester coloumn
                year_semester = year_semester.drop_duplicates(
                )  # Drop the duplicate value
                # Get the unique Year and Semester pair
                year_ = [
                    "Year {} Semester {}".format(row[1]['Year'],
                                                 row[1]['Semester'])
                    for row in year_semester.iterrows()
                ]
                year_ = sorted(year_)

                select_term_questions = [{
                    'type': 'list',
                    'name': 'term',
                    'message': 'Which year and semester do you want?',
                    'choices': ['Total'] + year_
                }]

                select_term_answers = prompt(select_term_questions,
                                             style=custom_style_2)

                if select_term_answers['term'] == 'Total':
                    self.db = self.db.astype({'Credit': int
                                              })  # Cast credit column to int
                    # (After update mode will cause conflict!)
                    product_column = self.db['Grade(Score)'] * self.db[
                        'Credit']  # Calculate Product of Score and Credit
                    gpa = product_column.sum() / self.db['Credit'].sum(
                    )  # Calculate SumProduct / Sum of Credit
                    art.tprint("GPA = {}".format(
                        str(gpa)[:4]))  # Print the GPA
                else:

                    select_type_questions = [{
                        'type':
                        'list',
                        'name':
                        'type',
                        'message':
                        'Which type do you want?',
                        'choices': ['Cumulative', 'Semester']
                    }]

                    select_type_answer = prompt(select_type_questions,
                                                style=custom_style_2)

                    if select_type_answer['type'] == "Semester":
                        #  Calculate specific term
                        year_split = select_term_answers['term'].split(
                            " ")  # Extract the selected term
                        year = year_split[1]  # Get the year
                        semester = year_split[3]  # Get the semester
                        # Filter the db by given Year and Semester
                        db_filter = self.db[(self.db["Year"] == year) &
                                            (self.db["Semester"] == semester)]
                        db_filter = db_filter.astype(
                            {'Credit':
                             int})  # Cast credit column to int (same as above)
                        product_column = db_filter['Grade(Score)'] * db_filter[
                            'Credit']  # Calculate Product of Score and Credit
                        gpa = product_column.sum() / db_filter['Credit'].sum(
                        )  # Calculate SumProduct / Sum of Credit
                        art.tprint("GPA = {}".format(
                            str(gpa)[:4]))  # Print the GPA
                    else:
                        #  Calculate cumulative gpa
                        # Slice the list of year to only use semester
                        year_slice = year_[:year_.
                                           index(select_term_answers['term']) +
                                           1]
                        sum_product = 0
                        credit_sum = 0
                        for select in year_slice:
                            select_split = select.split(
                                " ")  # Extract the selected term
                            year_select = select_split[1]  # Get the year
                            semester_select = select_split[
                                3]  # Get the semester
                            # Filter the db by given Year and Semester
                            db_filter = self.db[
                                (self.db["Year"] == year_select)
                                & (self.db["Semester"] == semester_select)]
                            product_column = db_filter[
                                'Grade(Score)'] * db_filter[
                                    'Credit']  # Calculate Product of Score and Credit
                            sum_product += product_column.sum(
                            )  # Collect product
                            cretdit = db_filter['Credit'].sum(
                            )  # Calculate sum of credit
                            credit_sum += cretdit  # Collect credit
                        gpa = sum_product / credit_sum  # Calculate SumProduct / Sum of Credit
                        art.tprint("GPA = {}".format(
                            str(gpa)[:4]))  # Print the GPA

            main_menu_answers = prompt(
                main_menu_questions,
                style=custom_style_2)  # Loop the main menu question

        if main_menu_answers['todo'] == "Save and Close":
            # Save current state of db to csv and close
            print("Saving....")
            self.db.to_csv('GPA.csv', encoding='utf-8', index=False)
            print("Complete!")
            art.tprint("Goodbye")
        else:
            art.tprint("Goodbye")
示例#20
0

namecheap_questions = [{
    'type': 'input',
    'name': 'user',
    'qmark': ' 👤',
    'message': 'What\'s your Namecheap username?',
}, {
    'type': 'input',
    'name': 'key',
    'qmark': ' 🔑',
    'message': 'What\'s your Namecheap API key?',
    'validate': KeyValidator
}]

api_answer = prompt(api_question)
if api_answer['is_ok']:
    ip_answer = prompt(ip_question)
    if ip_answer['is_ok']:
        namecheap_answers = prompt(namecheap_questions)
        create_a_records(namecheap_answers['user'], namecheap_answers['key'])
    else:
        print(
            'To whitelist an IP, visit https://sway-me.xyz/wiki#namecheap#whitelist_ip'
        )
else:
    nlh = "\n - "
    nl = "\n"
    print(f'''You have selected the following services:
    {nl} - traefik{nlh}{nlh.join(services)}{nl}{nl}Please create an "A" Record for each service. You can do this later, 
but it is required.  Otherwise your services will be unreachable. If you are using namecheap, 
示例#21
0
def outputJson(jsonValue):
    global jsonData  #skipcq PYL-W0603
    jsonData = json.loads(jsonValue)
    options = []
    for i in jsonData.keys():
        options.append(i)
    print()
    questions = [{
        'type': 'list',
        'name': 'c1',
        'message': 'What do you want to check first ?',
        'choices': options
    }, {
        'type': 'list',
        'name': 'c2',
        'message': 'Which page do you want to review ?',
        'choices': getc2,
        'filter': filterc2,
        'when': shouldc2
    }, {
        'type': 'list',
        'name': 'c3',
        'message': 'Issues or Achievements?',
        'choices': ['Issues', 'Achievements'],
        'filter': filterc3
    }, {
        'type': 'list',
        'name': 'c4',
        'message': 'See them all at once or one by one',
        'choices': ['All at Once', 'One by One']
    }]
    answers = prompt(questions, style=style)
    k1 = 'warning'
    if (answers['c3'] == 'achieved'):
        k1 = 'achievement'

    if answers['c1'] == 'pages':
        li = jsonData[answers['c1']][answers['c2']][answers['c3']]
    else:
        li = jsonData[answers['c1']][answers['c3']]

    no = 0
    didBreak = False
    allAtOnce = False
    if answers['c4'] == 'All at Once':
        allAtOnce = True
    for i in li:
        no = no + 1
        ivalue = str(i['value'])
        message = "Point - " + str(
            no) + "\n Label : " + i[k1] + "\n Current : " + ivalue
        if allAtOnce is False:
            qn = [{
                'type': 'confirm',
                'name': 'forward',
                'message': message + '\n Go to next?',
                'default': True
            }]
            a = prompt(qn, style=style)
            if a['forward'] is False:
                didBreak = True
                break
        else:
            if no % 2 == 1:
                print(Fore.BLUE + Style.BRIGHT + message + "\n" +
                      Style.RESET_ALL)
            else:
                print(Fore.CYAN + Style.BRIGHT + message + "\n" +
                      Style.RESET_ALL)

    if didBreak is False and allAtOnce is False:
        print('List Ended')

    retry = [{
        'type': 'confirm',
        'name': 'again',
        'message': 'Do you want to check other things?',
        'default': True
    }]
    res = prompt(retry, style=style)
    if res['again'] is True:
        outputJson(jsonValue)
    else:
        saveFile = [{
            'type': 'confirm',
            'name': 'fileSave',
            'message': 'Do you want to save your analysis in a file?',
            'default': True
        }]
        isFileSaved = prompt(saveFile, style=style)
        if isFileSaved['fileSave'] is True:
            filename = str(jsonData['pages'][0]['url'] +
                           '_webedge_analysis.yaml')
            bad_chars = ['/', ':', '\\']
            for i in bad_chars:
                filename = filename.replace(i, '')
            with open(filename, 'w+') as f:
                f.write(
                    yaml.dump(yaml.safe_load(json.dumps(
                        json.loads(jsonValue)))))
            print(filename + " saved")

        print(
            Fore.GREEN + Style.BRIGHT +
            "=====================\nWebEdge Analysis Done\n====================="
            + Style.RESET_ALL)
示例#22
0
                                first=False)
entries_found_dic = {}
counter = 0
for entry in entries_found:
    entry_name = str(entries_found[counter]).\
        replace('Entry: "', '').\
        replace('"', '')
    entries_found_dic[entry_name] = entries_found[counter]
    counter += 1

entries_list_keys = list(entries_found_dic.keys())

questions = [
    {
        'type': 'list',
        'name': 'Entry',
        'message': 'This is what I found',
        'choices': entries_list_keys,
    },
]

answer = prompt(questions)
title = str(answer).replace("{'Entry': '", '').replace("'}", '')
pyperclip.copy(entries_found_dic[title].password)
print('URL: {}'.format(entries_found_dic[title].url))
colored_passwd = colored(entries_found_dic[title].password, 'white',
                         'on_white')
print('username: {}'.format(entries_found_dic[title].username))
print('Password: {}'.format(colored_passwd))
print('Password copied to clipboard')
示例#23
0
        elif case == 5:
            return data['sureness']
        else:
            return data

    def get_data(self, case, **kwargs):
        """
            case: getting different data from Player, depending on which step of the game?
            i.e., case = 0: What do you want to do? (claim, ask for card)
                  case = 1: If claim, which suit will you claim
                  case = 2: Given which suit, which players have which cards?
                  case = 3: If not claim, but ask for card, who will you ask?
                  case = 4: Which card will you ask for?
        """
        if case == 0:
            data = prompt(initialize_move_question, style=custom_style_3)
            return data

        elif case == 1:
            which_range_to_claim_question[0]["choices"] = kwargs["choices"]
            data = prompt(which_range_to_claim_question, style=custom_style_2)
            return data

        elif case == 2:
            # Get current list of candidate cards
            list_of_dicts = [{'name': i} for i in kwargs['choices']]

            # if a card has already been selected, disable it in the checkbox list
            if kwargs.get('selected', None) is not None:
                for i in range(len(kwargs['choices'])):
                    if list_of_dicts[i]['name'] in kwargs['selected']:
示例#24
0
def get_ngrok_id():
    spinner = Halo(text="Loading", spinner="dots")
    spinner.start()
    if not os.path.isfile(config_file):
        with open(config_file, "w+") as f:
            try:
                data = {}
                data["debug"] = (True, )
                data["entry_file"] = "main.py"
                data["ngrok_auth"] = "None"
                data["running_time"] = 2
                data["secret_key"] = "None"
                data["vncserver"] = False
                data["backup"] = False
                f.write(yaml.dump(data, default_flow_style=False))
            except Exception as e:
                print(f"{bcolors.FAIL}Error: {e}{bcolors.ENDC}")
                exit()

    with open(config_file) as f:
        try:
            data = yaml.load(f, Loader=yaml.FullLoader)
        except Exception as e:
            print(f"{bcolors.FAIL}Error: {e} {bcolors.ENDC}")
            exit()
    ques1 = [{
        "type":
        "input",
        "name":
        "ques1",
        "message":
        "Initial Setup: \n Please create ngrok account at https://ngrok.com and paste it here: ",
    }]
    ques2 = [{
        "type": "list",
        "name": "ques2",
        "message": "Select a option to continue",
        "choices": ["Continue with previous setup", "Reset ngrok id"],
    }]
    ques3 = [{
        "type": "list",
        "name": "ques3",
        "message": "Do you need VNC server? ",
        "choices": ["yes", "no"],
    }]

    ques4 = [{
        "type": "list",
        "name": "ques4",
        "message": "Do you want automatic backups to Google Drive? ",
        "choices": ["yes", "no"],
    }]

    spinner.succeed()
    if data["ngrok_auth"] == "None":
        ans = prompt(ques1)
        if len(ans["ques1"]) >= 10:
            data["ngrok_auth"] = ans["ques1"]
            data["secret_key"] = id_generator(10)
            ans = prompt(ques3)
            if ans["ques3"] == "yes":
                data["vncserver"] = True
            else:
                data["vncserver"] = False
            ans = prompt(ques4)
            if ans["ques4"] == "yes":
                data["backup"] = True
            else:
                data["backup"] = False
            with open(config_file, "w") as f:
                f.write(yaml.dump(data, default_flow_style=False))
                print(f"{bcolors.OKBLUE}Setup Complete{bcolors.ENDC}")
        else:
            print("[!] Invalid Input")
    else:
        ans = prompt(ques2)
        if ans["ques2"] == "Continue with previous setup":
            print(f"{bcolors.OKBLUE}Setup Complete{bcolors.ENDC}")
        else:
            data["ngrok_auth"] = "None"
            with open(config_file, "w") as f:
                f.write(yaml.dump(data, default_flow_style=False))
            get_ngrok_id()
示例#25
0
 def make_choice(self):
     from IHM.accueil import Accueil
     answers = prompt(questions)
     voiture_service.creer_voiture(answers['marque'], answers['prix'])
     return Accueil()
示例#26
0
        'when': lambda ans: ans.get('theme') == display_hist,
        'choices': get_fields_list()
    },
    {
        'type': 'input',
        'name': 'date_hist',
        'message': 'Введіть дату. (Рік-місяць-день)',
        'when': lambda ans: ans.get('hist'),
        'validate': validate_date_str
    }


]

while 1:
    answer = prompt(main_question, style=custom_style_2)

    if answer.get('theme') == display_graph \
        and answer.get('period') == all_period:
        fields = answer.get('fields', [])
        draw_graph(fields, 'all')
    elif answer.get('theme') == display_graph \
        and answer.get('period') == choose_period:
        fields = answer.get('fields', [])
        period = (answer.get('start_period'), answer.get('end_period'))
        years = answer.get('years', [])
        print(period, years)
        draw_graph(fields, period, years)
    elif answer.get('theme') == display_clean \
        and answer.get('clean_vis', []):
        draw_clean(answer.get('clean_vis'))
示例#27
0
def ask_bootstrap_questions():
    profile_names = list(profiles.read_names())
    current_profile_name = profiles.get_current_name(exit_if_not_set=False)

    if current_profile_name:
        def sort_current_profile_first(a=None, b=None):
            if a == current_profile_name:
                return -1
            if b == current_profile_name:
                return 1
            return 0
        profile_names.sort(key=sort_current_profile_first)

    puts('\n')
    answers = prompt([
        {
            'name': 'jobs',
            'type': 'checkbox',
            'message': 'What would you like to do?',
            'choices': [
                {
                    'name': 'Change shell to zsh',
                    'checked': True,
                },
                {
                    'name': 'Generate & link all dotfiles',
                    'checked': True,
                },
                {
                    'name': 'Install/upgrade brew packages',
                    'checked': True,
                },
                {
                    'name': 'Install/upgrade brew casks',
                    'checked': True,
                },
                {
                    'name': 'Install/upgrade gem rakes',
                    'checked': True,
                },
                {
                    'name': 'Install NVM',
                    'checked': True
                },
                {
                    'name': 'Install/update the powerlevel9k oh-my-zsh theme',
                    'checked': True,
                },
                {
                    'name': 'Sync git repositories',
                    'checked': True,
                },
                {
                    'name': 'Configure iterm2 and system settings',
                    'checked': False,
                },
                {
                    'name': 'Import GPG keys',
                    'checked': False,
                },
                {
                    'name': 'Install fonts',
                    'checked': False,
                },
                {
                    'name': 'Open non-casked app download pages',
                    'checked': False,
                },
            ],
            'filter': jobs_filter,
        },
        {
            'name': 'profile',
            'type': 'list',
            'message': 'Which profile should be used to setup this computer?',
            'choices': profile_names,
        },
    ])

    if 'jobs' not in answers or 'profile' not in answers:
        exit(1)

    puts('\n')
    return answers['jobs'], answers['profile']
def run_create_flow(session):
    """
    Command line interface questions for creating a new account.
    Asks details of account to create, adds account to vault locally and then updates vault in cloud.
    """
    questions = [
        {
            'type': 'input',
            'name': 'name',
            'message': 'What is the name of your new account?',
            'validate': validate_nonempty,
        },
        {
            'type': 'input',
            'name': 'username',
            'message': 'What is the username for your new account?',
            'validate': validate_nonempty,
        },
        {
            'type': 'list',
            'name': 'password_method',
            'message': 'How would you like to create your password?',
            'choices': [
                'Input password myself',
                'Generate a password for me',
            ]
        },
        {
            'type': 'password',
            'name': 'password',
            'message': 'What is the password?',
            'when': lambda answers: answers.get('password_method', '') ==
            'Input password myself',
            'validate': validate_nonempty,
        },
        {
            'type': 'password',
            'name': 'confirm_password',
            'message': 'Please confirm your password:'******'when': lambda answers: answers.get('password', False),
            'default': '',
        },
    ]

    answers = prompt(questions, style=custom_style)

    if len(answers) == 0:
        exit()

    if answers['password_method'] == 'Input password myself':
        if answers['password'] == answers['confirm_password']:
            print("Password confirmed.")
        else:
            print("Passwords do not match. Nothing will be created.")
            return
    elif answers['password_method'] == 'Generate a password for me':
        answers['password'] = run_generate_password_flow()

    if not session.account_exists(answers['name']):
        new_account = Account(answers['name'], answers['username'],
                              answers['password'])
        session.vault.append(new_account)
        print('Account created.')
        update_vault(session)
    else:
        print('An account already exists with this name in the vault.')
        print('Nothing created.')
示例#29
0
def get_answers():
    answers = prompt(questions)
    return answers
示例#30
0
fortune_teller_number = choice(range(len(fortune_tellers)))

print('Fortune Teller #{}'.format(fortune_teller_number + 1))

fortune_teller = fortune_tellers[fortune_teller_number]
pos_0 = fortune_teller[0]
pos_1 = fortune_teller[1]
pos_2 = fortune_teller[2]
pos = 0
print()

user_input = prompt(
    [
        {
            'type': 'list',
            'name': 'answer',
            'message': 'Choose an option:',
            'choices': pos_0,
        }
    ]
)['answer']

if represents_int(user_input):
    amount_to_move = int(user_input)
else:
    amount_to_move = len(user_input)

for _ in range(amount_to_move):
    pos += 1
    if pos == 3:
        pos = 1
print()
示例#31
0
            {
                'name':
                'Leon (6.8kтнРя╕П): Personal assistant. Easily add your own module.',
                'checked': True
            },
            {
                'name': 'Webdav: Generic webDAV server',
                'checked': True
            },
            {
                'name':
                'Home-Assistant (33kтнРя╕П): Manage smart home devices',
                'checked': True
            },
        ],
        'validate':
        lambda answer: 'You must choose at least one service.'
        if len(answer) == 0 else True
    },
]

initial_answer = prompt(initial_question)
if initial_answer['is_ok']:
    services_answers = prompt(services_questions)
    services = [
        service.split()[0].lower().rstrip(':')
        for _, category in services_answers.items() for service in category
    ]
    with open('.services.json', 'w') as out:
        out.write(json.dumps(services))
示例#32
0
from Utils import _print
from Utils import _search
from Utils import _questions

# File Path Variables
actionGroupFiles = []
dataFiles = []
metadataFiles = []
pageFiles = []
sectionFiles = []
testFiles = []

####   Ask the Questions   ####
###############################
## Ask the Starter Question ##
whatDoYouWantToDoAnswers = prompt(_questions.whatDoYouWantToDo)

# Branching logic based on the answer to the Starter Question.
if (whatDoYouWantToDoAnswers["user_action"] == "search"):
    whatAreYouSearchingForAnswers = prompt(_questions.whatAreYouSearchingFor)
    entityType = whatAreYouSearchingForAnswers["searching_for"]

    if (entityType == "action_group"):
        _print.askTheQuestionPrintTheAnswers(
            _questions.whichActionGroupAttributes, "action_group")
    elif (entityType == "data"):
        _print.askTheQuestionPrintTheAnswers(
            _questions.whichDataEntityAttributes, "data")
    elif (entityType == "metadata"):
        _print.askTheQuestionPrintTheAnswers(
            _questions.whichMetadataAttributes, "metadata")
def interactive():
    # ask for format
    fmt = prompt([{
        'type': 'list',
        'name': 'format',
        'message': 'Select meme format:',
        'choices': FMT_NAMES
    }])['format']

    panel_types_of_format = PANEL_TYPES[fmt]

    panels = []
    # cap and sep are rejected after woman/cat panel.
    reject_cap_and_sep = False
    loop = True
    # begin adding panels
    while loop:
        applicable_panel_types = (
            panel_types_of_format +
            (['caption', 'sep'] if not reject_cap_and_sep else []) + ['abort'])
        displayed_panel_types = [
            str(k) + ': ' + DESCRIPTIONS[fmt][k]
            for k in applicable_panel_types
        ]

        # ask for panel type
        panel_type = prompt([{
            'type': 'list',
            'name': 'type',
            'message': f'Select type for panel {len(panels) + 1}:',
            'choices': displayed_panel_types
        }])['type'].split(': ')[0]

        if panel_type == 'abort':
            break  # exit loop, proceed to panel editing

        if not panel_type == 'sep':
            # sep lines do not need text
            text = prompt([{
                'type':
                'input',
                'name':
                'text',
                'message':
                f'Text for panel {len(panels) + 1}: (leave blank to abort)',
            }])['text']
            if not text:
                continue  # return to panel type selection
        else:
            text = ''

        if panel_type in ('woman', 'cat') and not reject_cap_and_sep:
            # notify at first woman/cat panel addition
            print(
                color('Warning: after the addition of a woman or cat panel, \
captions and lines are no longer accepted.',
                      fgc=3))  # yellow
            reject_cap_and_sep = True

        panels.append([panel_type, text])
        print(panel_memory(panels, fmt))

        loop = prompt([{
            'type': 'confirm',
            'name': 'loop',
            'message': 'Add another panel?',
            'default': True
        }])['loop']

        if not loop and all([(p[0] in ('caption', 'sep')) for p in panels]):
            # no body panels added
            print(
                color(
                    'Error: cannot proceed until a real meme panel is added.',
                    fgc=1))  # red
            loop = True

    # select font
    cmdfont = prompt([{
        'type': 'list',
        'name': 'font',
        'message': 'Select font:',
        'choices': FONTS.keys()
    }])['font']

    # begin editing panels
    loop = True
    while loop:
        print('This is a list of panels you have added to your meme:')
        print(panel_memory(panels, fmt))
        preview = prompt([{
            'type': 'confirm',
            'name': 'preview',
            'message':
            'Display a preview of your meme? (Esc to close preview)',
            'default': True
        }])['preview']
        if preview:
            MEMETHESIZERS[fmt](fmt, panels, cmdfont=cmdfont).show()

        loop = prompt([{
            'type': 'confirm',
            'name': 'modify',
            'message': 'Any further modifications to make?',
            'default': False
        }])['modify']

        if loop:  # modify
            num = prompt([{
                'type':
                'input',
                'name':
                'num',
                'message':
                'Enter panel # to edit / remove / insert another panel after:',
                'validate':
                lambda s: (s.isdecimal() and (0 <= int(s) < len(panels) + 1)),
                'filter':
                lambda s: int(s)
            }])['num']

            if num == 0:
                prop_choices = ['Insert after']
            elif panels[num - 1][0] == 'sep':
                prop_choices = ['Insert after', 'Remove']
            else:
                prop_choices = [
                    'Edit text', 'Edit type', 'Insert after', 'Remove'
                ]

            prop = prompt([{
                'type': 'list',
                'name': 'prop',
                'message': 'Select how the panel should be modified:',
                'choices': prop_choices
            }])['prop']

            if prop == 'Edit text':
                panels[num - 1][1] = prompt([{
                    'type': 'input',
                    'name': 'text',
                    'message': f'Text for panel {num}:',
                    'default': panels[num - 1][1],
                    'validate': lambda s: bool(s)
                }])['text']
            elif prop == 'Edit type':
                panels[num - 1][0] = prompt([{
                    'type': 'list',
                    'name': 'type',
                    'message': f'Select type for panel {num}:',
                    'choices': displayed_panel_types
                    # NOTE: for womanyelling, cap and sep stay rejected
                }])['type'].split(': ')[0]
            elif prop == 'Insert after':
                applicable_panel_types = (
                    panel_types_of_format +
                    (['caption', 'sep'] if not reject_cap_and_sep else []) +
                    ['abort'])
                displayed_panel_types = [
                    str(k) + ': ' + DESCRIPTIONS[fmt][k]
                    for k in applicable_panel_types
                ]
                new_panel_confirmed = False
                while not new_panel_confirmed:
                    # ask for panel type
                    panel_type = prompt([{
                        'type': 'list',
                        'name': 'type',
                        'message': f'Select type for panel {num + 1}:',
                        'choices': displayed_panel_types
                    }])['type'].split(': ')[0]

                    if panel_type == 'abort':
                        break  # exit loop, proceed to panel editing

                    if not panel_type == 'sep':
                        # sep lines do not need text
                        text = prompt([{
                            'type':
                            'input',
                            'name':
                            'text',
                            'message':
                            f'Text for panel {num + 1}: (leave blank to abort)',
                        }])['text']
                        if not text:
                            # return to 'print current panels /
                            # ask if preview is needed' part
                            continue
                    else:
                        text = ''

                    panels = panels[:num] + [[panel_type, text]] + panels[num:]
                    print(panel_memory(panels, fmt))
                    new_panel_confirmed = True

            elif prop == 'Remove':
                # connect two splices of `panels` before and after (num - 1)
                panels = panels[:(num - 1)] + panels[num:]

    # all panels recorded
    # begin memethesizing
    o = prompt([{
        'type': 'input',
        'name': 'saveto',
        'message': f'Save meme to: (only .jpg and .png supported)',
        'validate': lambda s: bool(s)
    }])['saveto']

    path = ((o if re.search('\.(jpe?g|png)$', o, flags=re.I) else o +
             '.jpg') if o else 'meme.jpg')

    MEMETHESIZERS[fmt](fmt, panels, cmdfont=cmdfont).save(path)

    print(color(f'Meme saved to {path}.', fgc=2))
示例#34
0
def main():
    """
    Prompt the user to enter all the necessary
    attributes to encrypt/decrypt a directory.
    """

    # Set a custom style of the UI.
    # This is just settings visual color parameters
    # using html color codes.
    style = style_from_dict({
        Token.Separator: "#cc5454",
        Token.QuestionMark: "#673ab7 bold",
        Token.Selected: "#cc5454",
        Token.Pointer: "#673ab7 bold",
        Token.Instruction: "",
        Token.Answer: "#ff6600 bold",
        Token.Question: "",
    })

    # File extensions to use as options to the user.
    file_exts = [".txt", ".pdf", ".docx", ".png"]
    # Format each items to be compatible with PyInquirer, dict-comprehension.
    file_exts = [{"name": i} for i in file_exts]
    # Select the first entry as a default.
    file_exts[0]["checked"] = True

    # dict translating answers to functions.
    operations = {"Encrypt": encrypt, "Decrypt": decrypt}

    # Create and format the questions.
    questions = [
        {
            "type": "input",
            "name": "key_filename",
            "message": "Enter key filename (Blank to generate a new one):",
            "validate": FileValidator,
        },
        {
            "type": "input",
            "name": "folder",
            "message": "Enter folder to encrypt/decrypt:",
            "validate": FolderValidator,
        },
        {
            "type": "list",
            "name": "operation",
            "message": "What do you want to do?",
            "choices": ["Encrypt", "Decrypt"],
        },
        {
            "type": "checkbox",
            "name": "file_ext",
            "message": "Which file's do you want to encrypt/decrypt?",
            "choices": file_exts,
        },
    ]

    print(
        "This script encrypts and decrypts files in bulk based on extension.")
    print("Use the same key to decrypt as you use to encrypt.")

    # Prompt the user to answer the previously created questions.
    answers = prompt(questions, style=style)

    # Gen a new key if one is not specified
    if not answers["key_filename"]:
        key = generate_key()
    else:
        key = read_key(answers["key_filename"])

    # Grab the right function based on the user input.
    func = operations[answers["operation"]]
    for i in answers["file_ext"]:
        # Call the appropiate function.
        func(answers["folder"], key, i)

    print("Done.")
示例#35
0
    Token.Instruction: '',  # default
    Token.Answer: '#5F819D bold',
    Token.Question: '',
})

questions = [{
    'type':
    'rawlist',
    'name':
    'theme',
    'message':
    'What do you want to do?',
    'choices': [
        'Order a pizza', 'Make a reservation',
        Separator(), 'Ask opening hours', 'Talk to the receptionist'
    ]
}, {
    'type':
    'rawlist',
    'name':
    'size',
    'message':
    'What size do you need',
    'choices': ['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
    'filter':
    lambda val: val.lower()
}]

answers = prompt(questions, style=style)
print_json(answers)
示例#36
0
                with open(TEMPLATE_PATH.joinpath("default.gitignore"),
                          "r") as default_gitignore:
                    contents.extend(default_gitignore.readlines())

            contents.extend(["\n"] + language_gitignore.readlines())
            output_gitignore.writelines(
                [c if c.endswith('\n') else f'{c}\n' for c in contents])
    except FileNotFoundError:
        print(
            f"'{language}' is as a valid option, but no corresponing .gitignore could be located for it. Did you remember to create one?"
        )


if __name__ == "__main__":
    if len(argv) == 1:
        responses = prompt(questions)
        if responses.get('_language'):
            build_gitignore(**responses)
    else:
        user_choice = " ".join(argv[1:]).strip().lower()
        if user_choice in VALID_CHOICES:
            build_gitignore(user_choice)
        else:
            print(
                f"No .gitignore template exists for '{user_choice}'! Did you misspell something?\n",
                "Current options:",
                "".join(
                    sorted([
                        f"  • {p}\n"
                        for p in TEMPLATE_PATH.rglob('*.gitignore')
                    ])),