Ejemplo n.º 1
0
def single_prompt(
    prompt: str,
    validation: Optional[Callable] = lambda _, x: True,
    default: Optional[Any] = None,
) -> Any:
    """
    Prompt user for an answer to a question
    """
    return inquirer.prompt(
        [inquirer.Text("question", prompt, default, validate=validation)],
        theme=GreenPassion(),
    )["question"]
Ejemplo n.º 2
0
def get_chosen_tags(toggl_wrapper: TogglWrapper,
                    chosen_project: str) -> List[str]:
    tags_names = [ANY_TAG]
    tags_names.extend(x.name for x in toggl_wrapper.get_all_tags())
    questions = [
        inquirer.Checkbox(
            "tags",
            message=f"What tags to track for {chosen_project}?",
            choices=tags_names,
        )
    ]
    answers = inquirer.prompt(questions, theme=GreenPassion())
    return answers["tags"]
Ejemplo n.º 3
0
def game():
    print('Vamos a jugar: "Piedra, papel o tijeras"')
    pc_select = random.choice(['piedra', 'papel', 'tijeras'])
    question = [
        inquirer.List(
            'eleccion',
            message="Priedra, papel o tijeras?",
            choices=['piedra', 'papel', 'tijeras'],
        ),
    ]
    player_select = inquirer.prompt(question, theme=GreenPassion())

    return (player_select['eleccion'], pc_select)
Ejemplo n.º 4
0
def get_operation():
    operations = [('List VMs', 'list'), ('Change power state of VM', 'power'),
                  ('Delete a VM', 'delete'), ('Clone a VM', 'clone'),
                  ('Exit', 'exit')]
    questions = [
        List('operation',
             message='Select an operation',
             choices=operations,
             carousel=True)
    ]

    answers = prompt(questions, theme=GreenPassion())
    return answers
Ejemplo n.º 5
0
 def get_user_source(self):
     """"function for picking the news source from the user"""
     questions = [
         inquirer.List(
             'sources',
             message=
             "From which news source would you like to acquire your headlines?",
             choices=['nbc-news', 'cnbc', 'bbc-news', 'cnn'],
         ),
     ]
     """theme adds a green background to the items in the list"""
     answers = inquirer.prompt(questions, theme=GreenPassion())
     print("News Source : ", answers['sources'])
     self.mynewssource = answers['sources']
     return self.mynewssource
Ejemplo n.º 6
0
def get_chosen_projects(toggl_wrapper: TogglWrapper) -> List[str]:
    projects_names = [x.name for x in toggl_wrapper.get_all_projects()]
    while True:
        questions = [
            inquirer.Checkbox(
                "projects",
                message="Which projects to track?",
                choices=projects_names,
            ),
        ]
        answers = inquirer.prompt(questions, theme=GreenPassion())
        projects_chosen = answers["projects"]
        if len(projects_chosen) != 0:
            return projects_chosen
        print("You have to pick at least one project.")
Ejemplo n.º 7
0
def firstTimeSetUp():
    """
    Generate a user config file for first-time setup
    """
    print("No user config found. Running first time setup")

    questions = [
        inquirer.Path(
            name="rootLocation",
            message=
            "Where would you like canvas sync's root store location to be? (Absolute Paths Please)",
            normalize_to_absolute_path=True)
    ]

    answers = inquirer.prompt(questions, theme=GreenPassion())

    if not path.exists(filePath := answers["rootLocation"]):
Ejemplo n.º 8
0
def get_filtered_options(options):
    print(f"{Colors.OKBLUE}Config loaded successfully!{Colors.ENDC}")
    settings = [setting["key"] for setting in options]

    questions = [
        inquirer.Checkbox('interests',
                          message="What are you interested in?",
                          choices=settings),
    ]
    answers = inquirer.prompt(questions, theme=GreenPassion())
    if answers is None:
        answers = {
            "interests": []
        }

    return [setting for setting in options
            if setting["key"] in answers["interests"]]
Ejemplo n.º 9
0
def mainMenue() -> int:
    questions = [
        inquirer.List(
            name="Menue Select",
            message="I want to:",
            choices=["1) Select courses/files to be tracked", "2) Exit"])
    ]

    answer = inquirer.prompt(questions, theme=GreenPassion())["Menue Select"]

    if "1" in answer:
        editTracking()
        return 1

    if "2" in answer:
        print("Bye!")
        return 0
