Exemple #1
0
def cli_set_config():
    """ command: `leetcode-dl -set`"""

    puts('====== Leetcode-dl ======')
    all_languages = ProgLangDict.keys()
    username = prompt.query('Input your leetcode username: '******'Input your leetcode password: '******'Input your repo url: ')
    while True:
        language = prompt.query(
            'Input your leetcode coding languages(like python, javascript): ')
        languages = [x.lower().strip() for x in language.split(',')]
        if set(languages).issubset(set(all_languages)):
            break
        puts(colored.yellow('language set wrong'))

    dist = prompt.query('Input the path to save the solutions:',
                        default=os.getcwd(),
                        validators=[validators.PathValidator()])

    dct = dict(username=username,
               password=password,
               repo=repo,
               language=language,
               dist=dist)
    write_config(CONFIG_FILE, **dct)
    puts(colored.green('Set Completed!'))
Exemple #2
0
def init():
    if 'files' not in os.listdir(os.getcwd() + '/caoslib'):
        os.mkdir(os.getcwd() + '/caoslib/files')

    open(CONFIG_PATH, 'a').close()
    open(COOKIES_PATH, 'a').close()
    open(LINKS_PATH, 'a').close()

    login = prompt.query('Tell me your login: '******'Tell me your password: '******'Tell me you group number from the caos.ejudge.ru: ')

    config = configparser.ConfigParser()
    config['Credentials'] = {}
    config['Group'] = {}

    config['Credentials']['login'] = login
    config['Credentials']['password'] = password
    config['Group']['group_number'] = group

    open(CONFIG_PATH, 'a').close()
    with open(CONFIG_PATH, 'w') as configfile:
        config.write(configfile)

    init_session()
def getColorData():
    """Asks for hue, saturation and brightness as inputs in the CMD
    
    Returns:
        dict -- If values were ok returns dict containing "hue", "saturation" and "brightness", empty if not.
    """
    tries = 0
    while tries < 3:
        hue_input = prompt.query("Enter hue (0-360): ")
        sat_input = prompt.query("Enter saturation (0-100): ")
        brightness_input = prompt.query("Enter brightness (0-100): ")

        try:
            hue = int(hue_input)
            saturation = int(sat_input)
            brightness = int(brightness_input)

            puts("Setting hue: " + str(hue) + ", saturation: " +
                 str(saturation) + ", brightness: " + str(brightness))

            return {
                "hue": hue,
                "saturation": saturation,
                "brightness": brightness
            }
        except ValueError:
            puts(
                colored.yellow(
                    "Hue must be a number between 0 and 360, try again."))
            tries += 1
    if (tries >= 3):
        puts(colored.red("3 tries of failing is enough, quitting example"))
    return {}
def transfer(database):
    """ The function asks for account  numbers and transfer amount
    """
    my_acc = prompt.query('Enter your account number')
    other_acc = prompt.query('Enter other account number')
    amount = prompt.query('Enter amount :')
    database.transfer(my_acc, other_acc, amount)
def main():

    filenames = getFileNames()

    print("Loading Shapefiles from " + filenames["shapefile"])
    # Open up the shapefile
    states = GeoDataFrame.from_file(filenames["shapefile"])
    # Set the 'Name' column as the index
    states.set_index("NAME", inplace=True)
    print("Done!")

    print("Loading data from " + filenames["data"])
    # Load the file the user wants to process
    data = LoadCSV(filenames["data"])
    print("Done!")

    # list out the columns in the data file
    PickColumns(data)
    # ask the user which columns they want to use for lat/lon
    lat_col = prompt.query("Please enter the column number for Latitude: ", default="7", validators=[])

    lon_col = prompt.query("Please enter the column number for Longitude: ", default="8", validators=[])

    # Wrap them in ints because they need to be referenced as numbers later on
    lat_col = int(lat_col)
    lon_col = int(lon_col)

    # Add a State column to the data file
    data = AddColumn(data, "State")

    # Process each row and add the state name to the new column
    data["State"] = data.apply(lambda row: GetStateFromPoint(row, lat_col, lon_col, states), axis=1)
    print("Writing file to " + filenames["output"])
    data.to_csv(filenames["output"])
    print("Done!")
Exemple #6
0
    def fetch_args(self):
        results = {}

        validate_creds_exists(self.app)
        db = DBWrapper(self.app.creds)
        results["environment"] = db.get_configure().get("environment")
        results["enterprise_id"] = db.get_enterprise_id()
        results["api_key"] = db.get_configure().get("api_key")

        if hasattr(self.app.pargs, "pipeline_id"):
            pipeline_id = self.app.pargs.pipeline_id
            if not pipeline_id:
                pipeline_id = prompt.query("Enter the Pipeline ID: ")

            results["pipeline_id"] = pipeline_id

        if hasattr(self.app.pargs, "execution_id"):
            execution_id = self.app.pargs.execution_id
            if not execution_id:
                execution_id = prompt.query("Enter the Execution ID: ")

            results["execution_id"] = execution_id

        if hasattr(self.app.pargs, "reason"):
            reason = self.app.pargs.reason
            if not reason:
                reason = prompt.query(
                    "Why do you want to stop this Execution? : ")

            results["reason"] = reason

        return results
Exemple #7
0
def main(video_id=None, quality=None, saveOrStream='D'):

    if not video_id:
        idstr = prompt.query("Enter the video ID: ")
        video_id = getVideoId(idstr)
        if not video_id:
            err('invalid video id entered')
            return
    try:
        file_url, localFile = getVideoFileUrl(video_id)

        info("Downloading with filename: {0}".format(localFile))

        if not quality:
            video_options = "1080p (best), 180p (worst), 234p, 360p, 404p, 720p, 900p"
            quality = prompt.query("Enter quality {0}: ".format(video_options))

        if not saveOrStream:
            choice = prompt.query("Enter 'S' to Stream and 'D' to Download ")
        else:
            choice = saveOrStream

        command = "streamlink \"{0}\" \"{1}\" ".format(file_url, quality)
        if choice == "D" or choice == 'd':
            command += "-o \"{0}\"".format(localFile)
        elif choice == "S" or choice == 's':
            info("Streaming ...")
        else:
            err("Invalid command")
            return

        info("Starting system command : {0}".format(command))
        os.system(command)
    except Exception as e:
        err(str(e))
Exemple #8
0
 def get_ticket_number(self):
     ticket_number = prompt.query('Ticket Number: ')
     puts(colored.yellow('Confirm ticket #' + str(ticket_number)))
     if prompt.query('Confirm: y/n: ') == 'y':
         self.ticket_number = int(ticket_number)
         puts(colored.green('#' + str(ticket_number) + ' confirmed!'))
     else:
         self.get_ticket_number()
Exemple #9
0
def register(data, arg):
    puts('Choose a username and password. ' +
         colored.red('Note that this application is NOT secure.') +
         " do not use a password you use elsewhere.")
    username = prompt.query('> username: '******'> password: '******'')
def add(database):
    """ The function asks for account details to be added
    """
    acc_no = prompt.query('Enter Account Number : ')
    name = prompt.query('Enter Name : ')
    acc_type = prompt.query('Account Type : ')
    account = ac.Account(acc_no, name, 0, acc_type)
    database.add_account(account)
def draw(database):
    """ The function asks for account number and amount to be withdrawn
    """
    acc_no = prompt.query('Enter account number')
    if acc_no.isdigit():
        amount = prompt.query('Enter amount :')
        if amount.isdigit():
            database.draw(acc_no, amount)
def add_balance(database):
    """ The function asks for account  number and balance to be added
    """
    acc_no = prompt.query('Enter account number')
    if acc_no.isdigit():
        amount = prompt.query('Enter amount :')
        if amount.isdigit():
            database.add_balance(acc_no, amount)
Exemple #13
0
def push_address(args, pushbullet):
    if args.title and args.body:
        name = args.title
        address = args.body
    else:
        name = prompt.query('Name: ')
        address = prompt.query('Address: ')

    return pushbullet.bullet_address(args.device, name, address)
Exemple #14
0
def push_link(args, pushbullet):
    if args.title or args.url:
        title = args.title
        url = args.url
    else:
        title = prompt.query('Title: ')
        url = prompt.query('URL: ')

    return pushbullet.bullet_link(args.device, title, url)
Exemple #15
0
def push_note(args, pushbullet):
    if args.title or args.url:
        title = args.title
        body = args.body
    else:
        title = prompt.query('Title: ')
        body = prompt.query('Body (optional): ', validators=[])

    return pushbullet.bullet_note(args.device, title, body)
Exemple #16
0
def _get_players():
    num_players = prompt.query('How many players?',
                               default='2',
                               validators=[validators.IntegerValidator()])
    return [
        prompt.query('Player %s name:' % (i + 1),
                     default='Player %s' % (i + 1))
        for i in range(int(num_players))
    ]
def setup_user_input():
    config_file = prompt.query('Config file name:', default='local')
    config_class = prompt.query('Config class name:', default='LocalConfig')
    test_schema = prompt.options('Which tests do you want to run?', triple_options)
    _dict = {
        'config_file': config_file.lower(),
        'config_class': config_class,
        'test_schema': test_schema
    }
    return _dict
Exemple #18
0
def edit_sync_params():
    puts(colored.green('Editing synchronization workload parameters...\n'))
    user_conf.num_consumers = prompt.query('Number of worker threads: ',
                                           default=str(user_conf.num_consumers),
                                           validators=[validators.IntegerValidator()])
    user_conf.deep_sync_interval_seconds = prompt.query('Number of seconds to wait before next full scan: ',
                                                        default=str(user_conf.deep_sync_interval_seconds),
                                                        validators=[validators.IntegerValidator()])
    puts()
    puts(colored.green('Workload parameters saved.'))
Exemple #19
0
def edit_sync_params():
    puts(colored.green('Editing synchronization workload parameters...\n'))
    user_conf.num_consumers = prompt.query('Number of worker threads: ',
                                           default=str(user_conf.num_consumers),
                                           validators=[validators.IntegerValidator()])
    user_conf.deep_sync_interval_seconds = prompt.query('Number of seconds to wait before next full scan: ',
                                                        default=str(user_conf.deep_sync_interval_seconds),
                                                        validators=[validators.IntegerValidator()])
    puts()
    puts(colored.green('Workload parameters saved.'))
Exemple #20
0
def fc_func():
    puts(colored.green("Enter Fibre Channel information"))
    wwn = prompt.query("Enter target WWN:")
    lun_id = prompt.query("Enter Target LUN ID:")
    conn_info = {'driver_volume_type': 'fibre_channel',
                 'data': {'encrypted': False,
                          'target_discovered': False,
                          'target_wwn': wwn,
                          'target_lun': int(lun_id)} }

    return conn_info
Exemple #21
0
def getFileNames():
    filename_dict = {}

    filename_dict["shapefile"] = prompt.query(
        "Shapefile to process: ", default="shapefiles/s_16de14.shp", validators=[]
    )
    filename_dict["data"] = prompt.query("Data to process: ", default="csv/meteorites.csv", validators=[])

    filename_dict["output"] = prompt.query("Output file: ", default="output.csv", validators=[])

    return filename_dict
Exemple #22
0
def push_list(args, pushbullet):
    if args.title or args.items:
        title = args.title
        _items = args.items
    else:
        title = prompt.query('Title: ')
        _items = prompt.query('Items (separate by comma): ')

    items = _items.split(', ')

    return pushbullet.bullet_list(args.device, title, items)
Exemple #23
0
def main():
    video_id = prompt.query("Enter the video ID: ")
    title_url = const.BASEURL.format(video_id)
    video_resp = requests.get(title_url, headers=const.HEADERS)
    if video_resp.status_code != requests.codes.ok:
        err("Failed to get URL")
        return
    result = video_resp.json()
    content_info = result['resultObj']['contentInfo'][0]
    # Video Details
    vid_title = content_info['contentTitle'].replace(" ", "-")
    vid_episode = content_info['episodeNumber']
    vid_ep_title = content_info['episodeTitle'].replace(" ", "-")

    info("You are downloading \"{0}\"".format(vid_title))

    # Downloading actual content now
    file_url = const.CDNURL.format(video_id)
    cdn_resp = requests.get(file_url, headers=const.HEADERS)
    if cdn_resp.status_code != requests.codes.ok:
        err("Failed to get info about content")
        return
    cdn_content = cdn_resp.json()['resultObj']
    src = cdn_content['src']

    file_url = src.replace("https", "hlsvariant://https")
    file_url = file_url.replace("2000,_STAR.", "2000,3000,4500,_STAR.")

    if (vid_title):
        localFile = str(vid_title)
    if (vid_episode):
        localFile += "_" + str(vid_episode)
    if (vid_ep_title):
        localFile += "_" + str(vid_ep_title)
    localFile += ".mp4"

    info("Downloading with filename: {0}".format(localFile))
    video_options = "1080p (best), 180p (worst), 234p, 360p, 404p, 720p, 900p"
    quality = prompt.query("Enter quality {0}: ".format(video_options))

    choice = prompt.query("Enter 'S' to Stream and 'D' to Download ")

    command = "livestreamer \"{0}\" \"{1}\" ".format(file_url, quality)
    if choice == "D" or choice == 'd':
        command += "-o {2}".format(localFile)
    elif choice == "S" or choice == 's':
        info("Streaming ...")
    else:
        err("Invalid command")
        return

    info("Starting system command : {0}".format(command))
    os.system(command)