Ejemplo n.º 10
0
def get_credentials():
    questions = []
    answers = []

    if not Config.PC_HOST:
        questions.append(
            Text(name='pc_host',
                 message='IP address or host name of Prism Element',
                 validate=input_required))
    else:
        answers.append({'pc_host': Config.PC_HOST})

    if not Config.PC_PORT:
        questions.append(
            Text(name='pc_port',
                 message='HTTPS port for Prism Element',
                 default='9440',
                 validate=input_required))
    else:
        answers.append({'pc_port': Config.PC_PORT})

    if not Config.USERNAME:
        questions.append(
            Text(name='username',
                 message='Prism Element username',
                 validate=input_required))
    else:
        answers.append({'username': Config.USERNAME})

    if not Config.PASSWORD:
        questions.append(
            Password(name='password',
                     message='Password for Prism Element',
                     validate=input_required))
    else:
        answers.append({'password': Config.PASSWORD})

    answers.append(prompt(questions, theme=GreenPassion()))
    cred = {}
    for answer in answers:
        for key, value in answer.items():
            cred[key] = value

    return cred
Ejemplo n.º 11
0
async def find_ctf_url(name):
    
    ctf_list = await get_ctf_list()
    
    ctfs = []
    
    name.replace(" ","")
    for event in ctf_list.keys():
        ev = event
        event  = re.sub(" ","",event)
        if name.lower() in event.lower():  
            ctfs.append((ev,ctf_list[ev]))   
    if not ctfs:
        print("No match found :(")
        return
    
    ques = [ inquirer.List('event',message="Choose event", choices= ctfs) ]
    ans = inquirer.prompt(ques,theme=GreenPassion())
    
    url = "https://ctftime.org" + ans['event'] + "/tasks/"
    return url
Ejemplo n.º 12
0
def run():
    mile_in_km = 1.609344
    question = [
        inquirer.List(
            'convert',
            message="Priedra, papel o tijeras?",
            choices=['km a millas', 'millas a kilometros'],
        ),
    ]
    convertion = inquirer.prompt(question, theme=GreenPassion())

    if convertion["convert"] == "km a millas":
        meassure = float(input('Ingresa los kilometros a convertir: '))
        print(
            f"{meassure} kilometros equivale a: {round(meassure/mile_in_km, 3)} millas"
        )
    else:
        meassure = float(input('Ingresa las millas a convertir: '))
        print(
            f"{meassure} millas equivale a: {round(meassure * mile_in_km, 3)} kilometros"
        )
Ejemplo n.º 13
0
def play_music(audio_file):
    #this part of the script plays the song or any audio that the user selects
    pygame.mixer.init()
    mixer.music.load(audio_file)
    mixer.music.play()
    active = True
    while active:
        print(f"Currently playing {audio_file}")
        questions = [
            inquirer.Checkbox("p,u,q",
                              message="Do you want to pause or unpause",
                              choices=['Pause', 'Unpause', 'Quit'])
        ]
        answers = inquirer.prompt(questions, theme=GreenPassion())
        for keys, values in answers.items():
            temps = (keys, values)
            listodict = temps
            listtostring = ' '.join(map(str, temps))
            finalstrings = listtostring[5:].strip()
            stringtolist = ast.literal_eval(finalstrings)
            if len(stringtolist) == 1:
                if "Pause" in stringtolist:
                    mixer.music.pause()
                    clear_terminal()
                elif "Unpause" in stringtolist:
                    mixer.music.unpause()
                    clear_terminal()
                elif "Quit" in stringtolist:
                    print(f"Thank you for using the program")
                    os.system("unlink .test.wav")
                    active = False
                    sys.exit()
                else:
                    print(f"We did not find the commad")
            elif len(stringtolist) > 1:
                print(f"We can only take upto one choice")
            else:
                print(f"We did not recognize the command")
    return
Ejemplo n.º 14
0
def main():
    q = [
        inquirer.Checkbox("Music Files",
                          message="Select Music files that you want to play",
                          choices=files)
    ]
    answers = inquirer.prompt(q, theme=GreenPassion())
    for key, value in answers.items():
        temp = (key, value)
        DictToList = temp
    listToString = ' '.join(map(str, temp))
    finalString = listToString[12:]
    stringToList = ast.literal_eval(finalString)
    if len(stringToList) >= 2:
        for songs in stringToList:
            changing_dir(stringToList)
            if songs.endswith(".mp3"):
                Convert(songs)
                play_music(".test.wav")
                os.system("unlink .test.wav")
            else:
                changing_dir(songs)
                play_music(songs)
    elif len(stringToList) == 1:
        single_audio = ' '.join(map(str, stringToList))
        changing_dir(single_audio)
        if single_audio.endswith(".mp3"):
            Convert(single_audio)
            play_music(".test.wav")
            os.system("unlink .test.wav")
        elif single_audio.endswith(".wav"):
            play_music(single_audio)
        else:
            print(f"We dont support the extension {single_audio.endwith}")
            sys.exit()
    else:
        print("Something went wrong")
    return