Exemple #24
0
 def askForMissingObjectnames(self, object_name, object_subname):
     objectnamePrompt, objectnamePromptHR, objectsubnamePrompt, objectsubnamePromptHR = self._getObjectNames()
     if objectnamePromptHR == "":
         objectnamePromptHR = objectnamePrompt
     if objectsubnamePromptHR == "":
         objectsubnamePromptHR = objectsubnamePrompt
     if object_name is None:
         object_name = prompt.query(objectnamePromptHR + ":")
     if object_subname is None:
         if objectsubnamePrompt != "":
             object_subname = prompt.query(objectsubnamePromptHR + ":")
     return [object_name, object_subname]
Exemple #25
0
    def __config(self):
        global portSelection
        configList = [{
            'selector': '1',
            'prompt': 'Set Baud Rate'
        }, {
            'selector': '2',
            'prompt': 'Set Login Details'
        }, {
            'selector': '3',
            'prompt': 'Set AT Library'
        }, {
            'selector': '4',
            'prompt': 'Change Device'
        }, {
            'selector': '5',
            'prompt': 'About'
        }, {
            'selector': '0',
            'prompt': 'Back'
        }]

        config = int(prompt.options("Config:", configList))

        if config == 1:
            baudRate = prompt.query("Baud rate:",
                                    validators=[validators.IntegerValidator()])
            self.__modifyConfigFiles('BaudRate', baudRate)
        elif config == 2:
            print 'Under Construction...'
            os.environ["SIGFOX_USR"] = prompt.query("Username:"******"SIGFOX_PWD"] = getpass.getpass('Password:'******'Error'
        raw_input("Press Enter to continue...")
        self.__config()
Exemple #26
0
def iscsi_func():
    puts(colored.green("Enter iSCSI information"))
    iqn = prompt.query("Enter target IQN:")
    portal = prompt.query("Enter Target Portal ():")
    lun_id = prompt.query("Enter Target LUN ID:")
    conn_info = {'driver_volume_type': 'iscsi',
                 'data': {'encrypted': False,
                          'target_discovered': False,
                          'target_iqn': iqn,
                          'target_portal': portal,
                          'target_lun': int(lun_id)} }

    return conn_info
Exemple #27
0
 def askForMissingObjectnames(self, object_name, object_subname):
     objectnamePrompt, objectnamePromptHR, objectsubnamePrompt, objectsubnamePromptHR = self._getObjectNames(
     )
     if objectnamePromptHR == "":
         objectnamePromptHR = objectnamePrompt
     if objectsubnamePromptHR == "":
         objectsubnamePromptHR = objectsubnamePrompt
     if object_name is None:
         object_name = prompt.query(objectnamePromptHR + ":")
     if object_subname is None:
         if objectsubnamePrompt != "":
             object_subname = prompt.query(objectsubnamePromptHR + ":")
     return [object_name, object_subname]
Exemple #28
0
 def get_board(self):
     boards = self.trello_client.list_boards()
     for i in range(len(boards)):
         print(str(i) + ': ' + boards[i].name)
     done = False
     while not done:
         board_number = int(prompt.query('Board number: '))
         puts(colored.yellow('Confirm board: ' + boards[board_number].name))
         if prompt.query('Confirm: y/n: ') == 'y':
             self.board = boards[board_number]
             self.board_id = self.board.id
             puts(colored.green(self.board.name + ' confimed'))
             done = True
Exemple #29
0
def prompt_drive_config(drive):
    if hasattr(drive, 'config'):
        drive_config_data = drive.config.data
    else:
        drive_config_data = drive_config.DriveConfig.DEFAULT_VALUES
    if drive_config_data['local_root'] is None or drive_config_data['local_root'] == '':
        drive_config_data['local_root'] = OS_USER_HOME + '/OneDrive/' + drive.drive_id
    puts(colored.green('You selected Drive "%s"...' % drive.drive_id))

    puts()
    with indent(4, quote=' >'):
        puts('When specifying local root, pick a directory not used by or under any other Drive.')
        puts('When specifying HTTPS download / upload sizes, note that files larger than those sizes will be handled '
             'as chunks.')
    puts()

    while True:
        local_root = prompt.query('Which local directory do you want to sync with this Drive?',
                                  default=drive_config_data['local_root'])
        try:
            while local_root[-1] == '/':
                local_root = local_root[:-1]
            if not os.path.exists(local_root):
                puts(colored.yellow('Directory "%s" does not exist. Try creating it...' % local_root))
                mkdir(local_root)
                puts(colored.green('Successfully created directory "%s".' % local_root))
            elif os.path.isfile(local_root):
                raise ValueError('Path "%s" is a file.' % local_root)
            if os.path.isdir(local_root):
                drive_config_data['local_root'] = local_root
                break
            raise ValueError('Invalid path "%s"' % local_root)
        except Exception as ex:
            puts(colored.red('Error: ' + str(ex)))
    drive_config_data['max_get_size_bytes'] = prompt.query('Maximum size, in KB, for a single download request?',
                                                           default=str(drive_config_data['max_get_size_bytes'] >> 10),
                                                           validators=[validators.IntegerValidator()]) * 1024
    drive_config_data['max_put_size_bytes'] = prompt.query('Maximum size, in KB, for a single upload request?',
                                                           default=str(drive_config_data['max_put_size_bytes'] >> 10),
                                                           validators=[validators.IntegerValidator()]) * 1024
    try:
        while not prompt.yn('Do you have ignore list files specific to this Drive to add?', default='n'):
            ignore_file_path = prompt.query('Path to the ignore list file (hit [Ctrl+C] to skip): ',
                                            validators=[validators.FileValidator()])
            drive_config_data['ignore_files'].add(ignore_file_path)
            puts(colored.green('Recorded ignore list file: "{}"' % ignore_file_path))
    except KeyboardInterrupt:
        pass
    drive_conf = drive_config.DriveConfig.load(drive_config_data)
    drive.config = drive_conf
    drive_store.add_record(drive)
def search(database):
    """ The function ask for search parameters
    """
    search_by = \
        prompt.query('Search by [n : Name or a :Account Number] : ').lower()
    if search_by == 'n':
        name = prompt.query('Enter Name : ').lower()
        database.search_by_name(name)
    elif search_by == 'a':
        acc_no = prompt.query('Enter Account Number : ')
        if acc_no.isdigit():
            database.search_by_account_no(acc_no)
        else:
            print('Invalid input')
Exemple #31
0
def add_card(cards):
    """Adds card to the database based on user input

    Args:
        cards (Cards): Cards object to interface with MongoDB
    Returns:
        None
    """
    card_set = prompt.query('Enter card set: ', default='None')
    card_color = prompt.query('Enter card color: ')
    card_text = prompt.query('Enter card text: ')
    card_creator = prompt.query('Enter card creator: ', default='None')
    cards.create_cards([{'set': card_set, 'color': card_color,
                        'text': card_text, 'creator': card_creator}])
Exemple #32
0
    def update(self):
        """
        Update an existing Manga title
        """
        try:
            local_manga = self._manga_prompt(
                'Which Manga title would you like to update?')
        except NoMangaSavesError:
            return

        # Run a search query on the selected title
        try:
            remote_series = self.manga.search(local_manga.title)
        except NoSearchResultsError:
            return puts(
                'No search results returned for {query} (the title may have been licensed or otherwise removed)'
                .format(query=colored.blue(local_manga.title, bold=True)))

        for remote_chapter in remote_series.chapters.values():
            try:
                self.manga.update(remote_chapter, local_manga)
            except ImageResourceUnavailableError:
                puts(
                    'A match was found, but no image resources for the pages appear to be available'
                )
                puts(
                    'This probably means the Manga was licensed and has been removed'
                )
                if prompt.query('Exit?',
                                'Y').lower().strip() in self.YES_RESPONSES:
                    self.exit()
                return self.prompt()
            except AttributeError as e:
                self.log.warn(
                    'An exception was raised downloading this chapter',
                    exc_info=e)
                puts(
                    'Chapter does not appear to have any readable pages, skipping'
                )
                continue
            except Exception as e:
                self.log.error('Uncaught exception thrown', exc_info=e)
                response = prompt.query(
                    'An unknown error occurred trying to download this chapter. Continue?',
                    'Y')
                if response.lower().strip() in self.YES_RESPONSES:
                    continue
                puts('Exiting')
                break
Exemple #33
0
def prompt_drive_config(drive):
    if hasattr(drive, 'config'):
        drive_config_data = drive.config.data
    else:
        drive_config_data = drive_config.DriveConfig.DEFAULT_VALUES
    if drive_config_data['local_root'] is None or drive_config_data['local_root'] == '':
        drive_config_data['local_root'] = OS_USER_HOME + '/OneDrive/' + drive.drive_id
    puts(colored.green('You selected Drive "%s"...' % drive.drive_id))

    puts()
    with indent(4, quote=' >'):
        puts('When specifying local root, pick a directory not used by or under any other Drive.')
        puts('When specifying HTTPS download / upload sizes, note that files larger than those sizes will be handled '
             'as chunks.')
    puts()

    while True:
        local_root = prompt.query('Which local directory do you want to sync with this Drive?',
                                  default=drive_config_data['local_root'])
        try:
            if not os.path.exists(local_root):
                puts(colored.yellow('Directory "%s" does not exist. Try creating it...' % local_root))
                mkdir(local_root)
                puts(colored.green('Successfully created directory "%s".' % local_root))
            elif os.path.isfile(local_root):
                raise ValueError('Path "%s" is a file.' % local_root)
            if os.path.isdir(local_root):
                drive_config_data['local_root'] = local_root
                break
            raise ValueError('Invalid path "%s"' % local_root)
        except Exception as e:
            puts(colored.red('Error: ' + str(e)))
    drive_config_data['max_get_size_bytes'] = prompt.query('Maximum size, in KB, for a single download request?',
                                                           default=str(drive_config_data['max_get_size_bytes'] >> 10),
                                                           validators=[validators.IntegerValidator()]) * 1024
    drive_config_data['max_put_size_bytes'] = prompt.query('Maximum size, in KB, for a single upload request?',
                                                           default=str(drive_config_data['max_put_size_bytes'] >> 10),
                                                           validators=[validators.IntegerValidator()]) * 1024
    try:
        while not prompt.yn('Do you have ignore list files specific to this Drive to add?', default='n'):
            ignore_file_path = prompt.query('Path to the ignore list file (hit [Ctrl+C] to skip): ',
                                            validators=[validators.FileValidator()])
            drive_config_data['ignore_files'].add(ignore_file_path)
            puts(colored.green('Recorded ignore list file: "{}"' % ignore_file_path))
    except KeyboardInterrupt:
        pass
    drive_conf = drive_config.DriveConfig.load(drive_config_data)
    drive.config = drive_conf
    drive_store.add_record(drive)
Exemple #34
0
 def _prompt(self, attrName, attrDef):
     attrDef["attr_type"] = str(attrDef["attr_type"]).lower()
     v = []
     if attrDef["attr_type"] == "string":
         if attrDef["attr_mandatory"]:
             v.append(
                 validators.RegexValidator(
                     r'.+', 'Enter a value, that is not empty.'))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return str(result)
     elif attrDef["attr_type"] == "bool":
         if attrDef["attr_mandatory"]:
             v.append(
                 validators.RegexValidator(
                     re.compile('^(true|false|0|1)$', re.IGNORECASE),
                     'Enter true, 1, false or 0.'))
         else:
             v.append(
                 validators.RegexValidator(
                     re.compile('^(true|false|0|1)?$', re.IGNORECASE),
                     'Enter true, 1, false or 0.'))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return bool(result)
     elif attrDef["attr_type"] == "int":
         v.append(
             IntegerValidator('Enter a valid integer.',
                              not attrDef["attr_mandatory"]))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return int(result)
     elif attrDef["attr_type"] == "float":
         v.append(
             FloatValidator('Enter a valid float.',
                            not attrDef["attr_mandatory"]))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return float(result)
     elif attrDef["attr_type"] == "json":
         # todo add json validation
         if attrDef["attr_mandatory"]:
             v.append(validators.RegexValidator(r'.+'))
         return prompt.query(attrDef["attr_name"] + ":", validators=v)
     return None
Exemple #35
0
def monitor():
    ''' Toggle monitoring mode '''
    if not os.path.exists(path):
        os.makedirs(path)
    db.connect()
    db.create_tables([Stock, Company], safe=True)
    user_inp = prompt.query('Enter Commands (h for help)\n>> ')
    while user_inp != 'q':
        if user_inp not in monitor_commands.keys():
            puts('Invalid command')
        else:
            monitor_commands[user_inp][0]()
        puts()
        user_inp = prompt.query('Enter Commands (h for help)\n>> ')
    db.close()
Exemple #36
0
    def prompt(self, header=True):
        """
        Prompt for an action
        :param header: Display the application header before the options
        :type  header: bool

        :return : An action to perform
        :rtype : str
        """
        if header:
            self.print_header()
        puts('1. Download new series')
        puts('2. Update existing series')
        puts('3. Create PDF\'s from existing series')
        puts('4. List all tracked series\'')
        puts('--------------------------------')
        puts('s. Re-run setup')
        puts('e. Exit\n')

        self.log.info('Prompting user for an action')
        action = prompt.query('What would you like to do?').lower()
        if action not in self.PROMPT_ACTIONS:
            self.log.info('User provided an invalid action response')
            puts(
                'Invalid selection, please chose from one of the options listed above'
            )
            return self.prompt(False)

        action = self.PROMPT_ACTIONS[action]
        action_method = getattr(self, action)
        action_method()
Exemple #37
0
    def _manga_prompt(self, query='Which Manga title would you like to use?'):
        """
        Prompt the user to select a saved Manga entry
        :param query: The prompt query message
        :type  query: str

        :return: The metadata instance of the selected Manga
        :rtype : SeriesMeta

        :raises: NoMangaSavesError
        """
        manga_list = self._list_manga()

        # Prompt the user for the Manga title to update
        while True:
            try:
                update_key = int(prompt.query(query))
                local_manga = manga_list[update_key - 1]
            except (ValueError, IndexError):
                self.log.info('User provided invalid update input')
                puts(
                    'Invalid entry, please select a Manga entry from the above list'
                )
                continue
            break
        return local_manga
Exemple #38
0
def dispatch_task():
    puts("\n" + colored.blue("-" * 80) + "\n")
    puts(colored.green("Preference wizard supports the following tasks:\n", bold=True))
    option_descriptions = [
        "Connect a new OneDrive Personal Account",  # 0
        "Connect a new OneDrive for Business Account",  # 1
        "View / Delete connected OneDrive accounts",  # 2
        "Add a remote Drive to sync",  # 3
        "View / Edit / Delete existing Drives",  # 4
        "Edit global ignore list files",  # 5
        "Edit HTTPS proxies",  # 6
        "Configure synchronization workload (resync interval, etc.)",  # 7
        "Exit wizard",  # 8
    ]
    for i in range(0, len(option_descriptions)):
        puts("[{}] {}".format(i, option_descriptions[i]))
    puts()
    task_id = prompt.query(
        "Please enter the task index and hit [ENTER]: ",
        validators=[validators.IntegerValidator(), validators.OptionValidator(range(len(option_descriptions)))],
    )
    tasks = [
        add_personal_account,
        add_business_account,
        list_existing_accounts,
        add_new_drive,
        list_existing_drives,
        edit_default_ignore_list,
        edit_proxies,
        edit_sync_params,
        bye,
    ]
    if task_id < len(option_descriptions) - 1:
        puts("\n" + colored.blue("-" * 80) + "\n")
    tasks[task_id]()
Exemple #39
0
def prompt_edit_drive(drive_list):
    try:
        while True:
            puts()
            target_id = prompt.query("Please enter command: ", validators=[validators.RegexValidator("-?[0-9]+")])
            try:
                if target_id[0] == "-":
                    target_id = int(target_id[1:])
                    drive = drive_list[target_id]
                    if drive is None:
                        raise ValueError("the Drive has been deleted.")
                    drive_store.delete_record(drive)
                    drive_list[target_id] = None
                    puts(colored.green('Successfully deleted Drive "%s"' % drive.drive_id))
                else:
                    target_id = int(target_id)
                    drive = drive_list[target_id]
                    if drive is None:
                        raise ValueError("the Drive has been deleted.")
                    prompt_drive_config(drive)
                    drive_store.add_record(drive)
                    puts(colored.green('Successfully edited Drive "%s"' % drive.drive_id))
            except ValueError as ex:
                puts(colored.red("Error: " + str(ex)))
    except KeyboardInterrupt:
        puts(colored.green("Aborted."))
Exemple #40
0
def setup_tar(filename, name):
    puts(colored.yellow("Checking box integrity..."))
    tar = tarfile.open(filename, 'r')
    files = tar.getnames()
    vmx = None
    for i in files:
        if i.endswith('vmx'):
            vmx = i
        if i.startswith('/') or i.startswith('..'):
            puts(colored.red("This box is comprised of filenames starting with '/' or '..'"))
            puts(colored.red("Exiting for the safety of your files"))
            exit()
    if vmx:
        puts(colored.green("Extracting..."))
        if not name:
            folder, dot, ext = vmx.rpartition('.')
            path = os.path.join(HOME, folder)
            os.mkdir(os.path.join(HOME, folder), 0755)
        else:
            path = os.path.join(HOME, name)
            os.mkdir(os.path.join(HOME, name), 0755)
        tar.extractall(path)
        vmx_path = os.path.join(path, vmx)
        config = {
            'vmx': vmx_path,
            'url': None,
            'user': prompt.query("What username would you like to save?", default='mech')
        }
        save_mechfile(config, path)
        save_mechfile(config, '.')
        rewrite_vmx(vmx_path)
        return os.path.join(path, vmx)
Exemple #41
0
def user_choice():
    """
    Asks the user to choose to look in his favorites or search a new product.
    If the user enters a wrong choice, asks to choose again (recursively).

    :return response: 1 or 2.

    """

    puts(colored.blue("Voulez-vous : "))
    with indent(4):
        puts(colored.blue("1 : Retrouver vos aliments substitués"))
        puts(colored.blue("2 : Rechercher un nouvel aliment"))
    try:
        response = int(prompt.query(" "))
    except ValueError:
        puts(colored.red("Attention : vous devez obligatoirement "
                         "rentrer 1 ou 2 pour continuer."))
        return user_choice()
    else:
        # asking again in case of wrong choice
        choice_list = [1, 2]
        if response not in choice_list:
            puts(colored.red("Attention : vous devez obligatoirement "
                             "rentrer 1 ou 2 pour continuer."))
            return user_choice()
        else:
            return response
Exemple #42
0
def changeColorSpecific():
    """Changes color on a specific printer
    """
    verticalLine()
    puts(colored.cyan("Example - Change color on a specific printer"))
    puts("Available printers: ")
    showPrintersBasic()

    ip_input = prompt.query("Enter printer ip: ")
    try:
        ip = ipaddress.ip_address(ip_input)
        ip = str(ip)

        for printer in printerList.getPrinters():
            if printer.getIp() == ip:
                colors = getColorData()

                if not colors:  #An empty dict is False
                    return

                changeColor(printer, colors['hue'], colors['saturation'],
                            colors['brightness'])
    except ValueError:
        puts(
            colored.yellow(
                "You entered an invalid ip adress. (Format: IPv4Address)"))
Exemple #43
0
def _do_game():
    game = Game(
        players=[Player(name=name) for name in _get_players()],
        max_rounds=int(
            prompt.query('How many rounds would you like to play?',
                         default=str(Game.DEFAULT_ROUNDS_PER_GAME),
                         validators=[validators.IntegerValidator()])),
    )

    puts()
    puts(colored.green('Awesome.'))

    while not game.is_finished:
        game.begin_round()

        puts()
        _puts_beginning_of_round_header(game)

        _init_round(game.current_round)
        while not game.current_round.is_finished:
            _do_turn(game.current_round)

        _puts_end_of_round_summary(game)

    _declare_winner(game)
Exemple #44
0
def init(force):
    """
    This command initializes a folder with the typical contents of a Python package.
    After running this and writing your code, you should be ready to publish your package.
    """
    echo('\nThis utility will help you set up a new python module for publishing on PyPi!\n')
    echo('After answering a few questions, it will create a few files.')
    echo('\nPress ^C at any time to bail!\n')

    remap = {
        'entry': 'entry point',
        'package': 'package name'
    }
    d = _defaults()
    for k, v in d.items():
        d[k] = prompt.query('%s:' % remap.get(k, k), default=v)

    echo('\nReady to create the following files:')

    with indent(4, quote='  -'):
        puts('setup.py')
        puts('setup.cfg')
        puts('MANIFEST.in')
        puts(d['package'] + '/' + '__init__.py')
        puts(d['package'] + '/' + d['entry'])
        puts('requirements.txt')

    finalize = prompt.yn('\nSound like a plan?', default='y')

    if finalize:
        echo('')
        _make_package(d, force)
        echo('')

    success('Your package is initialized!')
Exemple #45
0
def dispatch_task():
    puts('\n' + colored.blue('-' * 80) + '\n')
    puts(
        colored.green('Preference wizard supports the following tasks:\n',
                      bold=True))
    option_descriptions = [
        'Connect a new OneDrive Personal Account',  # 0
        'Connect a new OneDrive for Business Account',  # 1
        'View / Delete connected OneDrive accounts',  # 2
        'Add a remote Drive to sync',  # 3
        'View / Edit / Delete existing Drives',  # 4
        'Edit global ignore list files',  # 5
        'Edit HTTPS proxies',  # 6
        'Configure synchronization workload (resync interval, etc.)',  # 7
        'Exit wizard'  # 8
    ]
    for i in range(0, len(option_descriptions)):
        puts('[{}] {}'.format(i, option_descriptions[i]))
    puts()
    task_id = prompt.query('Please enter the task index and hit [ENTER]: ',
                           validators=[
                               validators.IntegerValidator(),
                               validators.OptionValidator(
                                   range(len(option_descriptions)))
                           ])
    tasks = [
        add_personal_account, add_business_account, list_existing_accounts,
        add_new_drive, list_existing_drives, edit_default_ignore_list,
        edit_proxies, edit_sync_params, bye
    ]
    if task_id < len(option_descriptions) - 1:
        puts('\n' + colored.blue('-' * 80) + '\n')
    tasks[task_id]()
Exemple #46
0
def add_personal_account():
    puts(colored.green('Link with an OneDrive Personal account:'))
    puts(
        colored.cyan(
            'Please use your browser to visit the following URL, sign in with your OneDrive account and '
            'authorize onedrive-d, then copy the callback URL back here. The callback URL is the URL at '
            'which the authorization page goes blank and usually starts with '
            + clients.PersonalClient.DEFAULT_REDIRECT_URI + '.'))
    puts()
    puts(colored.yellow('Please visit this URL: '))
    puts(personal_client.get_auth_uri())
    while True:
        try:
            url = prompt.query(
                str(
                    colored.yellow(
                        '\nPlease paste the callback URL or hit [Ctrl+C] to abort:'
                    )))
            account = accounts.get_personal_account(personal_client, uri=url)
            profile = account.profile
            account_store.add_account(account)
            puts(
                colored.green('Success: added account {} ({}).'.format(
                    profile.user_id, profile.name)))
            return
        except KeyboardInterrupt:
            puts(colored.red('Aborted.'))
            return
        except Exception as ex:
            puts(colored.red('Error: ' + str(ex)))
Exemple #47
0
def category_selection():
    """
    Asks the user to choose in which category to look for a product.
    If the user enters a wrong choice, asks to choose again (recursively).

    :return categories[category_number]: chosen category.

    """

    puts(colored.green("Rentrez le numéro de la catégorie "
                       "choisie pour accéder aux produits : "))
    # getting categories from the database
    categories = []
    for element in Category.objects.get_categories():
        categories.append(element['name'])
    # asking the user to choose
    for i in range(len(categories)):
        with indent(4):
            puts(colored.blue(str(i + 1) + ' : ' + categories[i]))
    try:
        category_number = int(prompt.query(" "))
        category_number = category_number - 1
    except ValueError:
        # asking again in case of wrong choice
        puts(colored.red("Attention : vous devez rentrer un nombre"
                         " de la liste de catégories"))
        return category_selection()
    else:
        if category_number in range(len(categories)):
            return categories[category_number]
        else:
            # asking again in case of wrong choice
            puts(colored.red("Attention : vous devez rentrer un nombre"
                             " de la liste de catégories"))
            return category_selection()
Exemple #48
0
def add_personal_account():
    puts(colored.green("Link with an OneDrive Personal account:"))
    puts(
        colored.cyan(
            "Please use your browser to visit the following URL, sign in with your OneDrive account and "
            "authorize onedrive-d, then copy the callback URL back here. The callback URL is the URL at "
            "which the authorization page goes blank and usually starts with "
            + clients.PersonalClient.DEFAULT_REDIRECT_URI
            + "."
        )
    )
    puts()
    puts(colored.yellow("Please visit this URL: "))
    puts(personal_client.get_auth_uri())
    while True:
        try:
            url = prompt.query(str(colored.yellow("\nPlease paste the callback URL or hit [Ctrl+C] to abort:")))
            account = accounts.get_personal_account(personal_client, uri=url)
            profile = account.profile
            account_store.add_account(account)
            puts(colored.green("Success: added account {} ({}).".format(profile.user_id, profile.name)))
            return
        except KeyboardInterrupt:
            puts(colored.red("Aborted."))
            return
        except Exception as ex:
            puts(colored.red("Error: " + str(ex)))
Exemple #49
0
def prompt_edit_drive(drive_list):
    try:
        while True:
            puts()
            target_id = prompt.query(
                'Please enter command: ',
                validators=[validators.RegexValidator('-?[0-9]+')])
            try:
                if target_id[0] == '-':
                    target_id = int(target_id[1:])
                    drive = drive_list[target_id]
                    if drive is None:
                        raise ValueError('the Drive has been deleted.')
                    drive_store.delete_record(drive)
                    drive_list[target_id] = None
                    puts(
                        colored.green('Successfully deleted Drive "%s"' %
                                      drive.drive_id))
                else:
                    target_id = int(target_id)
                    drive = drive_list[target_id]
                    if drive is None:
                        raise ValueError('the Drive has been deleted.')
                    prompt_drive_config(drive)
                    drive_store.add_record(drive)
                    puts(
                        colored.green('Successfully edited Drive "%s"' %
                                      drive.drive_id))
            except ValueError as ex:
                puts(colored.red('Error: ' + str(ex)))
    except KeyboardInterrupt:
        puts(colored.green('Aborted.'))
Exemple #50
0
def dispatch_task():
    puts('\n' + colored.blue('-' * 80) + '\n')
    puts(colored.green('Preference wizard supports the following tasks:\n', bold=True))
    option_descriptions = [
        'Connect a new OneDrive Personal Account',  # 0
        'Connect a new OneDrive for Business Account',  # 1
        'View / Delete connected OneDrive accounts',  # 2
        'Add a remote Drive to sync',  # 3
        'View / Edit / Delete existing Drives',  # 4
        'Edit global ignore list files',  # 5
        'Edit HTTPS proxies',  # 6
        'Configure synchronization workload (resync interval, etc.)',  # 7
        'Exit wizard'  # 8
    ]
    for i in range(0, len(option_descriptions)):
        puts('[{}] {}'.format(i, option_descriptions[i]))
    puts()
    task_id = prompt.query('Please enter the task index and hit [ENTER]: ',
                           validators=[
                               validators.IntegerValidator(),
                               validators.OptionValidator(range(len(option_descriptions)))])
    tasks = [
        add_personal_account,
        add_business_account,
        list_existing_accounts,
        add_new_drive,
        list_existing_drives,
        edit_default_ignore_list,
        edit_proxies,
        edit_sync_params,
        bye
    ]
    if task_id < len(option_descriptions) - 1:
        puts('\n' + colored.blue('-' * 80) + '\n')
    tasks[task_id]()
Exemple #51
0
def init(force):
    """
    This command initializes a folder with the typical contents of a Python package.
    After running this and writing your code, you should be ready to publish your package.
    """
    echo('\nThis utility will help you set up a new python module for publishing on PyPi!\n')
    echo('After answering a few questions, it will create a few files.')
    echo('\nPress ^C at any time to bail!\n')

    remap = {
        'entry': 'entry point',
        'package': 'package name'
    }
    d = _defaults()
    for k, v in d.items():
        d[k] = prompt.query('%s:' % remap.get(k, k), default=v)

    echo('\nReady to create the following files:')

    with indent(4, quote='  -'):
        puts('setup.py')
        puts('setup.cfg')
        puts('MANIFEST.in')
        puts(d['package'] + '/' + '__init__.py')
        puts(d['package'] + '/' + d['entry'])
        puts('requirements.txt')

    finalize = prompt.yn('\nSound like a plan?', default='y')

    if finalize:
        echo('')
        _make_package(d, force)
        echo('')

    success('Your package is initialized!')
Exemple #52
0
def _get_user_action():
  """Prompt user for text input, returns parsed action and direction

  Returns: tuple of <action>, <direction>
  <action> is either 'move' or 'look'
  <direction> is one of the compass directions (north, south, east, west)
  """
  user_input = prompt.query(">")
  input_gen = _yield_input_tokens(user_input)

  action = None
  while not action:
    try:
      token = next(input_gen)
    except StopIteration as err:
      print(err)
      break

    if token in MOVEMENT_SET:
      action = 'move'
    elif token in LOOKING_SET:
      action = 'look'

  direction = None
  while not direction:
    try:
      token = next(input_gen)
    except:
      print("End of input")
      break

    if token in DIRECTION_SET:
      direction = token

  return (action, direction)
def get_team_info():
    team_id = prompt.query("Enter a team ID")
    try:
        team = _db_api_get_authenticated("/teams/info")['teams'][team_id]
    except:
        puts(colored.red("Couldn't get team info for that team!"))
        return
    print team
    puts(colored.cyan("#####TEAM %s#############" % team_id))
    puts("Name: " + team['name'])
    puts("E-Mail: " + team['email'])
    puts("URL: " + team['url'])
    puts("Country: " + team['country'])
    meta = _db_api_get_authenticated("/teams/metadata/team/" + str(team['id']))['metadata']
    univ_url = meta[univ_url_id]['content']
    if not univ_url.startswith("http"):
        univ_url = "http://" + univ_url
    poc_url = meta[prof_url_id]['content']
    poc_email = meta[prof_email_id]['content']
    poc_name = meta[prof_name_id]['content']
    univ_name = meta[univ_name_id]['content']
    team_id = team['id']
    validated = team['validated']
    puts("Metadata: ")
    puts("School: %s (%s)" % (univ_name, univ_url))
    puts("POC: %s <%s> (%s)" % (poc_name, poc_email, poc_url))
Exemple #54
0
def main():
    gs = goslate.Goslate()
    puts(colored.green('PO File translation with GoogleTranslate', bold=True))
    path = prompt.query('POFile Path: ', validators=[PoFileValidator()])
    po = polib.pofile(path)
    target_language = prompt.query('Target Language: ',
                                   validators=[RegexValidator(r'.+')])
    source_language = prompt.query('Source Language: ',
                                   validators=[RegexValidator(r'.+')])

    for entry in progress.bar(po, expected_size=len(po)):
        translate = gs.translate(entry.msgid, target_language,
                                 source_language)
        entry.msgstr = translate
    po.save()
    puts(colored.green('%s saved' % path))
Exemple #55
0
    def configure(self):
        """Configure the credentials and host endpoints of the customer"""

        # Trigger the Insert operation, if --set is given OR if the Creds DB is empty
        db = DBWrapper(self.app.creds)
        credentials = db.get_configure()

        if self.app.pargs.set or not credentials:
            environment = input("Environment name: ")
            api_key = prompt.query("Esper API Key: ")

            token_client = APIClient({'api_key': api_key, 'environment': environment}).get_token_api_client()
            try:
                response = token_client.get_token_info()
            except ApiException as e:
                self.app.log.error(f"[configure] Failed to get token info: {e}")
                if e.status == HTTPStatus.UNAUTHORIZED:
                    self.app.render("You are not authorized, invalid API Key.")
                else:
                    error_message = json.loads(e.body).get('message') if e.body and json.loads(e.body).get(
                        'message') else e.reason
                    self.app.render(f"ERROR: {error_message}")
                return

            if response:
                enterprise_id = response.enterprise
            else:
                self.app.log.info(f"[configure] API key is not associated with any enterprise.")
                self.app.render("API key is not associated with any enterprise.")
                return

            credentials = {
                "environment": environment,
                "api_key": api_key,
                "enterprise_id": enterprise_id
            }

            # set new credentials into the DB
            self.app.log.debug("Purging and inserting new credentials DB...")
            db.set_configure(credentials)

        # Trigger listing operation, if --list is given or Creds DB has content
        if self.app.pargs.list or credentials:
            validate_creds_exists(self.app)

            if not self.app.pargs.json:
                title = "TITLE"
                details = "DETAILS"
                renderable = [
                    {title: 'environment', details: credentials.get('environment')},
                    {title: 'api_key', details: credentials.get('api_key')}
                ]
                self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys",
                                tablefmt="plain")
            else:
                renderable = {
                    'environment': credentials.get('environment'),
                    'api_key': credentials.get('api_key')
                }
                self.app.render(renderable, format=OutputFormat.JSON.value)