Ejemplo n.º 15
0

# assign max_length from config
print(f'{bcolors.WARNING}\nThe maximum password length is ' +
      config_rules['max_length'] + ' characters.')
print(f'This can be altered in the config file.\n{bcolors.ENDC}')

# prompts for desired password complexity
options = [
    inquirer.Text('password_length', message='Password Length'),
    inquirer.Checkbox('character_categories',
                      message='Character Categories',
                      choices=['Uppercase', 'Lowercase', 'Numbers', 'Symbols'])
]

selected_options = inquirer.prompt(options, theme=GreenPassion())

password_length = selected_options["password_length"]
character_categories = selected_options["character_categories"]

selected_characters = ''
for i in character_categories:
    if i == 'Uppercase':
        selected_characters = selected_characters + string.ascii_uppercase
    elif i == 'Lowercase':
        selected_characters = selected_characters + string.ascii_lowercase
    elif i == 'Numbers':
        selected_characters = selected_characters + string.digits
    elif i == 'Symbols':
        selected_characters = selected_characters + string.punctuation
Ejemplo n.º 16
0
		validate=lambda _, x: re.match(r"([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)", x),
	),
	inquirer.Text('phone', message="What's your phone number",
		validate=lambda _, x: re.match(r"^[0][1-9]\d{9}$|^[1-9]\d{9}$", x),
	),
	inquirer.List('stream',
		message="Which stream do you belong to?",
		choices=['CS/BS', 'Computer', 'IT', 'ENTC', 'Electronics', 'Electrical', 'Mechanical', 'Civil', 'Chemical', 'Production'],
	),
	inquirer.List('year',
		message="Which year are you in?",
		choices=["First Year", "Second Year", "Third Year", "Fourth Year"],
	)
]

personalAnswers = inquirer.prompt(personalQuestions, theme=GreenPassion())

print("\n\nPlease join our community at https://bit.ly/dscbvppune\n\n")
fun(f)
clear()
print(f.renderText('DSC BVP Pune'))
print(f.renderText("Teams"))

domainRelatedQuestions = [
	inquirer.Checkbox('domains',
		message="Select the domains you would like to be a part of (Press space to select, enter to submit)",
		choices=['Technical Team', 'Designing Team', 'Content Team', 'Management and Publicity Team'],
	),
]

domainChoiceAnswers = inquirer.prompt(domainRelatedQuestions, theme=GreenPassion())
Ejemplo n.º 17
0
def menu_list(items: dict, label: str = "Questions"):
    menu_items = items
    choices = [menu_items[value] for value in menu_items]
    questions = (inquirer.List(label, choices=choices), )
    answers = inquirer.prompt(questions, theme=GreenPassion())
    return answers[label]
Ejemplo n.º 18
0
def confirm_overlap(x, fragments, viewer=None):
    """Show dialogs to confirm overlapping fragments."""
    print('{}: {} overlapping fragments found'.format(x.name, len(fragments)))
    if fragments:
        fragments.sort_values('n_nodes')
        # Have user inspect fragments
        # Show larger fragments in 3d viewer
        if any(fragments.n_nodes > 10):
            # Generate a summary
            large_frags = fragments[fragments.n_nodes > 10]
            s = large_frags.summary(add_props=['overlap_score', 'id'])[[
                'name', 'id', 'n_nodes', 'n_connectors', 'overlap_score'
            ]]
            # Show and let user decide which ones to merge
            if not viewer:
                viewer = navis.Viewer(title='Check overlap')
            # Make sure viewer is actually visible and cleared
            viewer.show()
            viewer.clear()
            # Add original skeleton
            viewer.add(x, color='w')
            viewer.add(large_frags)
            viewer.picking = True
            viewer._picking_text.visible = True
            viewer.show_legend = True

            # Print summary
            print('Large (>10 nodes) overlapping fragments:')
            print(s.to_string(index=False, show_dimensions=False))

            msg = """
            Please check these large fragments for overlap and deselect
            neurons that you DO NOT want to have merged by clicking on
            their names in the legend.
            Hit ENTER when you are ready to proceed or CTRL-C to cancel.
            """

            try:
                _ = input(msg)
            except KeyboardInterrupt:
                raise KeyboardInterrupt('Merge process aborted by user.')
            except BaseException:
                raise

            # Remove deselected fragments
            # Mind you not all fragments are on viewer - this is why we remove
            # neurons that has been hidden
            fragments = fragments[~np.isin(fragments.id, viewer.invisible)]

    # Now ask for smaller fragments via CLI
    if fragments:
        s = fragments.summary(
            add_props=['overlap_score', 'sampler_count', 'id'])[[
                'name', 'id', 'n_nodes', 'n_connectors', 'sampler_count',
                'overlap_score'
            ]]

        # Ask user which neuron should be merged
        msg = """
        Please check the fragments that potentially overlap with the input neuron (white).
        Deselect those that should NOT be merged using the arrows keys.
        Hit ENTER when you are ready to proceed or CTRL-C to abort
        """
        print(msg)

        msg = s.to_string(index=False).split('\n')[0]

        s_str = s.to_string(index=False, show_dimensions=False, header=False)
        choices = [(v, i) for i, v in enumerate(s_str.split('\n'))]
        q = [
            inquirer.Checkbox(name='selection',
                              message=msg,
                              choices=choices,
                              default=list(range(len(choices))))
        ]

        # Ask the question
        selection = inquirer.prompt(q, theme=GreenPassion()).get('selection')

        if isinstance(selection, type(None)):
            raise SystemExit('Merge process aborted by user.')

        # Remove fragments that are not selected
        if selection:
            fragments = fragments[selection]
        else:
            # If no selection, remove all neurons from the list
            fragments = fragments[:0]

    # If no overlapping fragments (either none from the start or all removed
    # during filtering) ask if just proceed with upload
    if not fragments:
        print('No overlapping fragments to be merged into in target instance.')
        msg = 'Proceed with just uploading this neuron?'
        q = [inquirer.Confirm(name='confirm', message=msg)]
        confirm = inquirer.prompt(q, theme=GreenPassion()).get('confirm')

        if not confirm:
            raise SystemExit('Merge process aborted by user.')

        base_neuron = None
    # If any fragments left, ask for base neuron
    else:
        # Ask user which neuron to use as merge target
        s = fragments.summary(
            add_props=['overlap_score', 'sampler_count', 'id'])[[
                'name', 'id', 'n_nodes', 'n_connectors', 'sampler_count',
                'overlap_score'
            ]]

        msg = """
        Above fragments and your input neuron will be merged into a single neuron.
        All annotations will be preserved but only the neuron used as merge target
        will keep its name and skeleton ID.
        Please select the neuron you would like to use as merge target!
        """ + s.to_string(index=False).split('\n')[0]
        print(msg)

        s_str = s.to_string(index=False, show_dimensions=False, header=False)
        choices = [(v, i) for i, v in enumerate(s_str.split('\n'))]
        q = [
            inquirer.List(name='base_neuron',
                          message='Choose merge target',
                          choices=choices)
        ]
        # Ask the question
        bn = inquirer.prompt(q, theme=GreenPassion()).get('base_neuron')

        if isinstance(bn, type(None)):
            raise ValueError("Merge aborted by user")

        base_neuron = fragments[bn]

        # Some safeguards:
        # Check if we would delete any samplers
        cond1 = s.id != base_neuron.id
        cond2 = s.sampler_count > 0
        has_sampler = s[cond1 & cond2]
        if not has_sampler.empty:
            print("Merging selected fragments would delete reconstruction "
                  "samplers on the following neurons:")
            print(has_sampler)
            q = [inquirer.Confirm(name='confirm', message='Proceed anyway?')]
            confirm = inquirer.prompt(q, theme=GreenPassion())['confirm']

            if not confirm:
                raise SystemExit('Merge process aborted by user.')

        # Check if we would generate any 2-soma neurons
        has_soma = [not isinstance(s, type(None)) for s in fragments.soma]
        if sum(has_soma) > 1:
            print('Merging the selected fragments would generate a neuron  '
                  'with two somas!')
            q = [inquirer.Confirm(name='confirm', message='Proceed anyway?')]
            confirm = inquirer.prompt(q, theme=GreenPassion())['confirm']

            if not confirm:
                raise SystemExit('Merge process aborted by user.')

    return fragments, base_neuron