Exemple #56
0
def init(force):
    """
    This command initializes a folder with the typical contents of a Python package.
    After running this and writing your code, you should be ready to publish your package.
    """
    echo('\nThis utility will help you set up a new python module for publishing on PyPi!\n')
    echo('After answering a few questions, it will create a few files.')
    echo('\nPress ^C at any time to bail!\n')

    d = {}
    d['name'] = prompt.query('name:', default=os.getcwd().split('/')[-1])
    d['version'] = prompt.query('version:', default='1.0.0')
    gitauthor = retrieve(['git', 'config', '--get', 'user.username'], default=getpass.getuser())
    gitemail = retrieve(['git', 'config', '--get', 'user.email'], default=getpass.getuser() + '@gmail.com')
    d['author'] = prompt.query('author:', default=gitauthor)
    d['email'] = prompt.query('email:', default=gitemail)
    gitrepo = 'https://github.com/' + d['author'] + '/' + d['name']
    d['repository'] = prompt.query('repository:', default=gitrepo, validators=[])
    d['readme'] = prompt.query('readme:', default='README.md')
    d['license'] = prompt.query('license:', default='MIT')
    d['package'] = prompt.query('package name:', default=d['name'].replace('-','_'))
    d['entry'] = prompt.query('entry point:', default='main.py')
    d['description'] = prompt.query('description:', default='', validators=[])
    
    echo('\nReady to create the following files:')

    with indent(4, quote='  -'):
        puts('setup.py')
        puts('setup.cfg')
        puts('MANIFEST.in')
        puts(d['package'] + '/' + '__init__.py')
        puts(d['package'] + '/' + d['entry'])
        puts('requirements.txt')

    finalize = prompt.yn('\nSound like a plan?', default='y')

    if finalize:
        echo('')
        write('requirements.txt', force=force)
        write('setup.py', fields=d, force=force)
        write('setup.cfg', fields=d, stringify=False, force=force)
        write('MANIFEST.in', fields=d, stringify=False, force=force)
        write('__init__.py', fields=d, folder=d['package'], force=force)
        write(d['entry'], folder=d['package'], force=force)
        echo('')

    success('Your package is initialized!')