Ejemplo n.º 19
0
def extractfrom(file, target):
    sourceMIZ = MIZFile(file, True)
    mission = sourceMIZ.getMission()

    groups = []
    for coalition_idx, coalition in mission["coalition"].items():
        if coalition_idx != 'blue':
            continue
        for country_idx, country in coalition["country"].items():
            for unittype in ["plane"]:
                if not unittype in country:
                    continue
                for group_idx, group in country[unittype]["group"].items():
                    if (len(group["units"]) > 0) and (list(
                            group["units"].values())[0]["skill"] == "Client"):
                        groups.append(group["name"])

    flightquestion = [
        inquirer.Text(name='mission', message='Mission name', default=file),
        inquirer.Text(name='creator',
                      message='MDC creator',
                      default=os.getenv('username')),
        inquirer.Text(name='date',
                      message='MDC date',
                      default=datetime.today().strftime('%Y-%m-%d')),
        inquirer.List(
            name='flight',
            message="Flight to export waypoints from",
            choices=groups,
        ),
        inquirer.Text(name='alow', message='ALOW: alow'),
        inquirer.Text(name='msl_floor', message='ALOW: msl floor'),
        inquirer.Text(name='bingo', message='Bingo')
    ]
    flightanswer = inquirer.prompt(flightquestion, theme=GreenPassion())

    exportflight = None
    for coalition_idx, coalition in mission["coalition"].items():
        if coalition_idx != 'blue':
            continue
        for country_idx, country in coalition["country"].items():
            for unittype in ["plane"]:
                if not unittype in country:
                    continue
                for group_idx, group in country[unittype]["group"].items():
                    if group["name"] == flightanswer['flight']:
                        exportflight = group

    exportjson = {}
    exportjson['mission'] = flightanswer['mission']
    exportjson['creator'] = flightanswer['creator']
    exportjson['date'] = flightanswer['date']
    exportjson['data'] = {}
    exportjson['data']['waypoints'] = {}
    exportjson['data']['alow'] = {}
    if not hasattr(
            flightanswer, 'alow'
    ) and flightanswer['alow'] != None and flightanswer['alow'] != "":
        exportjson['data']['alow']['alow'] = flightanswer['alow']
    if not hasattr(flightanswer, 'msl_floor') and flightanswer[
            'msl_floor'] != None and flightanswer['msl_floor'] != "":
        exportjson['data']['alow']['msl_floor'] = flightanswer['msl_floor']
    if not hasattr(
            flightanswer, 'bingo'
    ) and flightanswer['bingo'] != None and flightanswer['bingo'] != "":
        exportjson['data']['bingo'] = flightanswer['bingo']

    for waypoint_idx, waypoint in group["route"]["points"].items():
        lat, lon = sourceMIZ.getProjectedLatLon(waypoint['x'], waypoint['y'])
        lat_d = math.floor(lat)
        lat_m = round(lat % 1 * 60 * 1000)
        lon_d = math.floor(lon)
        lon_m = round(lon % 1 * 60 * 1000)
        exportjson['data']['waypoints'][waypoint_idx] = {}
        exportjson['data']['waypoints'][waypoint_idx]['ns'] = ('s',
                                                               'n')[lat_d >= 0]
        exportjson['data']['waypoints'][waypoint_idx]['lat_d'] = abs(lat_d)
        exportjson['data']['waypoints'][waypoint_idx]['lat_m'] = lat_m
        exportjson['data']['waypoints'][waypoint_idx]['we'] = ('w',
                                                               'e')[lat_d >= 0]
        exportjson['data']['waypoints'][waypoint_idx]['lon_d'] = abs(lon_d)
        exportjson['data']['waypoints'][waypoint_idx]['lon_m'] = lon_m
        exportjson['data']['waypoints'][waypoint_idx]['altitude'] = math.floor(
            waypoint['alt'] * 3.28084)

    with open(target, 'w') as outfile:
        json.dump(exportjson, outfile)
Ejemplo n.º 20
0
from typing import Any, Dict, List, Optional, Set, Tuple
from . import training

parent_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '../'))

# Use the env var path or ../yuri-data
ROOT_PATH = os.environ.get('YURI_ROOT_PATH',
                           os.path.join(parent_path, 'yuri-data'))
DEFAULT_DATA_FILE = os.path.join(ROOT_PATH, 'slack_channel_data/data.json')
DEFAULT_MODEL_DIR = os.path.join(ROOT_PATH, 'slack_channel_model')
DEFAULT_BATCH_SIZE = 10
DIRECTION_NEWER = True
DIRECTION_OLDER = False
IGNORE_LABEL = 'ignore'
CREATE_LABEL = '+add new'
INQUIRER_RENDER = ConsoleRender(theme=GreenPassion())