Exemple #57
0
 def ask(self, string_id):
     '''Ask a step question.'''
     question = QUESTIONS.get(string_id, None)
     if question is None:
         return
     self.config[string_id] = prompt.query(
         question.text, default=question.default,
         validators=[getattr(self, question.validator)])
Exemple #58
0
    def get_memory(self):
        """
        Customize default Memory

        https://docs.vagrantup.com/v2/virtualbox/configuration.html
        """
        if prompt.yn('Customize your box memory', default='y'):
            self.content['memory'] = prompt.query(
                "New Memory: ", validators=[IntegerValidator()])
Exemple #59
0
    def forwarded_port(self, another_ports=None):
        """
        Forwarded ports allow you to access a port on your host
        machine and have all data forwarded to a port on the guest
        machine, over either TCP or UDP.

        https://docs.vagrantup.com/v2/networking/forwarded_ports.html
        """
        ports = another_ports if another_ports else []
        if prompt.yn('Create a forwarded port ?', default='y'):
            guest = prompt.query("Guest Port: ",
                                 validators=[IntegerValidator()])
            host = prompt.query("Host Port: ",
                                validators=[IntegerValidator()])
            data = {'quest': guest, 'host': host}
            ports.append(data)
            self.forwarded_port(another_ports=ports)
        self.content['forwarded_ports'] = ports