def get_client(token: str,
               session: Optional[Session] = None) -> slacker.Slacker:
    if not token:
        raise Exception(f'No token was provided')
    if not token.startswith('xoxp-'):
        raise Exception(
            f'The provided token is invalid since it not a user token, please use a user token instead'
        )
    return slacker.Slacker(token, session=session)


def get_channel_id(token: str,
                   name: str,
Ejemplo n.º 21
0
import inquirer
from inquirer.themes import GreenPassion


q = [
    inquirer.Text("name", message="Whats your name?", default="No one"),
    inquirer.List("jon", message="Does Jon Snow know?", choices=["yes", "no"], default="no"),
    inquirer.Checkbox(
        "kill_list", message="Who you want to kill?", choices=["Cersei", "Littlefinger", "The Mountain"]
    ),
]

inquirer.prompt(q, theme=GreenPassion())
Ejemplo n.º 22
0
def handleGET():
    global upload_contents, cmd_contents, waiting, pastcmds
    try:
        if waiting == True:
            waiting = False
            time.sleep(.1)
            ret(.1)
        prompt = craft_prompt(request.headers, request.remote_addr)
        cmd = input(prompt)
        if cmd or not cmd.startswith('#'):
            pastcmds.append(cmd)
            if history_cmd.match(cmd) and pastcmds:
                pastcmds.pop()
                if os.name != 'nt':
                    q = [
                        inquirer.List('past_cmd',
                                      message='Command history',
                                      choices=pastcmds,
                                      default=pastcmds[-1]),
                    ]
                    cmd = inquirer.prompt(q, theme=GreenPassion())['past_cmd']
                    pastcmds.append(cmd)
                else:
                    print(
                        f"{B}ERROR:{RA} The history command currently doesn't work on Windows systems..."
                    )
                    return emptyresponse
            if unix_path.match(cmd):
                return redirect(
                    url_for('download',
                            filepath=benc(
                                unix_path.search(cmd).group(1).encode())))
            elif unix_upld.match(cmd):
                filepath = cmd.split()[1]
                if valid_file(filepath):
                    file_name = unix_upld.search(cmd).group(2).encode()
                    with open(filepath, 'rb') as f:
                        upload_contents = benc(f.read())
                    return redirect(url_for('upload', filename=file_name))
                else:
                    abort(404)
            elif wind_path.match(cmd):
                return redirect(
                    url_for('download',
                            filepath=benc(
                                wind_path.search(cmd).group(1).encode())))
            elif wind_upld.match(cmd):
                filepath = cmd.split()[1]
                if valid_file(filepath):
                    file_name = wind_upld.search(cmd).group(2).encode()
                    with open(filepath, 'rb') as f:
                        upload_contents = benc(f.read())
                    return redirect(url_for('upload', filename=file_name))
                else:
                    abort(404)
            elif clear_cmd.match(cmd):
                os.system('cls') if os.name == 'nt' else os.system('clear')
                return emptyresponse
            elif show_shellcodes.match(cmd):
                reload(utils)
                if utils.shellcodes[1][0]:
                    for k, v in utils.shellcodes.items():
                        print(f"{B+str(k)+RA} => {v[0]}")
                else:
                    print(f"[{B}ERROR{RA}] There are no shellcodes available.")
                return emptyresponse
            elif set_shellcode.match(cmd):
                shc_id = int(set_shellcode.search(cmd).group(1))
                reload(utils)
                try:
                    if utils.shellcodes[shc_id][0]:
                        return redirect(url_for('setshellcode', shc_id=shc_id))
                    else:
                        print(f"[x] There is no shellcode with id: {shc_id}")
                        return emptyresponse
                except KeyError:
                    print(f"[x] There is no shellcode with id: {shc_id}")
                    return emptyresponse
            elif help_cmd.match(cmd):
                print(tabulate(commands, headers=["Command", "Description"]))
                return emptyresponse
            elif exit_cmd.match(cmd):
                cmd_contents = cmd
                waiting = True
                startloading()
                return redirect(url_for('commander'))
            else:
                cmd_contents = cmd
                return redirect(url_for('commander'))
        else:
            return emptyresponse
    except EOFError:
        abort(404)
Ejemplo n.º 23
0
def select_vm_delete(vms):
    answers = select_vm(vms, 'Select a VM to delete')
    questions = [Confirm('confirm', message="Should I continue")]

    answers.update(prompt(questions, theme=GreenPassion()))
    return answers
Ejemplo n.º 24
0
    def build_menu(self):

        # find dates of menu days from the starting date
        if self.start_date is not None:
            start_date = ciso8601.parse_datetime(self.start_date)
        else:
            today = datetime.date.today()
            # if start_date is not defined we set it to next Monday
            next_monday_date = today + datetime.timedelta(days=-today.weekday(), weeks=1)
            start_date = next_monday_date
            self.start_date = start_date
        start_weekday = start_date.weekday()

        weekday_meals_d = self.config[0]['weekdays']
        weekdays = list(weekday_meals_d.keys())
        date_weekday_d = {}
        menu_date = start_date
        menu_weekday = start_weekday
        for i in range(self.days):
            date_weekday_d[menu_date] = weekdays[menu_weekday]
            menu_date += datetime.timedelta(days=1)
            menu_weekday = menu_date.weekday()

        # find index of recipe in day, meal and with groups
        for menu_date, menu_weekday in date_weekday_d.items():
            for meal, groups in weekday_meals_d[menu_weekday].items():
                # select the recipe with the oldest last date
                idx = self._select_recipe_index(meal, groups)
                # create entry for the menu DataFrame
                meal_time = datetime.time(*[int(i)for i in self.config[0][meal].split(':')])
                t = datetime.datetime.combine(menu_date, meal_time)
                d = {"day": menu_weekday,
                     "date": t.strftime("%Y-%m-%d %H:%M:%S"),
                     "meal": meal,
                     "recipe": self.recipes.at[idx, "recipe"],
                     "ingredients": self.recipes.at[idx, "ingredients"],
                     "notes": self.recipes.at[idx, 'notes'],
                     "recipe_id": int(idx)}

                # update provisional new date
                self.recipes.at[idx, 'new_date'] = t
                # add recipe to menu
                self.menu = self.menu.append(d, ignore_index=True)

        # previous_update_idx = None
        update_idx = self._verify_menu()
        while update_idx != "break":
            question = [
                inquirer.List('group',
                              message=f"Select new recipe",
                              choices=list(self.recipes.sort_values(by=['new_date'])['recipe'].values)
                              ),
            ]
            print()
            answer = inquirer.prompt(question, theme=GreenPassion())['group']
            idx = self.recipes[self.recipes['recipe'] == answer].index[0]
            old_recipe_idx = self.menu.at[update_idx, 'recipe_id']
            # and update the menu with the selected recipe
            self.menu.at[update_idx, 'recipe'] = answer
            self.menu.at[update_idx, 'recipe_id'] = idx
            self.menu.at[update_idx, 'ingredients'] = self.recipes.at[idx, 'ingredients']
            # we assign the menu date to the selected recipe
            self.recipes.at[idx, 'new_date'] = self.recipes.at[old_recipe_idx, 'new_date']
            # and restore the previous date of the discarded recipe
            self.recipes.at[old_recipe_idx, 'new_date'] = self.recipes.at[old_recipe_idx, 'date']
            update_idx = self._verify_menu()

        self._update_recipes()
        self._save_recipes()
Ejemplo n.º 25
0
def config_setter() -> None:
    """Function that sets the config file"""

    clear_screen()
    load_config()
    load_preference()

    dict_options = {
        "username": config["username"],
        "password": config["password"],
        "player": preference["player"],
        "browser": preference["browser"],
        "download_dir": preference["download_dir"],
        "video_download_dir": preference["video_download_dir"],
        "watch_video_resolution": preference["watch_video_resolution"],
        "download_video_resolution": preference["download_video_resolution"],
    }

    list_options = [[k, v] for k, v in dict_options.items()]

    print(
        tabulate(list_options,
                 headers=["type", "Cur. Value"],
                 tablefmt="pretty"))

    def resolve_value(answer):
        if answer["option"] != "Exit":
            return f"Current Value : {dict_options[answer['option']]} -> New Value "
        clear_screen()
        sys.exit(0)

    def confirm_value(answer):
        return f"Confirm < {dict_options[answer['option']]} -> {answer['value']} > "

    def post_validate(answer, current):
        response = True
        if current == "Yes":
            if answer["option"] in ("username", "password"):
                config[answer["option"]] = answer["value"]
                write_config()
            elif answer["option"] in (
                    "player",
                    "browser",
                    "watch_video_resolution",
                    "download_video_resolution",
            ):
                preference[answer["option"]] = answer["value"]
                write_preference()
            else:
                if os.path.exists(answer["value"]):
                    preference[answer["option"]] = answer["value"]
                    write_preference()
        #                else:
        #                    response = False

        return response

    questions = [
        inquirer.List(
            "option",
            message="<< OPTIONS >> ",
            choices=[*list(dict_options.keys()), "Exit"],
        ),
        inquirer.Text("value", message=resolve_value),
        inquirer.List(
            "commit",
            message=confirm_value,
            choices=["Yes", "No"],
            validate=post_validate,
            default=False,
        ),
        inquirer.List("postExit",
                      message="Edit / Quit ",
                      choices=["Edit", "Quit"]),
    ]

    answer = inquirer.prompt(questions, theme=GreenPassion())

    if answer and answer["postExit"] == "Edit":
        config_setter()

    print("\nConfiguration Saved... Enter to continue...")
    input()
    clear_screen()
    sys.exit(0)
Ejemplo n.º 26
0
if proc.returncode != 0:
    print("error checking services status", file=sys.stderr)
    print(e.decode('ascii'), file=sys.stderr)
    sys.exit(1)


services = get_services_from_cmd_output(o.decode('ascii'))

questions = [inquirer.Checkbox(
    'selected_services',
    message="Services to enable/disable",
    choices=services
)]

services_to_disable = inquirer.prompt(questions, theme=GreenPassion())

print('The following services will be changed:\n')
for service in services_to_disable['selected_services']:
    print("{0} will be {1}".format(service.name,
                                   "disabled" if service.enabled else "enabled"))

questions = [
    inquirer.Confirm('continue',
                     message="Continue", default=True)
]

print()

user_answer = inquirer.prompt(questions)
if user_answer['continue']:
Ejemplo n.º 27
0
def main(argv: Optional[Sequence[Text]] = None):
    """
    Lots of piping done there:

    - Parsing CLI
    - Prompting remaining details via inquirer
    - Orchestrating the import and displaying progress

    Parameters
    ----------
    argv
        Optional override of CLI arguments in case by example you want to call
        this from another Python program
    """

    args = parse_args(argv)
    importer = ImportManager(Path("."))

    if args.backup:
        importer.backups = [importer.backup_from_string_id(x) for x in args.backup]

    answers = inquirer.prompt(make_questions(args, importer), theme=GreenPassion())

    if answers is None:
        return

    if args.target is None:
        importer.target = Path(answers["target"])
    else:
        importer.target = Path(args.target)

    if not args.backup:
        importer.backups = [importer.backup_from_string_id(answers["backup"])]

    for source in (
        importer.source_from_string_id(x)
        for x in [
            *(x for x in answers["sources"] if x != "other"),
            *([answers["other_source"]] if "other" in answers["sources"] else []),
        ]
    ):
        importer.activate_source(source)

    importer.ensure_ids()

    for op in importer.do_import():
        print("")
        print("")
        print(f"---> {op.label}")
        print("")

        bar = tqdm(colour="blue")

        try:
            for p in op.progress:
                bar.total = p.total
                bar.unit = p.unit

                if bar.unit == "byte":
                    bar.unit_scale = True
                    bar.unit_divisor = 1024

                bar.update(p.done - bar.n)
        finally:
            bar.close()
Ejemplo n.º 28
0
from pprint import pprint
import inquirer
from inquirer.themes import GreenPassion

questions = [
    inquirer.Checkbox(
        'interests',
        message="What are you interested in?",
        choices=['Computers', 'Books', 'Science', 'Nature', 'Fantasy', 'History'],
        default=['Computers', 'Books']
    ),
]

answers = inquirer.prompt(questions, theme=GreenPassion())
pprint(answers)
Ejemplo n.º 29
0
else:
    print("Connection not available")
selection = [
    inquirer.List(
        'detection',
        message="What object you want to detect?",
        choices=[
            "car", "bus", "bicycle", "motorbike", "person", "boat", "cat",
            "dog", "cow", "sheep", "bird", "botle"
        ],
    )
]

print("[INFO] Press Enter to Sellect")

answers = inquirer.prompt(selection, theme=GreenPassion())

objex = ''.join(answers['detection'])

a = objex.split(",")

ab = "total " + a[0]

print(
    "[INFO] Prototxt file(by default its set to (mobilenet_ssd/MobileNetSSD_deploy.prototxt)"
)
print(
    "[INFO] Caffe pre-trained model file(by default its set to (mobilenet_ssd/MobileNetSSD_deploy.caffemodel)"
)
print(
    "[INFO] Select Video Input(if you not selected any video file it will start webcam stream)"