Instruction:
Given the following Python 3 function, write the documentation
def check_mod_enabled(mod):
    '''
    Checks to see if the specific apache mod is enabled.

    This will only be functional on operating systems that support
    `a2enmod -l` to list the enabled mods.

    CLI Example:

    .. code-block:: bash

        salt '*' apache.check_mod_enabled status
    '''
    if mod.endswith('.load') or mod.endswith('.conf'):
        mod_name = mod[:-5]
    else:
        mod_name = mod

    cmd = 'a2enmod -l'
    try:
        active_mods = __salt__['cmd.run'](cmd, python_shell=False).split(' ')
    except Exception as e:
        return e

    return mod_name in active_mods

Response: Checks to see if apache mod is enabled.


Instruction:
Write a Python 3 script for
creating an alias for a key.

Response:
def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None,
                 profile=None):
    '''
    Create a display name for a key.

    CLI example::

        salt myminion boto_kms.create_alias 'alias/mykey' key_id
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        conn.create_alias(alias_name, target_key_id)
        r['result'] = True
    except boto.exception.BotoServerError as e:
        r['result'] = False
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Implement a Python 3 function for
creating a grant for a key.

Response:
def create_grant(key_id, grantee_principal, retiring_principal=None,
                 operations=None, constraints=None, grant_tokens=None,
                 region=None, key=None, keyid=None, profile=None):
    '''
    Adds a grant to a key to specify who can access the key and under what
    conditions.

    CLI example::

        salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if key_id.startswith('alias/'):
        key_id = _get_key_id(key_id)
    r = {}
    try:
        r['grant'] = conn.create_grant(
            key_id,
            grantee_principal,
            retiring_principal=retiring_principal,
            operations=operations,
            constraints=constraints,
            grant_tokens=grant_tokens
        )
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Here you have a function in Python 3, explain what it does
def create_key(policy=None, description=None, key_usage=None, region=None,
               key=None, keyid=None, profile=None):
    '''
    Creates a master key.

    CLI example::

        salt myminion boto_kms.create_key '{"Statement":...}' "My master key"
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    _policy = salt.serializers.json.serialize(policy)
    try:
        key_metadata = conn.create_key(
            _policy,
            description=description,
            key_usage=key_usage
        )
        r['key_metadata'] = key_metadata['KeyMetadata']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response: Create a master key.


Instruction:
Here you have a function in Python 3, explain what it does
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    Decrypt ciphertext.

    CLI example::

        salt myminion boto_kms.decrypt encrypted_ciphertext
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        plaintext = conn.decrypt(
            ciphertext_blob,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['plaintext'] = plaintext['Plaintext']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response:
Decrypt ciphertext.

    CLI example::

        salt myminion boto_kms.decrypt encrypted_ciphertext


Instruction:
Can you tell what is the following Python 3 function doing
def key_exists(key_id, region=None, key=None, keyid=None, profile=None):
    '''
    Check for the existence of a key.

    CLI example::

        salt myminion boto_kms.key_exists 'alias/mykey'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        key = conn.describe_key(key_id)
        # TODO: add to context cache
        r['result'] = True
    except boto.exception.BotoServerError as e:
        if isinstance(e, boto.kms.exceptions.NotFoundException):
            r['result'] = False
            return r
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response: Check for the existence of a key.


Instruction:
Here you have a function in Python 3, explain what it does
def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):
    '''
    From an alias, get a key_id.
    '''
    key_metadata = describe_key(
        alias, region, key, keyid, profile
    )['key_metadata']
    return key_metadata['KeyId']

Response: Get a key_id from an alias get a key_id.


Instruction:
Write a Python 3 function for
marking a key as disabled.

Response:
def disable_key(key_id, region=None, key=None, keyid=None, profile=None):
    '''
    Mark key as disabled.

    CLI example::

        salt myminion boto_kms.disable_key 'alias/mykey'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        key = conn.disable_key(key_id)
        r['result'] = True
    except boto.exception.BotoServerError as e:
        r['result'] = False
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Write a Python 3 function that can
encrypt plaintext into cipher text using specified key.

Response:
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    Encrypt plaintext into cipher text using specified key.

    CLI example::

        salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        ciphertext = conn.encrypt(
            key_id,
            plaintext,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['ciphertext'] = ciphertext['CiphertextBlob']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Can you generate the documentation for the following Python 3 function
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
                      key_spec=None, grant_tokens=None, region=None, key=None,
                      keyid=None, profile=None):
    '''
    Generate a secure data key.

    CLI example::

        salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        data_key = conn.generate_data_key(
            key_id,
            encryption_context=encryption_context,
            number_of_bytes=number_of_bytes,
            key_spec=key_spec,
            grant_tokens=grant_tokens
        )
        r['data_key'] = data_key
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response: Generate a secure data key.


Instruction:
Write a Python 3 function for
generating a random string.

Response:
def generate_random(number_of_bytes=None, region=None, key=None, keyid=None,
                    profile=None):
    '''
    Generate a random string.

    CLI example::

        salt myminion boto_kms.generate_random number_of_bytes=1024
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        random = conn.generate_random(number_of_bytes)
        r['random'] = random['Plaintext']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Explain what the following Python 3 code does
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None,
                   profile=None):
    '''
    Get the policy for the specified key.

    CLI example::

        salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        key_policy = conn.get_key_policy(key_id, policy_name)
        r['key_policy'] = salt.serializers.json.deserialize(
            key_policy['Policy'],
            object_pairs_hook=odict.OrderedDict
        )
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response: Get the key policy for the specified key.


Instruction:
Create a Python 3 function for
getting status of whether or not key rotation is enabled for a key.

Response:
def get_key_rotation_status(key_id, region=None, key=None, keyid=None,
                            profile=None):
    '''
    Get status of whether or not key rotation is enabled for a key.

    CLI example::

        salt myminion boto_kms.get_key_rotation_status 'alias/mykey'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        key_rotation_status = conn.get_key_rotation_status(key_id)
        r['result'] = key_rotation_status['KeyRotationEnabled']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
How would you implement a function in Python 3 that
lists all grants for the specified key.

Response:
def list_grants(key_id, limit=None, marker=None, region=None, key=None,
                keyid=None, profile=None):
    '''
    List grants for the specified key.

    CLI example::

        salt myminion boto_kms.list_grants 'alias/mykey'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if key_id.startswith('alias/'):
        key_id = _get_key_id(key_id)
    r = {}
    try:
        _grants = []
        next_marker = None
        while True:
            grants = conn.list_grants(
                key_id,
                limit=limit,
                marker=next_marker
            )
            for grant in grants['Grants']:
                _grants.append(grant)
            if 'NextMarker' in grants:
                next_marker = grants['NextMarker']
            else:
                break
        r['grants'] = _grants
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Can you tell what is the following Python 3 function doing
def list_key_policies(key_id, limit=None, marker=None, region=None, key=None,
                      keyid=None, profile=None):
    '''
    List key_policies for the specified key.

    CLI example::

        salt myminion boto_kms.list_key_policies 'alias/mykey'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if key_id.startswith('alias/'):
        key_id = _get_key_id(key_id)
    r = {}
    try:
        key_policies = conn.list_key_policies(
            key_id,
            limit=limit,
            marker=marker
        )
        # TODO: handle limit, marker and truncation automatically.
        r['key_policies'] = key_policies['PolicyNames']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response: List key_policies for the specified key.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def put_key_policy(key_id, policy_name, policy, region=None, key=None,
                   keyid=None, profile=None):
    '''
    Attach a key policy to the specified key.

    CLI example::

        salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}'
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy))
        r['result'] = True
    except boto.exception.BotoServerError as e:
        r['result'] = False
        r['error'] = __utils__['boto.get_error'](e)
    return r

Response: Attach a key policy to the specified key.


Instruction:
Can you create a Python 3 function that
revokes a grant from a key.

Response:
def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None,
                 profile=None):
    '''
    Revoke a grant from a key.

    CLI example::

        salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j...
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if key_id.startswith('alias/'):
        key_id = _get_key_id(key_id)
    r = {}
    try:
        conn.revoke_grant(key_id, grant_id)
        r['result'] = True
    except boto.exception.BotoServerError as e:
        r['result'] = False
        r['error'] = __utils__['boto.get_error'](e)
    return r


Instruction:
Can you write a function in Python 3 where it
prints the stack trace and environment information to the given printout.

Response:
def _makepretty(printout, stack):
    '''
    Pretty print the stack trace and environment information
    for debugging those hard to reproduce user problems.  :)
    '''
    printout.write('======== Salt Debug Stack Trace =========\n')
    traceback.print_stack(stack, file=printout)
    printout.write('=========================================\n')


Instruction:
Write a Python 3 script to
signal handler for SIGUSR2 only available on Unix - like systems

Response:
def _handle_sigusr2(sig, stack):
    '''
    Signal handler for SIGUSR2, only available on Unix-like systems
    '''
    try:
        import yappi
    except ImportError:
        return
    if yappi.is_running():
        yappi.stop()
        filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid())
        destfile = os.path.join(tempfile.gettempdir(), filename)
        yappi.get_func_stats().save(destfile, type='CALLGRIND')
        if sys.stderr.isatty():
            sys.stderr.write('Saved profiling data to: {0}\n'.format(destfile))
        yappi.clear_stats()
    else:
        if sys.stderr.isatty():
            sys.stderr.write('Profiling started\n')
        yappi.start()


Instruction:
How would you explain what the following Python 3 function does
def enable_sig_handler(signal_name, handler):
    '''
    Add signal handler for signal name if it exists on given platform
    '''
    if hasattr(signal, signal_name):
        signal.signal(getattr(signal, signal_name), handler)

Response: Enable signal handler for given signal name on given platform


Instruction:
How would you explain what the following Python 3 function does
def caller_name(skip=2, include_lineno=False):
    '''
    Get a name of a caller in the format module.class.method

    `skip` specifies how many levels of stack to skip while getting caller
    name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.

    An empty string is returned if skipped levels exceed stack height

    Source: https://gist.github.com/techtonik/2151727
    '''
    stack = inspect.stack()
    start = 0 + skip
    if len(stack) < start + 1:
        return ''
    parentframe = stack[start][0]

    name = []
    if include_lineno is True:
        try:
            lineno = inspect.getframeinfo(parentframe).lineno
        except:  # pylint: disable=bare-except
            lineno = None
    module = inspect.getmodule(parentframe)
    # `modname` can be None when frame is executed directly in console
    # TODO(techtonik): consider using __main__
    if module:
        name.append(module.__name__)
    # detect classname
    if 'self' in parentframe.f_locals:
        # I don't know any way to detect call from the object method
        # XXX: there seems to be no way to detect static method call - it will
        #      be just a function call
        name.append(parentframe.f_locals['self'].__class__.__name__)
    codename = parentframe.f_code.co_name
    if codename != '<module>':  # top level usually
        name.append(codename)   # function or a method
    del parentframe
    fullname = '.'.join(name)
    if include_lineno and lineno:
        fullname += ':{}'.format(lineno)
    return fullname

Response: Get a name of a caller in the format module. class. method. caller.


Instruction:
Write a Python 3 script for
ensuring the NX - OS system image is running on the device.

Response:
def image_running(name, system_image, kickstart_image=None, issu=True, **kwargs):
    '''
    Ensure the NX-OS system image is running on the device.

    name
        Name of the salt state task

    system_image
        Name of the system image file on bootflash:

    kickstart_image
        Name of the kickstart image file on bootflash:
        This is not needed if the system_image is a combined system and
        kickstart image
        Default: None

    issu
        Ensure the correct system is running on the device using an in service
        software upgrade, or force a disruptive upgrade by setting the option
        to False.
        Default: False

    timeout
        Timeout in seconds for long running 'install all' upgrade command.
        Default: 900

    Examples:

    .. code-block:: yaml

        upgrade_software_image_n9k:
          nxos.image_running:
            - name: Ensure nxos.7.0.3.I7.5a.bin is running
            - system_image: nxos.7.0.3.I7.5a.bin
            - issu: True

        upgrade_software_image_n7k:
          nxos.image_running:
            - name: Ensure n7000-s2-kickstart.8.0.1.bin is running
            - kickstart_image: n7000-s2-kickstart.8.0.1.bin
            - system_image: n7000-s2-dk9.8.0.1.bin
            - issu: False
    '''
    ret = {'name': name,
           'result': False,
           'changes': {},
           'comment': ''}

    if kickstart_image is None:
        upgrade = __salt__['nxos.upgrade'](system_image=system_image,
                                           issu=issu, **kwargs)
    else:
        upgrade = __salt__['nxos.upgrade'](system_image=system_image,
                                           kickstart_image=kickstart_image,
                                           issu=issu, **kwargs)

    if upgrade['upgrade_in_progress']:
        ret['result'] = upgrade['upgrade_in_progress']
        ret['changes'] = upgrade['module_data']
        ret['comment'] = 'NX-OS Device Now Being Upgraded - See Change Details Below'
    elif upgrade['succeeded']:
        ret['result'] = upgrade['succeeded']
        ret['comment'] = 'NX-OS Device Running Image: {}'.format(_version_info())
    else:
        ret['comment'] = 'Upgrade Failed: {}.'.format(upgrade['error_data'])

    return ret


Instruction:
Here you have a function in Python 3, explain what it does
def WaitForTasks(tasks, si):

   pc = si.content.propertyCollector

   taskList = [str(task) for task in tasks]

   # Create filter
   objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
                                                            for task in tasks]
   propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
                                                         pathSet=[], all=True)
   filterSpec = vmodl.query.PropertyCollector.FilterSpec()
   filterSpec.objectSet = objSpecs
   filterSpec.propSet = [propSpec]
   filter = pc.CreateFilter(filterSpec, True)

   try:
      version, state = None, None

      # Loop looking for updates till the state moves to a completed state.
      while len(taskList):
         update = pc.WaitForUpdates(version)
         for filterSet in update.filterSet:
            for objSet in filterSet.objectSet:
               task = objSet.obj
               for change in objSet.changeSet:
                  if change.name == 'info':
                     state = change.val.state
                  elif change.name == 'info.state':
                     state = change.val
                  else:
                     continue

                  if not str(task) in taskList:
                     continue

                  if state == vim.TaskInfo.State.success:
                     # Remove task from taskList
                     taskList.remove(str(task))
                  elif state == vim.TaskInfo.State.error:
                     raise task.info.error
         # Move to next version
         version = update.version
   finally:
      if filter:
         filter.Destroy()

Response: This function waits for the tasks to complete.


Instruction:
Can you implement a function in Python 3 that
calculates the checksum char used for the 16th char in the value.

Response:
def checksum(value):
    """
    Calculates the checksum char used for the 16th char.
    Author: Vincenzo Palazzo
    """
    return chr(65 + sum(CHECKSUM_TABLE[index % 2][ALPHANUMERICS_DICT[char]]
                        for index, char in enumerate(value)) % 26)


Instruction:
Write a Python 3 script to
return a random binary blob.

Response:
def binary(self, length=(1 * 1024 * 1024)):
        """ Returns random binary blob.

        Default blob size is 1 Mb.
        """
        blob = [self.generator.random.randrange(256) for _ in range(length)]
        return bytes(blob) if sys.version_info[0] >= 3 else bytearray(blob)


Instruction:
Write a Python 3 script to
calculate the md5 hash of a given string

Response:
def md5(self, raw_output=False):
        """
        Calculates the md5 hash of a given string
        :example 'cfcd208495d565ef66e7dff9f98764da'
        """
        res = hashlib.md5(str(self.generator.random.random()).encode('utf-8'))
        if raw_output:
            return res.digest()
        return res.hexdigest()


Instruction:
Create a Python 3 function to
generate a random UUID4 string.

Response:
def uuid4(self, cast_to=str):
        """
        Generates a random UUID4 string.
        :param cast_to: Specify what type the UUID should be cast to. Default is `str`
        :type cast_to: callable
        """
        # Based on http://stackoverflow.com/q/41186818
        return cast_to(uuid.UUID(int=self.generator.random.getrandbits(128), version=4))


Instruction:
Can you tell what is the following Python 3 function doing
def password(
            self,
            length=10,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True):
        """
        Generates a random password.
        @param length: Integer. Length of a password
        @param special_chars: Boolean. Whether to use special characters !@#$%^&*()_+
        @param digits: Boolean. Whether to use digits
        @param upper_case: Boolean. Whether to use upper letters
        @param lower_case: Boolean. Whether to use lower letters
        @return: String. Random password
        """
        choices = ""
        required_tokens = []
        if special_chars:
            required_tokens.append(
                self.generator.random.choice("!@#$%^&*()_+"))
            choices += "!@#$%^&*()_+"
        if digits:
            required_tokens.append(self.generator.random.choice(string.digits))
            choices += string.digits
        if upper_case:
            required_tokens.append(
                self.generator.random.choice(string.ascii_uppercase))
            choices += string.ascii_uppercase
        if lower_case:
            required_tokens.append(
                self.generator.random.choice(string.ascii_lowercase))
            choices += string.ascii_lowercase

        assert len(
            required_tokens) <= length, "Required length is shorter than required characters"

        # Generate a first version of the password
        chars = self.random_choices(choices, length=length)

        # Pick some unique locations
        random_indexes = set()
        while len(random_indexes) < len(required_tokens):
            random_indexes.add(
                self.generator.random.randint(0, len(chars) - 1))

        # Replace them with the required characters
        for i, index in enumerate(random_indexes):
            chars[index] = required_tokens[i]

        return ''.join(chars)

Response: Generates a random password.


Instruction:
Make a summary of the following Python 3 code
def checksum_identity_card_number(characters):
    weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3]
    check_digit = 0

    for i in range(3):
        check_digit += weights_for_check_digit[i] * (ord(characters[i]) - 55)

    for i in range(4, 9):
        check_digit += weights_for_check_digit[i] * characters[i]

    check_digit %= 10

    return check_digit

Response: Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.


Instruction:
How would you implement a function in Python 3 that
returns 9 character Polish Identity Card Number

Response:
def identity_card_number(self):
        """
        Returns 9 character Polish Identity Card Number,
        Polish: Numer Dowodu Osobistego.

        The card number consists of 3 letters followed by 6 digits (for example, ABA300000),
        of which the first digit (at position 3) is the check digit.

        https://en.wikipedia.org/wiki/Polish_identity_card
        """
        identity = []

        for _ in range(3):
            identity.append(self.random_letter().upper())

        # it will be overwritten by a checksum
        identity.append(0)

        for _ in range(5):
            identity.append(self.random_digit())

        identity[3] = checksum_identity_card_number(identity)

        return ''.join(str(character) for character in identity)


Instruction:
Can you tell what is the following Python 3 function doing
def execute(self):

        # retrieve default language from system environment
        default_locale = os.environ.get('LANG', 'en_US').split('.')[0]
        if default_locale not in AVAILABLE_LOCALES:
            default_locale = DEFAULT_LOCALE

        epilog = """supported locales:

  {0}

  Faker can take a locale as an optional argument, to return localized data. If
  no locale argument is specified, the factory falls back to the user's OS
  locale as long as it is supported by at least one of the providers.
     - for this user, the default locale is {1}.

  If the optional argument locale and/or user's default locale is not available
  for the specified provider, the factory falls back to faker's default locale,
  which is {2}.

examples:

  $ faker address
  968 Bahringer Garden Apt. 722
  Kristinaland, NJ 09890

  $ faker -l de_DE address
  Samira-Niemeier-Allee 56
  94812 Biedenkopf

  $ faker profile ssn,birthdate
  {{'ssn': u'628-10-1085', 'birthdate': '2008-03-29'}}

  $ faker -r=3 -s=";" name
  Willam Kertzmann;
  Josiah Maggio;
  Gayla Schmitt;

""".format(', '.join(sorted(AVAILABLE_LOCALES)),
           default_locale,
           DEFAULT_LOCALE)

        formatter_class = argparse.RawDescriptionHelpFormatter
        parser = argparse.ArgumentParser(
            prog=self.prog_name,
            description='{0} version {1}'.format(self.prog_name, VERSION),
            epilog=epilog,
            formatter_class=formatter_class)

        parser.add_argument("--version", action="version",
                            version="%(prog)s {0}".format(VERSION))

        parser.add_argument('-v',
                            '--verbose',
                            action='store_true',
                            help="show INFO logging events instead "
                            "of CRITICAL, which is the default. These logging "
                            "events provide insight into localization of "
                            "specific providers.")

        parser.add_argument('-o', metavar="output",
                            type=argparse.FileType('w'),
                            default=sys.stdout,
                            help="redirect output to a file")

        parser.add_argument('-l', '--lang',
                            choices=AVAILABLE_LOCALES,
                            default=default_locale,
                            metavar='LOCALE',
                            help="specify the language for a localized "
                            "provider (e.g. de_DE)")
        parser.add_argument('-r', '--repeat',
                            default=1,
                            type=int,
                            help="generate the specified number of outputs")
        parser.add_argument('-s', '--sep',
                            default='\n',
                            help="use the specified separator after each "
                            "output")

        parser.add_argument('--seed', metavar='SEED',
                            type=int,
                            help="specify a seed for the random generator so "
                            "that results are repeatable. Also compatible "
                            "with 'repeat' option")

        parser.add_argument('-i',
                            '--include',
                            default=META_PROVIDERS_MODULES,
                            nargs='*',
                            help="list of additional custom providers to "
                            "user, given as the import path of the module "
                            "containing your Provider class (not the provider "
                            "class itself)")

        parser.add_argument('fake',
                            action='store',
                            nargs='?',
                            help="name of the fake to generate output for "
                                 "(e.g. profile)")

        parser.add_argument('fake_args',
                            metavar="fake argument",
                            action='store',
                            nargs='*',
                            help="optional arguments to pass to the fake "
                                 "(e.g. the profile fake takes an optional "
                                 "list of comma separated field names as the "
                                 "first argument)")

        arguments = parser.parse_args(self.argv[1:])

        if arguments.verbose:
            logging.basicConfig(level=logging.DEBUG)
        else:
            logging.basicConfig(level=logging.CRITICAL)

        random.seed(arguments.seed)
        seeds = random.sample(range(arguments.repeat*10), arguments.repeat)

        for i in range(arguments.repeat):

            print_doc(arguments.fake,
                      arguments.fake_args,
                      lang=arguments.lang,
                      output=arguments.o,
                      seed=seeds[i],
                      includes=arguments.include,
                      )
            print(arguments.sep, file=arguments.o)

            if not arguments.fake:
                # repeat not supported for all docs
                break

Response: This function creates a parser appropriate to the command - line arguments and runs it.


Instruction:
Given the following Python 3 function, write the documentation
def _check_digit(self):
        weights = (1 if x % 2 == 0 else 3 for x in range(12))
        body = ''.join([self.ean, self.group, self.registrant,
                        self.publication])
        remainder = sum(int(b) * w for b, w in zip(body, weights)) % 10
        diff = 10 - remainder
        check_digit = 0 if diff == 10 else diff
        return str(check_digit)

Response: Calculate the check digit for ISBN - 13.


Instruction:
Write a Python 3 function that can
check if a catch phrase is valid.

Response:
def _is_catch_phrase_valid(self, catch_phrase):
        """
        Validates a french catch phrase.

        :param catch_phrase: The catch phrase to validate.
        """
        for word in self.words_which_should_not_appear_twice:
            # Fastest way to check if a piece of word does not appear twice.
            begin_pos = catch_phrase.find(word)
            end_pos = catch_phrase.find(word, begin_pos + 1)

            if begin_pos != -1 and begin_pos != end_pos:
                return False

        return True


Instruction:
Make a summary of the following Python 3 code
def siret(self, max_sequential_digits=2):
        if max_sequential_digits > 4 or max_sequential_digits <= 0:
            max_sequential_digits = 2

        sequential_number = str(self.random_number(
            max_sequential_digits)).zfill(4)
        return self.numerify(self.siren() + ' ' + sequential_number + '#')

Response: Generates a random siret number.


Instruction:
Make a summary of the following Python 3 code
def remove_accents(value):
    search = 'ΆΈΉΊΌΎΏάέήίόύώΪϊΐϋΰ'
    replace = 'ΑΕΗΙΟΥΩαεηιουωΙιιυυ'

    def replace_accented_character(match):
        matched = match.group(0)
        if matched in search:
            return replace[search.find(matched)]
        return matched

    return re.sub(r'[{0}]+'.format(search), replace_accented_character, value)

Response: Removes accents from characters in the given string.


Instruction:
Explain what the following Python 3 code does
def latinize(value):
    def replace_double_character(match):
        search = ('Θ Χ Ψ '
                  'θ χ ψ '
                  'ΟΥ ΑΥ ΕΥ '
                  'Ου Αυ Ευ '
                  'ου αυ ευ').split()
        replace = ('TH CH PS '
                   'th ch ps '
                   'OU AU EU '
                   'Ou Au Eu '
                   'ou au eu').split()
        matched = match.group(0)
        if matched in search:
            return replace[search.index(matched)]
        return matched

    search = 'ΑΒΓΔΕΖΗΙΚΛΜΝΞΟΠΡΣΣΤΥΦΩαβγδεζηικλμνξοπρσςτυφω'
    replace = 'AVGDEZIIKLMNXOPRSSTUFOavgdeziiklmnxoprsstyfo'

    def replace_greek_character(match):
        matched = list(match.group(0))
        value = map(lambda l: replace[search.find(l)], matched)
        return ''.join(value)

    return re.sub(r'[{0}]+'.format(search),
                  replace_greek_character, re.sub(
        r'([ΘΧΨθχψ]+|ΟΥ|ΑΥ|ΕΥ|Ου|Αυ|Ευ|ου|αυ|ευ)',
        replace_double_character,
        remove_accents(value)))

Response: Converts greek letters to latin equivalents.


Instruction:
Create a Python 3 function to
return an Israeli identity number

Response:
def ssn(self):
        """
        Returns an Israeli identity number, known as Teudat Zehut ("tz").

        https://en.wikipedia.org/wiki/Israeli_identity_card
        """

        newID = str(self.generator.random.randrange(111111, 99999999))
        newID = newID.zfill(8)
        theSum = 0
        indexRange = [0, 2, 4, 6]
        for i in indexRange:
            digit = newID[i]
            num = int(digit)
            theSum = theSum + num
            num = int(newID[i + 1]) * 2
            if num > 9:
                num = int(str(num)[0]) + int(str(num)[1])
            theSum = theSum + num
        lastDigit = theSum % 10
        if lastDigit != 0:
            lastDigit = 10 - lastDigit

        return str(newID) + str(lastDigit)


Instruction:
Create a Python 3 function to
return an array of random words. for example Lorem ipsum dolor

Response:
def words(self, nb=3, ext_word_list=None, unique=False):
        """
        :returns: An array of random words. for example: ['Lorem', 'ipsum', 'dolor']

        Keyword arguments:
        :param nb: how many words to return
        :param ext_word_list: a list of words you would like to have instead of
            'Lorem ipsum'
        :param unique: If True, the returned word list will contain unique words

        :rtype: list
        """
        word_list = ext_word_list if ext_word_list else self.word_list
        if unique:
            return self.random_sample(word_list, length=nb)
        return self.random_choices(word_list, length=nb)


Instruction:
Explain what the following Python 3 code does
def sentence(self, nb_words=6, variable_nb_words=True, ext_word_list=None):
        if nb_words <= 0:
            return ''

        if variable_nb_words:
            nb_words = self.randomize_nb_elements(nb_words, min=1)

        words = self.words(nb=nb_words, ext_word_list=ext_word_list)
        words[0] = words[0].title()

        return self.word_connector.join(words) + self.sentence_punctuation

Response: Generates a random sentence of nb_words words.


Instruction:
Create a Python 3 function for
generating an array of sentences from the base class.

Response:
def sentences(self, nb=3, ext_word_list=None):
        """
        Generate an array of sentences
        :example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.']

        Keyword arguments:
        :param nb: how many sentences to return
        :param ext_word_list: a list of words you would like to have instead of
            'Lorem ipsum'.

        :rtype: list
        """
        return [self.sentence(ext_word_list=ext_word_list)
                for _ in range(0, nb)]


Instruction:
Write a Python 3 script to
return a single paragraph. For example a paragraph is Sapiente sunt omnis. Ut pariatur ad autem ducimus et Voluptas rem voluptas modi dolorem amet.

Response:
def paragraph(
            self,
            nb_sentences=3,
            variable_nb_sentences=True,
            ext_word_list=None):
        """
        :returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut
            pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.'

        Keyword arguments:
        :param nb_sentences: around how many sentences the paragraph should contain
        :param variable_nb_sentences: set to false if you want exactly ``nb``
            sentences returned, otherwise the result may include a number of
            sentences of ``nb`` +/-40% (with a minimum of 1)
        :param ext_word_list: a list of words you would like to have instead of
            'Lorem ipsum'.

        :rtype: str
        """
        if nb_sentences <= 0:
            return ''

        if variable_nb_sentences:
            nb_sentences = self.randomize_nb_elements(nb_sentences, min=1)

        para = self.word_connector.join(self.sentences(
            nb_sentences, ext_word_list=ext_word_list,
        ))

        return para


Instruction:
How would you code a function in Python 3 to
generate an array of paragraphs containing nb paragraphs.

Response:
def paragraphs(self, nb=3, ext_word_list=None):
        """
        Generate an array of paragraphs
        :example [paragraph1, paragraph2, paragraph3]
        :param nb: how many paragraphs to return
        :param ext_word_list: a list of words you would like to have instead of
            'Lorem ipsum'.

        :rtype: list
        """

        return [self.paragraph(ext_word_list=ext_word_list)
                for _ in range(0, nb)]


Instruction:
How would you explain what the following Python 3 function does
def text(self, max_nb_chars=200, ext_word_list=None):
        text = []
        if max_nb_chars < 5:
            raise ValueError(
                'text() can only generate text of at least 5 characters')

        if max_nb_chars < 25:
            # join words
            while not text:
                size = 0
                # determine how many words are needed to reach the $max_nb_chars
                # once;
                while size < max_nb_chars:
                    word = (self.word_connector if size else '') + \
                        self.word(ext_word_list=ext_word_list)
                    text.append(word)
                    size += len(word)
                text.pop()
            text[0] = text[0][0].upper() + text[0][1:]
            last_index = len(text) - 1
            text[last_index] += self.sentence_punctuation
        elif max_nb_chars < 100:
            # join sentences
            while not text:
                size = 0
                # determine how many sentences are needed to reach the
                # $max_nb_chars once
                while size < max_nb_chars:
                    sentence = (self.word_connector if size else '') + \
                        self.sentence(ext_word_list=ext_word_list)
                    text.append(sentence)
                    size += len(sentence)
                text.pop()
        else:
            # join paragraphs
            while not text:
                size = 0
                # determine how many paragraphs are needed to reach the
                # $max_nb_chars once
                while size < max_nb_chars:
                    paragraph = ('\n' if size else '') + \
                        self.paragraph(ext_word_list=ext_word_list)
                    text.append(paragraph)
                    size += len(paragraph)
                text.pop()

        return "".join(text)

Response: Generates a text string of the current language.


Instruction:
How would you explain what the following Python 3 function does
def city(self):
        pattern = self.random_element(self.city_formats)
        return self.generator.parse(pattern)

Response: returns a random city name


Instruction:
Make a summary of the following Python 3 code
def street_name(self):
        pattern = self.random_element(self.street_name_formats)
        return self.generator.parse(pattern)

Response: returns random street name


Instruction:
Here you have a function in Python 3, explain what it does
def street_address(self):
        pattern = self.random_element(self.street_address_formats)
        return self.generator.parse(pattern)

Response: returns random street address


Instruction:
How would you implement a function in Python 3 that
gets a random address

Response:
def address(self):
        """
        :example '791 Crist Parks, Sashabury, IL 86039-9874'
        """
        pattern = self.random_element(self.address_formats)
        return self.generator.parse(pattern)


Instruction:
Here you have a function in Python 3, explain what it does
def slugify(value, allow_dots=False, allow_unicode=False):
    if allow_dots:
        pattern = _re_pattern_allow_dots
    else:
        pattern = _re_pattern

    value = six.text_type(value)
    if allow_unicode:
        value = unicodedata.normalize('NFKC', value)
        value = pattern.sub('', value).strip().lower()
        return _re_spaces.sub('-', value)
    value = unicodedata.normalize('NFKD', value).encode(
        'ascii', 'ignore').decode('ascii')
    value = pattern.sub('', value).strip().lower()
    return _re_spaces.sub('-', value)

Response: Converts to lowercase removes non - word characters underscores and hyphens and converts spaces to hyphens.


Instruction:
Can you create a Python 3 function that
returns a random string from the postal_code_formats and replaces all question marks with a random letter and passes result to numerify to insert numbers

Response:
def postcode(self):
        """
        Replaces all question mark ('?') occurrences with a random letter
        from postal_code_formats then passes result to
        numerify to insert numbers
        """
        temp = re.sub(r'\?',
                      lambda x: self.postal_code_letter(),
                      self.random_element(self.postal_code_formats))
        return self.numerify(temp)


Instruction:
Write a Python 3 function that can
calculate and returns a control digit for given list of digits based on REGON standard.

Response:
def regon_checksum(digits):
    """
    Calculates and returns a control digit for given list of digits basing on REGON standard.
    """
    weights_for_check_digit = [8, 9, 2, 3, 4, 5, 6, 7]
    check_digit = 0

    for i in range(0, 8):
        check_digit += weights_for_check_digit[i] * digits[i]

    check_digit %= 11

    if check_digit == 10:
        check_digit = 0

    return check_digit


Instruction:
Here you have a function in Python 3, explain what it does
def local_regon_checksum(digits):
    weights_for_check_digit = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8]
    check_digit = 0

    for i in range(0, 13):
        check_digit += weights_for_check_digit[i] * digits[i]

    check_digit %= 11

    if check_digit == 10:
        check_digit = 0

    return check_digit

Response: Calculates and returns a control digit for given list of digits based on local REGON standard.


Instruction:
Explain what the following Python 3 code does
def company_vat_checksum(digits):
    weights_for_check_digit = [6, 5, 7, 2, 3, 4, 5, 6, 7]
    check_digit = 0

    for i in range(0, 9):
        check_digit += weights_for_check_digit[i] * digits[i]

    check_digit %= 11

    return check_digit

Response: Calculates and returns a control digit for given list of digits based on NIP standard.


Instruction:
Can you generate the documentation for the following Python 3 function
def regon(self):
        voivodeship_number = self.random_int(0, 49) * 2 + 1
        regon_digits = [int(voivodeship_number / 10), voivodeship_number % 10]

        for _ in range(6):
            regon_digits.append(self.random_digit())

        regon_digits.append(regon_checksum(regon_digits))

        return ''.join(str(digit) for digit in regon_digits)

Response: Returns 9 character Polish National Business Registry Number


Instruction:
Can you generate a brief explanation for the following Python 3 code
def local_regon(self):
        regon_digits = [int(digit) for digit in list(self.regon())]

        for _ in range(4):
            regon_digits.append(self.random_digit())

        regon_digits.append(local_regon_checksum(regon_digits))

        return ''.join(str(digit) for digit in regon_digits)

Response: Returns 14 character Polish National Business Registry Number local entity number.


Instruction:
Create a Python 3 function for
returning 10 character tax identification number

Response:
def company_vat(self):
        """
        Returns 10 character tax identification number,
        Polish: Numer identyfikacji podatkowej.

        https://pl.wikipedia.org/wiki/NIP
        """
        vat_digits = []

        for _ in range(3):
            vat_digits.append(self.random_digit_not_null())

        for _ in range(6):
            vat_digits.append(self.random_digit())

        check_digit = company_vat_checksum(vat_digits)

        # in this case we must generate a tax number again, because check_digit
        # cannot be 10
        if check_digit == 10:
            return self.company_vat()

        vat_digits.append(check_digit)

        return ''.join(str(digit) for digit in vat_digits)


Instruction:
How would you implement a function in Python 3 that
returns the checksum of CPF digits.

Response:
def checksum(digits):
    """
    Returns the checksum of CPF digits.
    References to the algorithm:
    https://pt.wikipedia.org/wiki/Cadastro_de_pessoas_f%C3%ADsicas#Algoritmo
    https://metacpan.org/source/MAMAWE/Algorithm-CheckDigits-v1.3.0/lib/Algorithm/CheckDigits/M11_004.pm
    """
    s = 0
    p = len(digits) + 1
    for i in range(0, len(digits)):
        s += digits[i] * p
        p -= 1

    reminder = s % 11
    if reminder == 0 or reminder == 1:
        return 0
    else:
        return 11 - reminder


Instruction:
Implement a Python 3 function for
generating the information required to create an ISBN - 10 or ISBN - 13 or ISO - 1 or ISO - 1 or ISO - 1 or ISO - 1 or ISO - 1 or ISO - 1 or ISO - 1.

Response:
def _body(self):
        """ Generate the information required to create an ISBN-10 or
        ISBN-13.
        """
        ean = self.random_element(RULES.keys())
        reg_group = self.random_element(RULES[ean].keys())

        # Given the chosen ean/group, decide how long the
        #   registrant/publication string may be.
        # We must allocate for the calculated check digit, so
        #   subtract 1
        reg_pub_len = ISBN.MAX_LENGTH - len(ean) - len(reg_group) - 1

        # Generate a registrant/publication combination
        reg_pub = self.numerify('#' * reg_pub_len)

        # Use rules to separate the registrant from the publication
        rules = RULES[ean][reg_group]
        registrant, publication = self._registrant_publication(reg_pub, rules)
        return [ean, reg_group, registrant, publication]


Instruction:
Can you create a Python 3 function that
separates the registration from the publication in a given string.

Response:
def _registrant_publication(reg_pub, rules):
        """ Separate the registration from the publication in a given
        string.
        :param reg_pub: A string of digits representing a registration
            and publication.
        :param rules: A list of RegistrantRules which designate where
            to separate the values in the string.
        :returns: A (registrant, publication) tuple of strings.
        """
        for rule in rules:
            if rule.min <= reg_pub <= rule.max:
                reg_len = rule.registrant_length
                break
        else:
            raise Exception('Registrant/Publication not found in registrant '
                            'rule list.')
        registrant, publication = reg_pub[:reg_len], reg_pub[reg_len:]
        return registrant, publication


Instruction:
How would you explain what the following Python 3 function does
def ssn(self):
        digits = []

        # Number of days between 1899-12-31 and a birth date
        for digit in str((self.generator.date_object() -
                          date(1899, 12, 31)).days):
            digits.append(int(digit))

        # Person's sequence number
        for _ in range(4):
            digits.append(self.random_int(0, 9))

        checksum = (digits[0] * -1 + digits[1] * 5 + digits[2] * 7 + digits[3] * 9 +
                    digits[4] * 4 + digits[5] * 6 + digits[6] * 10 + digits[7] * 5 +
                    digits[8] * 7)
        # Remainder of a checksum divided by 11 or 1 if it equals to 10
        digits.append(checksum % 11 % 10)

        return ''.join(str(digit) for digit in digits)

Response: Generate a random S - N string.


Instruction:
Given the following Python 3 function, write the documentation
def state_abbr(self, include_territories=True):
        if include_territories:
            self.random_element(self.states_and_territories_abbr)
        return self.random_element(self.states_abbr)

Response: Returns a random state or territory abbreviation.


Instruction:
Write a Python 3 script for
generating a random string of upper and lowercase letters.

Response:
def pystr(self, min_chars=None, max_chars=20):
        """
        Generates a random string of upper and lowercase letters.
        :type min_chars: int
        :type max_chars: int
        :return: String. Random of random length between min and max characters.
        """
        if min_chars is None:
            return "".join(self.random_letters(length=max_chars))
        else:
            assert (
                max_chars >= min_chars), "Maximum length must be greater than or equal to minium length"
            return "".join(
                self.random_letters(
                    length=self.generator.random.randint(min_chars, max_chars),
                ),
            )


Instruction:
Explain what the following Python 3 code does
def pydict(self, nb_elements=10, variable_nb_elements=True, *value_types):
        if variable_nb_elements:
            nb_elements = self.randomize_nb_elements(nb_elements, min=1)

        return dict(zip(
            self.generator.words(nb_elements),
            self._pyiterable(nb_elements, False, *value_types),
        ))

Response: Returns a dictionary of the n elements of the class.


Instruction:
Can you tell what is the following Python 3 function doing
def postcode(self):
        postcode = ''
        pattern = self.random_element(self.postcode_formats)
        for placeholder in pattern:
            postcode += self.random_element(self._postcode_sets[placeholder])
        return postcode

Response: Generate a random postcode from the set of available postcodes.


Instruction:
Can you tell what is the following Python 3 function doing
def ssn(self, dob=None, gender=None):
        # Hungarian SSNs consist of 11 decimal characters, of the following
        # schema:
        #
        #       M EEHHNN SSSK
        #       ↑    ↑    ↑ ↑
        #  gender  bday ser check digit
        #
        #
        #  The M (gender) character
        #  ------------------------
        #
        #  Born <= 1999        Born > 1999
        #  Male  Female        Male Female
        #   1      2             3     4
        #
        #  It also includes information on original citizenship,but this is
        #  ignored for the sake of simplicity.
        #
        #  Birthday
        #  --------
        #
        #  Simply encoded as EEHHNN.
        #
        #
        #  Serial
        #  ------
        #
        #  These digits differentiate persons born on the same date.
        #
        #
        #  Check digit
        #  -----------
        #
        #  For those born before 1996:
        #
        #  k11 = (1k1 + 2k2 + 3k3... 10k10) mod 11
        #
        #  That is, you multiply each digit with its ordinal, add it up and
        #  take it mod 11. After 1996:
        #
        #  k11 = (10k1 + 9k2 + 8k3... 1k10) mod 11
        #

        if dob:
            E = int(dob[0:2])
            H = int(dob[2:4])
            N = int(dob[4:6])

            if E <= 17:
                # => person born after '99 in all likelihood...
                if gender:
                    if gender.upper() == "F":
                        M = 4
                    elif gender.upper() == "M":
                        M = 3
                    else:
                        raise ValueError("Unknown gender - specify M or F.")
                else:
                    M = self.generator.random_int(3, 4)
            else:
                # => person born before '99.
                if gender:
                    if gender.upper() == "F":
                        M = 2
                    elif gender.upper() == "M":
                        M = 1
                    else:
                        raise ValueError("Unknown gender - specify M or F.")
                else:
                    M = self.generator.random_int(1, 2)
        elif gender:
            # => assume statistically that the person will be born before '99.
            E = self.generator.random_int(17, 99)
            H = self.generator.random_int(1, 12)
            N = self.generator.random_int(1, 30)

            if gender.upper() == "F":
                M = 2
            elif gender.upper() == "M":
                M = 1
            else:
                raise ValueError("Unknown gender - specify M or F")
        else:
            M = self.generator.random_int(1, 2)
            E = self.generator.random_int(17, 99)
            H = self.generator.random_int(1, 12)
            N = self.generator.random_int(1, 30)

        H = zfix(H)
        N = zfix(N)
        S = "{}{}{}".format(self.generator.random_digit(
        ), self.generator.random_digit(), self.generator.random_digit())

        vdig = "{M}{E}{H}{N}{S}".format(M=M, E=E, H=H, N=N, S=S)

        if 17 < E < 97:
            cum = [(k + 1) * int(v) for k, v in enumerate(vdig)]
        else:
            cum = [(10 - k) * int(v) for k, v in enumerate(vdig)]

        K = fmod(reduce(lambda x, y: x + y, cum), 11)

        return vdig + str(int(K))

Response: Generates Hungarian SSN equivalent for the given date and gender.


Instruction:
Write a Python 3 script for
returning a random postcode in the state

Response:
def postcode_in_state(self, state_abbr=None):
        """
        :example '4703'
        """
        if state_abbr is None:
            state_abbr = self.random_element(self.states_abbr)

        if state_abbr in self.states_abbr:
            postcode = "%d" % (self.generator.random.randint(
                            self.states_postcode[state_abbr][0],
                            self.states_postcode[state_abbr][1]))

            if len(postcode) == 3:
                postcode = "0%s" % postcode

            return postcode

        else:
            raise Exception('State Abbreviation not found in list')


Instruction:
Explain what the following Python 3 code does
def ssn(self):
        # see http://nl.wikipedia.org/wiki/Burgerservicenummer (in Dutch)
        def _checksum(digits):
            factors = (9, 8, 7, 6, 5, 4, 3, 2, -1)
            s = 0
            for i in range(len(digits)):
                s += digits[i] * factors[i]
            return s

        while True:
            # create an array of first 8 elements initialized randomly
            digits = self.generator.random.sample(range(10), 8)
            # sum those 8 digits according to (part of) the "11-proef"
            s = _checksum(digits)
            # determine the last digit to make it qualify the test
            digits.append((s % 11) % 10)
            # repeat steps until it does qualify the test
            if 0 == (_checksum(digits) % 11):
                break

        # build the resulting BSN
        bsn = "".join([str(e) for e in digits])
        # finally return our random but valid BSN
        return bsn

Response: Returns a 9 digits Dutch SSN called burgerservicenummer ( BSN ).


Instruction:
How would you explain what the following Python 3 function does
def checksum(digits):
    remainder = 10
    for digit in digits:
        remainder = (remainder + digit) % 10
        if remainder == 0:
            remainder = 10
        remainder = (remainder * 2) % 11

    control_digit = 11 - remainder
    if control_digit == 10:
        control_digit = 0
    return control_digit

Response: Calculate and return control digit for given list of digits based on ISO7064 MOD 11 10 standard.


Instruction:
Write a Python 3 function for
calculating the checksum of Estonian personal identity code.

Response:
def checksum(digits):
    """Calculate checksum of Estonian personal identity code.

    Checksum is calculated with "Modulo 11" method using level I or II scale:
    Level I scale: 1 2 3 4 5 6 7 8 9 1
    Level II scale: 3 4 5 6 7 8 9 1 2 3

    The digits of the personal code are multiplied by level I scale and summed;
    if remainder of modulo 11 of the sum is less than 10, checksum is the
    remainder.
    If remainder is 10, then level II scale is used; checksum is remainder if
    remainder < 10 or 0 if remainder is 10.

    See also https://et.wikipedia.org/wiki/Isikukood
    """
    sum_mod11 = sum(map(operator.mul, digits, Provider.scale1)) % 11
    if sum_mod11 < 10:
        return sum_mod11
    sum_mod11 = sum(map(operator.mul, digits, Provider.scale2)) % 11
    return 0 if sum_mod11 == 10 else sum_mod11


Instruction:
Make a summary of the following Python 3 code
def ssn(self, min_age=16, max_age=90):
        age = datetime.timedelta(
            days=self.generator.random.randrange(
                min_age * 365, max_age * 365))
        birthday = datetime.date.today() - age
        if birthday.year < 2000:
            ik = self.generator.random.choice(('3', '4'))
        elif birthday.year < 2100:
            ik = self.generator.random.choice(('5', '6'))
        else:
            ik = self.generator.random.choice(('7', '8'))

        ik += "%02d%02d%02d" % ((birthday.year % 100), birthday.month,
                                birthday.day)
        ik += str(self.generator.random.randrange(0, 999)).zfill(3)
        return ik + str(checksum([int(ch) for ch in ik]))

Response: Generate a random SSS number.


Instruction:
Make a summary of the following Python 3 code
def coordinate(self, center=None, radius=0.001):
        if center is None:
            return Decimal(str(self.generator.random.randint(-180000000, 180000000) / 1000000.0)).quantize(
                Decimal(".000001"),
            )
        else:
            center = float(center)
            radius = float(radius)
            geo = self.generator.random.uniform(center - radius, center + radius)
            return Decimal(str(geo)).quantize(Decimal(".000001"))

Response: Return a random coordinate of the class.


Instruction:
Write a Python 3 script to
return a random latlng from the list of locations known to exist on land in a country specified by country_code.

Response:
def local_latlng(self, country_code='US', coords_only=False):
        """Returns a location known to exist on land in a country specified by `country_code`.
        Defaults to 'en_US'. See the `land_coords` list for available locations/countries.
        """
        results = [loc for loc in self.land_coords if loc[3] == country_code]
        if results:
            place = self.random_element(results)
            return (place[0], place[1]) if coords_only else place


Instruction:
Can you tell what is the following Python 3 function doing
def location_on_land(self, coords_only=False):
        place = self.random_element(self.land_coords)
        return (place[0], place[1]) if coords_only else place

Response: Returns a random tuple specifying a coordinate set guaranteed to exist on land.


Instruction:
How would you explain what the following Python 3 function does
def checksum(digits):
    weights_for_check_digit = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7]
    check_digit = 0

    for i in range(0, 10):
        check_digit += weights_for_check_digit[i] * digits[i]

    check_digit %= 10

    return check_digit

Response: Calculates and returns a control digit for given list of digits based on PESEL standard.


Instruction:
Given the following Python 3 function, write the documentation
def calculate_month(birth_date):
    year = int(birth_date.strftime('%Y'))
    month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20

    return month

Response: Calculates and returns a month number based on PESEL standard.


Instruction:
Write a Python 3 function for
returning 11 character Polish national identity code.

Response:
def ssn(self):
        """
        Returns 11 character Polish national identity code (Public Electronic Census System,
        Polish: Powszechny Elektroniczny System Ewidencji Ludności - PESEL).

        It has the form YYMMDDZZZXQ, where YYMMDD is the date of birth (with century
        encoded in month field), ZZZ is the personal identification number, X denotes sex
        (even for females, odd for males) and Q is a parity number.

        https://en.wikipedia.org/wiki/National_identification_number#Poland
        """
        birth_date = self.generator.date_time()

        year_without_century = int(birth_date.strftime('%y'))
        month = calculate_month(birth_date)
        day = int(birth_date.strftime('%d'))

        pesel_digits = [
            int(year_without_century / 10),
            year_without_century % 10,
            int(month / 10),
            month % 10,
            int(day / 10), day % 10,
        ]

        for _ in range(4):
            pesel_digits.append(self.random_digit())

        pesel_digits.append(checksum(pesel_digits))

        return ''.join(str(digit) for digit in pesel_digits)


Instruction:
Implement a function in Python 3 to
return a 13 digits Swiss SSN named AHV or AVS and French and Italian

Response:
def ssn(self):
        """
        Returns a 13 digits Swiss SSN named AHV (German) or
                                            AVS (French and Italian)
        See: http://www.bsv.admin.ch/themen/ahv/00011/02185/
        """
        def _checksum(digits):
            evensum = sum(digits[:-1:2])
            oddsum = sum(digits[1::2])
            return (10 - ((evensum + oddsum * 3) % 10)) % 10

        digits = [7, 5, 6]
        # create an array of first 9 elements initialized randomly
        digits += self.generator.random.sample(range(10), 9)
        # determine the last digit to make it qualify the test
        digits.append(_checksum(digits))
        # repeat steps until it does qualify the test

        digits = ''.join([str(d) for d in digits])
        ssn = digits[:3] + '.' \
                         + digits[3:7] + '.' \
                         + digits[7:11] + '.' \
                         + digits[11:]
        return ssn


Instruction:
How would you code a function in Python 3 to
return Swiss UID number of the VAT in the current locale.

Response:
def vat_id(self):
        """
        :return: Swiss UID number
        """
        def _checksum(digits):
            code = ['8', '6', '4', '2', '3', '5', '9', '7']
            remainder = 11-(sum(map(lambda x, y: int(x) * int(y), code, digits)) % 11)
            if remainder == 10:
                return 0
            elif remainder == 11:
                return 5
            return remainder

        vat_id = self.bothify('########')
        return 'CHE' + vat_id + str(_checksum(vat_id))


Instruction:
Can you tell what is the following Python 3 function doing
def random_int(self, min=0, max=9999, step=1):
        return self.generator.random.randrange(min, max + 1, step)

Response: Returns a random integer between two values.


Instruction:
Can you write a function in Python 3 where it
returns a random digit or an empty string.

Response:
def random_digit_or_empty(self):
        """
        Returns a random digit/number
        between 0 and 9 or an empty string.
        """
        if self.generator.random.randint(0, 1):
            return self.generator.random.randint(0, 9)
        else:
            return ''


Instruction:
Create a Python 3 function to
return a random non - zero digit or an empty string.

Response:
def random_digit_not_null_or_empty(self):
        """
        Returns a random non-zero digit/number
        between 1 and 9 or and empty string.
        """
        if self.generator.random.randint(0, 1):
            return self.generator.random.randint(1, 9)
        else:
            return ''


Instruction:
How would you explain what the following Python 3 function does
def random_number(self, digits=None, fix_len=False):
        if digits is None:
            digits = self.random_digit()
        if fix_len:
            return self.generator.random.randint(
                pow(10, digits - 1), pow(10, digits) - 1)
        else:
            return self.generator.random.randint(0, pow(10, digits) - 1)

Response: Returns a random number with 1 digit or fixed length number


Instruction:
Here you have a function in Python 3, explain what it does
def random_letter(self):
        return self.generator.random.choice(
            getattr(string, 'letters', string.ascii_letters))

Response: Returns a random letter between a - z and A - Z.


Instruction:
Can you implement a function in Python 3 that
returns a random letter between a - z and A - Z.

Response:
def random_letters(self, length=16):
        """Returns a random letter (between a-z and A-Z)."""
        return self.random_choices(
            getattr(string, 'letters', string.ascii_letters),
            length=length,
        )


Instruction:
Can you implement a function in Python 3 that
returns a list of random non - unique elements from a passed object.

Response:
def random_choices(self, elements=('a', 'b', 'c'), length=None):
        """
        Returns a list of random, non-unique elements from a passed object.

        If `elements` is a dictionary, the value will be used as
        a weighting element. For example::

            random_element({"{{variable_1}}": 0.5, "{{variable_2}}": 0.2, "{{variable_3}}": 0.2, "{{variable_4}}": 0.1})

        will have the following distribution:
            * `variable_1`: 50% probability
            * `variable_2`: 20% probability
            * `variable_3`: 20% probability
            * `variable_4`: 10% probability

        """
        return self.random_elements(elements, length, unique=False)


Instruction:
Can you write a function in Python 3 where it
returns a list of random unique elements for the specified length.

Response:
def random_sample(self, elements=('a', 'b', 'c'), length=None):
        """
        Returns a list of random unique elements for the specified length.
        Multiple occurrences of the same value increase its probability to be in the output.
        """
        return self.random_elements(elements, length, unique=True)


Instruction:
Here you have a function in Python 3, explain what it does
def randomize_nb_elements(
            self,
            number=10,
            le=False,
            ge=False,
            min=None,
            max=None):
        """
        Returns a random value near number.

        :param number: value to which the result must be near
        :param le: result must be lower or equal to number
        :param ge: result must be greater or equal to number
        :returns: a random int near number
        """
        if le and ge:
            return number
        _min = 100 if ge else 60
        _max = 100 if le else 140
        nb = int(number * self.generator.random.randint(_min, _max) / 100)
        if min is not None and nb < min:
            nb = min
        if max is not None and nb > min:
            nb = max
        return nb

Response: Returns a random value near number.


Instruction:
Here you have a function in Python 3, explain what it does
def numerify(self, text='###'):
        text = _re_hash.sub(
            lambda x: str(self.random_digit()),
            text)
        text = _re_perc.sub(
            lambda x: str(self.random_digit_not_null()),
            text)
        text = _re_excl.sub(
            lambda x: str(self.random_digit_or_empty()),
            text)
        text = _re_at.sub(
            lambda x: str(self.random_digit_not_null_or_empty()),
            text)
        return text

Response: Replaces all placeholders in given text with randomized values.


Instruction:
Write a Python 3 script to
replace all question mark occurrences with a random letter.

Response:
def lexify(self, text='????', letters=string.ascii_letters):
        """
        Replaces all question mark ('?') occurrences with a random letter.

        :param text: string to be parsed
        :param letters: a set of letters to choose from.
        :returns: string with all letter placeholders filled in
        """
        return _re_qm.sub(lambda x: self.random_element(letters), text)


Instruction:
How would you code a function in Python 3 to
replace all placeholders with random numbers and letters.

Response:
def bothify(self, text='## ??', letters=string.ascii_letters):
        """
        Replaces all placeholders with random numbers and letters.

        :param text: string to be parsed
        :returns: string with all numerical and letter placeholders filled in
        """
        return self.lexify(self.numerify(text), letters=letters)


Instruction:
Create a Python 3 function for
replacing all circumflex ('^') occurrences with a random hexadecimal character.

Response:
def hexify(self, text='^^^^', upper=False):
        """
        Replaces all circumflex ('^') occurrences with a random
        hexadecimal character.

        :param text: string to be parsed
        :param upper: Format as uppercase hexadecimal
        :returns: string with all letter placeholders filled in
        """
        letters = string.hexdigits[:-6]
        if upper:
            letters = letters.upper()
        return _re_cir.sub(lambda x: self.random_element(letters), text)


Instruction:
Create a Python 3 function for
calculating the checksum of Norwegian personal identity code.

Response:
def checksum(digits, scale):
    """
    Calculate checksum of Norwegian personal identity code.

    Checksum is calculated with "Module 11" method using a scale.
    The digits of the personal code are multiplied by the corresponding
    number in the scale and summed;
    if remainder of module 11 of the sum is less than 10, checksum is the
    remainder.
    If remainder is 0, the checksum is 0.

    https://no.wikipedia.org/wiki/F%C3%B8dselsnummer
    """
    chk_nbr = 11 - (sum(map(operator.mul, digits, scale)) % 11)
    if chk_nbr == 11:
        return 0
    return chk_nbr


Instruction:
Given the following Python 3 function, write the documentation
def ssn(self, dob=None, gender=None):

        if dob:
            birthday = datetime.datetime.strptime(dob, '%Y%m%d')
        else:
            age = datetime.timedelta(
                days=self.generator.random.randrange(18 * 365, 90 * 365))
            birthday = datetime.datetime.now() - age
        if not gender:
            gender = self.generator.random.choice(('F', 'M'))
        elif gender not in ('F', 'M'):
            raise ValueError('Gender must be one of F or M.')

        while True:
            if 1900 <= birthday.year <= 1999:
                suffix = str(self.generator.random.randrange(0, 49))
            elif 1854 <= birthday.year <= 1899:
                suffix = str(self.generator.random.randrange(50, 74))
            elif 2000 <= birthday.year <= 2039:
                suffix = str(self.generator.random.randrange(50, 99))
            elif 1940 <= birthday.year <= 1999:
                suffix = str(self.generator.random.randrange(90, 99))
            if gender == 'F':
                gender_num = self.generator.random.choice((0, 2, 4, 6, 8))
            elif gender == 'M':
                gender_num = self.generator.random.choice((1, 3, 5, 7, 9))
            pnr = birthday.strftime('%d%m%y') + suffix.zfill(2) + str(gender_num)
            pnr_nums = [int(ch) for ch in pnr]
            k1 = checksum(Provider.scale1, pnr_nums)
            k2 = checksum(Provider.scale2, pnr_nums + [k1])
            # Checksums with a value of 10 is rejected.
            # https://no.wikipedia.org/wiki/F%C3%B8dselsnummer
            if k1 == 10 or k2 == 10:
                continue
            pnr += '{}{}'.format(k1, k2)
            return pnr

Response: Returns a 11 character Norwegian personal identity code.


Instruction:
Here you have a function in Python 3, explain what it does
def nie(self):

        first_chr = random.randrange(0, 3)
        doi_body = str(random.randrange(0, 10000000)).zfill(7)
        control = self._calculate_control_doi(str(first_chr) + doi_body)
        return "XYZ"[first_chr] + doi_body + control

Response: a random Spanish NIE


Instruction:
Write a Python 3 function for
generating a random NIF control DOI.

Response:
def nif(self):
        """
        https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal
        :return: NIF
        """

        nie_body = str(random.randrange(0, 100000000))  # generate a number of a maximum of 8 characters long
        return nie_body.zfill(8) + self._calculate_control_doi(nie_body)


Instruction:
How would you code a function in Python 3 to
generate a random Spanish CIF.

Response:
def cif(self):
        """
        https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
        :return: a random Spanish CIF
        """

        first_chr = random.choice('ABCDEFGHJNPQRSUVW')
        doi_body = str(random.randrange(0, 10000000)).zfill(7)
        cif = first_chr + doi_body
        return cif + self._calculate_control_cif(cif)


Instruction:
How would you explain what the following Python 3 function does
def doi(self):

        return random.choice([self.cif, self.nie, self.nif])()

Response: Returns a random Spanish CIF or NIE or NIFVersion.


Instruction:
Implement a Python 3 function for
calculating the letter that corresponds to the end of a CIF and returns the control character that corresponds to the end of a CIF.

Response:
def _calculate_control_cif(cls, cif):
        """
        Calculate the letter that corresponds to the end of a CIF
        :param cif: calculated value so far needing a control character
        :return: CIF control character

        Code was converted from the minified js of: https://generadordni.es/
        """

        sum_ = 0
        first_chr, cif_value = cif[0], cif[1:]
        for index, char in enumerate(cif_value):
            if index % 2:
                sum_ += int(char)
            else:
                sum_ += sum(map(int, str(int(char) * 2)))
        if sum_ > 10:
            sum_ = int(str(sum_)[-1])
        else:
            sum_ = sum_
        sum_ = 10 - (sum_ % 10)

        if first_chr in ['F', 'J', 'K', 'N', 'P', 'Q', 'R', 'S', 'U', 'V', 'W']:
            return chr(64 + sum_)
        elif first_chr in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'L', 'M']:
            if sum_ == 10:
                sum_ = 0
            return str(sum_)
        else:  # K, L, M  # pragma: no cover
            # Old format that is no longer used, here for full compatability
            return cls._calculate_control_doi(cif)


Instruction:
Write a Python 3 script for
generating a random 11 character Finnish personal identity code.

Response:
def ssn(self, min_age=0, max_age=105, artificial=False):
        """
        Returns 11 character Finnish personal identity code (Henkilötunnus,
        HETU, Swedish: Personbeteckning). This function assigns random
        gender to person.

        HETU consists of eleven characters of the form DDMMYYCZZZQ, where
        DDMMYY is the date of birth, C the century sign, ZZZ the individual
        number and Q the control character (checksum). The sign for the
        century is either + (1800–1899), - (1900–1999), or A (2000–2099).
        The individual number ZZZ is odd for males and even for females.
        For people born in Finland its range is 002-899
        (larger numbers may be used in special cases).
        An example of a valid code is 311280-888Y.

        https://en.wikipedia.org/wiki/National_identification_number#Finland
        """
        def _checksum(hetu):
            checksum_characters = "0123456789ABCDEFHJKLMNPRSTUVWXY"
            return checksum_characters[int(hetu) % 31]

        age = datetime.timedelta(
            days=self.generator.random.randrange(min_age * 365, max_age * 365))
        birthday = datetime.date.today() - age
        hetu_date = "%02d%02d%s" % (
            birthday.day, birthday.month, str(birthday.year)[-2:])
        range = (900, 999) if artificial is True else (2, 899)
        suffix = str(self.generator.random.randrange(*range)).zfill(3)
        checksum = _checksum(hetu_date + suffix)
        separator = self._get_century_code(birthday.year)
        hetu = "".join([hetu_date, separator, suffix, checksum])
        return hetu


Instruction:
Write a Python 3 function for
returning the century code for a given year

Response:
def _get_century_code(year):
        """Returns the century code for a given year"""
        if 2000 <= year < 3000:
            separator = 'A'
        elif 1900 <= year < 2000:
            separator = '-'
        elif 1800 <= year < 1900:
            separator = '+'
        else:
            raise ValueError('Finnish SSN do not support people born before the year 1800 or after the year 2999')
        return separator


Instruction:
Write a Python 3 script for
returning a 10 digit Swedish SSN and Personnummer.

Response:
def ssn(self, min_age=18, max_age=90):
        """
        Returns a 10 digit Swedish SSN, "Personnummer".

        It consists of 10 digits in the form YYMMDD-SSGQ, where
        YYMMDD is the date of birth, SSS is a serial number
        and Q is a control character (Luhn checksum).

        http://en.wikipedia.org/wiki/Personal_identity_number_(Sweden)
        """
        def _luhn_checksum(number):
            def digits_of(n):
                return [int(d) for d in str(n)]
            digits = digits_of(number)
            odd_digits = digits[-1::-2]
            even_digits = digits[-2::-2]
            checksum = 0
            checksum += sum(odd_digits)
            for d in even_digits:
                checksum += sum(digits_of(d * 2))
            return checksum % 10

        def _calculate_luhn(partial_number):
            check_digit = _luhn_checksum(int(partial_number) * 10)
            return check_digit if check_digit == 0 else 10 - check_digit

        age = datetime.timedelta(
            days=self.generator.random.randrange(min_age * 365, max_age * 365))
        birthday = datetime.datetime.now() - age
        pnr_date = birthday.strftime('%y%m%d')
        suffix = str(self.generator.random.randrange(0, 999)).zfill(3)
        luhn_checksum = str(_calculate_luhn(pnr_date + suffix))
        pnr = '{0}-{1}{2}'.format(pnr_date, suffix, luhn_checksum)

        return pnr


Instruction:
Can you write a function in Python 3 where it
generates a basic profile with personal informations

Response:
def simple_profile(self, sex=None):
        """
        Generates a basic profile with personal informations
        """
        SEX = ["F", "M"]
        if sex not in SEX:
            sex = self.random_element(SEX)
        if sex == 'F':
            name = self.generator.name_female()
        elif sex == 'M':
            name = self.generator.name_male()
        return {
            "username": self.generator.user_name(),
            "name": name,
            "sex": sex,
            "address": self.generator.address(),
            "mail": self.generator.free_email(),
            "birthdate": self.generator.date_of_birth(),
        }


Instruction:
Can you write a function in Python 3 where it
generates a complete profile.

Response:
def profile(self, fields=None, sex=None):
        """
        Generates a complete profile.
        If "fields" is not empty, only the fields in the list will be returned
        """
        if fields is None:
            fields = []

        d = {
            "job": self.generator.job(),
            "company": self.generator.company(),
            "ssn": self.generator.ssn(),
            "residence": self.generator.address(),
            "current_location": (self.generator.latitude(), self.generator.longitude()),
            "blood_group": "".join(self.random_element(list(itertools.product(["A", "B", "AB", "O"], ["+", "-"])))),
            "website": [self.generator.url() for _ in range(1, self.random_int(2, 5))],
        }

        d = dict(d, **self.generator.simple_profile(sex))
        # field selection
        if len(fields) > 0:
            d = {k: v for k, v in d.items() if k in fields}

        return d


Instruction:
Explain what the following Python 3 code does
def name(self):
        pattern = self.random_element(self.formats)
        return self.generator.parse(pattern)

Response: Get a random name for the current locale.


Instruction:
Make a summary of the following Python 3 code
def new_datetime(d):
    kw = [d.year, d.month, d.day]
    if isinstance(d, real_datetime):
        kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
    return datetime(*kw)

Response: Generate a safe datetime from a datetime. date or datetime. datetime object.


Instruction:
Make a summary of the following Python 3 code
def bs(self):
        result = []
        for word_list in self.bsWords:
            result.append(self.random_element(word_list))

        return " ".join(result)

Response: example integral extensible convergence


Instruction:
Write a Python 3 function for
returning a random mime type

Response:
def mime_type(self, category=None):
        """
        :param category: application|audio|image|message|model|multipart|text|video
        """
        category = category if category else self.random_element(
            list(self.mime_types.keys()))
        return self.random_element(self.mime_types[category])


Instruction:
Make a summary of the following Python 3 code
def file_name(self, category=None, extension=None):
        extension = extension if extension else self.file_extension(category)
        filename = self.generator.word()
        return '{0}.{1}'.format(filename, extension)

Response: returns a unique filename for the current locale


Instruction:
Can you generate a brief explanation for the following Python 3 code
def file_extension(self, category=None):
        category = category if category else self.random_element(
            list(self.file_extensions.keys()))
        return self.random_element(self.file_extensions[category])

Response: returns a random file extension


Instruction:
How would you explain what the following Python 3 function does
def file_path(self, depth=1, category=None, extension=None):
        file = self.file_name(category, extension)
        path = "/{0}".format(file)
        for _ in range(0, depth):
            path = "/{0}{1}".format(self.generator.word(), path)
        return path

Response: returns the path to the file


Instruction:
Explain what the following Python 3 code does
def unix_device(self, prefix=None):
        prefix = prefix or self.random_element(self.unix_device_prefixes)
        suffix = self.random_element(string.ascii_lowercase)
        path = '/dev/%s%s' % (prefix, suffix)
        return path

Response: returns a random unix device path


Instruction:
Write a Python 3 script to
return a random unix partition of the system

Response:
def unix_partition(self, prefix=None):
        """
        :param prefix: sd|vd|xvd
        """
        path = self.unix_device(prefix=prefix)
        path += str(self.random_digit())
        return path


Instruction:
Write a Python 3 script to
generate a random United States Individual Taxpayer Identification Number ( ITIN.

Response:
def itin(self):
        """Generate a random United States Individual Taxpayer Identification Number (ITIN).

        An United States Individual Taxpayer Identification Number
        (ITIN) is a tax processing number issued by the Internal
        Revenue Service. It is a nine-digit number that always begins
        with the number 9 and has a range of 70-88 in the fourth and
        fifth digit. Effective April 12, 2011, the range was extended
        to include 900-70-0000 through 999-88-9999, 900-90-0000
        through 999-92-9999 and 900-94-0000 through 999-99-9999.
        https://www.irs.gov/individuals/international-taxpayers/general-itin-information
        """

        area = self.random_int(min=900, max=999)
        serial = self.random_int(min=0, max=9999)

        # The group number must be between 70 and 99 inclusively but not 89 or 93
        group = random.choice([x for x in range(70, 100) if x not in [89, 93]])

        itin = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial)
        return itin


Instruction:
Make a summary of the following Python 3 code
def ein(self):

        # Only certain EIN Prefix values are assigned:
        #
        # https://www.irs.gov/businesses/small-businesses-self-employed/how-eins-are-assigned-and-valid-ein-prefixes

        ein_prefix_choices = [
            '01',
            '02',
            '03',
            '04',
            '05',
            '06',
            '10',
            '11',
            '12',
            '13',
            '14',
            '15',
            '16',
            '20',
            '21',
            '22',
            '23',
            '24',
            '25',
            '26',
            '27',
            '30',
            '31',
            '32',
            '33',
            '34',
            '35',
            '36',
            '37',
            '38',
            '39',
            '40',
            '41',
            '42',
            '43',
            '44',
            '45',
            '46',
            '47',
            '48',
            '50',
            '51',
            '52',
            '53',
            '54',
            '55',
            '56',
            '57',
            '58',
            '59',
            '60',
            '61',
            '62',
            '63',
            '64',
            '65',
            '66',
            '67',
            '68',
            '71',
            '72',
            '73',
            '74',
            '75',
            '76',
            '77',
            '80',
            '81',
            '82',
            '83',
            '84',
            '85',
            '86',
            '87',
            '88',
            '90',
            '91',
            '92',
            '93',
            '94',
            '95',
            '98',
            '99']

        ein_prefix = random.choice(ein_prefix_choices)
        sequence = self.random_int(min=0, max=9999999)

        ein = "{0:s}-{1:07d}".format(ein_prefix, sequence)
        return ein

Response:
Generate a random United States Employer Identification Number and is
        .


Instruction:
Can you generate the documentation for the following Python 3 function
def ssn(self, taxpayer_identification_number_type=SSN_TYPE):

        if taxpayer_identification_number_type == self.ITIN_TYPE:
            return self.itin()
        elif taxpayer_identification_number_type == self.EIN_TYPE:
            return self.ein()
        elif taxpayer_identification_number_type == self.SSN_TYPE:

            # Certain numbers are invalid for United States Social Security
            # Numbers. The area (first 3 digits) cannot be 666 or 900-999.
            # The group number (middle digits) cannot be 00. The serial
            # (last 4 digits) cannot be 0000.

            area = self.random_int(min=1, max=899)
            if area == 666:
                area += 1
            group = self.random_int(1, 99)
            serial = self.random_int(1, 9999)

            ssn = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial)
            return ssn

        else:
            raise ValueError("taxpayer_identification_number_type must be one of 'SSN', 'EIN', or 'ITIN'.")

Response: Generates a random US SSN from the specified type.


Instruction:
Here you have a function in Python 3, explain what it does
def catch_phrase(self):
        pattern = self.random_element(self.catch_phrase_formats)
        catch_phrase = self.generator.parse(pattern)
        catch_phrase = catch_phrase[0].upper() + catch_phrase[1:]
        return catch_phrase

Response: example a segurança de evoluir sem preocupação


Instruction:
Here you have a function in Python 3, explain what it does
def ide(self):
        def _checksum(digits):
            factors = (5, 4, 3, 2, 7, 6, 5, 4)
            sum_ = 0
            for i in range(len(digits)):
                sum_ += digits[i] * factors[i]
            return sum_ % 11

        while True:
            # create an array of first 8 elements initialized randomly
            digits = self.generator.random.sample(range(10), 8)
            # sum those 8 digits according to (part of) the "modulo 11"
            sum_ = _checksum(digits)
            # determine the last digit to make it qualify the test
            control_number = 11 - sum_
            if control_number != 10:
                digits.append(control_number)
                break

        digits = ''.join([str(digit) for digit in digits])
        # finally return our random but valid BSN
        return 'CHE-' + digits[0:3] + '.'\
                      + digits[3:6] + '.'\
                      + digits[6:9]

Response: Generate a random IDE number.


Instruction:
Write a Python 3 function that can
get a random unix time between start_datetime and end_datetime.

Response:
def unix_time(self, end_datetime=None, start_datetime=None):
        """
        Get a timestamp between January 1, 1970 and now, unless passed
        explicit start_datetime or end_datetime values.
        :example 1061306726
        """
        start_datetime = self._parse_start_datetime(start_datetime)
        end_datetime = self._parse_end_datetime(end_datetime)
        return self.generator.random.randint(start_datetime, end_datetime)


Instruction:
Write a Python 3 script to
get a timedelta object that is the time delta between start_datetime and end_datetime

Response:
def time_delta(self, end_datetime=None):
        """
        Get a timedelta object
        """
        start_datetime = self._parse_start_datetime('now')
        end_datetime = self._parse_end_datetime(end_datetime)
        seconds = end_datetime - start_datetime

        ts = self.generator.random.randint(*sorted([0, seconds]))
        return timedelta(seconds=ts)


Instruction:
Can you tell what is the following Python 3 function doing
def date_time(self, tzinfo=None, end_datetime=None):
        # NOTE: On windows, the lowest value you can get from windows is 86400
        #       on the first day. Known python issue:
        #       https://bugs.python.org/issue30684
        return datetime(1970, 1, 1, tzinfo=tzinfo) + \
            timedelta(seconds=self.unix_time(end_datetime=end_datetime))

Response: Get a datetime object for a date between January 1 1970 and now


Instruction:
Here you have a function in Python 3, explain what it does
def date_time_ad(self, tzinfo=None, end_datetime=None, start_datetime=None):

        # 1970-01-01 00:00:00 UTC minus 62135596800 seconds is
        # 0001-01-01 00:00:00 UTC.  Since _parse_end_datetime() is used
        # elsewhere where a default value of 0 is expected, we can't
        # simply change that class method to use this magic number as a
        # default value when None is provided.

        start_time = -62135596800 if start_datetime is None else self._parse_start_datetime(start_datetime)
        end_datetime = self._parse_end_datetime(end_datetime)

        ts = self.generator.random.randint(start_time, end_datetime)
        # NOTE: using datetime.fromtimestamp(ts) directly will raise
        #       a "ValueError: timestamp out of range for platform time_t"
        #       on some platforms due to system C functions;
        #       see http://stackoverflow.com/a/10588133/2315612
        # NOTE: On windows, the lowest value you can get from windows is 86400
        #       on the first day. Known python issue:
        #       https://bugs.python.org/issue30684
        return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts)

Response: Get a datetime object for a date between January 1 001 and now.


Instruction:
Can you generate the documentation for the following Python 3 function
def iso8601(self, tzinfo=None, end_datetime=None):
        return self.date_time(tzinfo, end_datetime=end_datetime).isoformat()

Response: returns ISO 8601 string for the current time


Instruction:
Here you have a function in Python 3, explain what it does
def date(self, pattern='%Y-%m-%d', end_datetime=None):
        return self.date_time(end_datetime=end_datetime).strftime(pattern)

Response: Get a date string between January 1 and 1970


Instruction:
Can you generate a brief explanation for the following Python 3 code
def time(self, pattern='%H:%M:%S', end_datetime=None):
        return self.date_time(
            end_datetime=end_datetime).time().strftime(pattern)

Response: Get a time string by default


Instruction:
Write a Python 3 function for
getting a DateTime object based on a random date between two given dates.

Response:
def date_time_between(self, start_date='-30y', end_date='now', tzinfo=None):
        """
        Get a DateTime object based on a random date between two given dates.
        Accepts date strings that can be recognized by strtotime().

        :param start_date Defaults to 30 years ago
        :param end_date Defaults to "now"
        :param tzinfo: timezone, instance of datetime.tzinfo subclass
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        start_date = self._parse_date_time(start_date, tzinfo=tzinfo)
        end_date = self._parse_date_time(end_date, tzinfo=tzinfo)
        if end_date - start_date <= 1:
            ts = start_date + self.generator.random.random()
        else:
            ts = self.generator.random.randint(start_date, end_date)
        if tzinfo is None:
            return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts)
        else:
            return (
                datetime(1970, 1, 1, tzinfo=tzutc()) + timedelta(seconds=ts)
            ).astimezone(tzinfo)


Instruction:
How would you explain what the following Python 3 function does
def date_between(self, start_date='-30y', end_date='today'):

        start_date = self._parse_date(start_date)
        end_date = self._parse_date(end_date)
        return self.date_between_dates(date_start=start_date, date_end=end_date)

Response: Returns a Date object based on a random date between two given dates.


Instruction:
Implement a Python 3 function for
getting a DateTime object based on a random date between 1 second form now and a given date.

Response:
def future_datetime(self, end_date='+30d', tzinfo=None):
        """
        Get a DateTime object based on a random date between 1 second form now
        and a given date.
        Accepts date strings that can be recognized by strtotime().

        :param end_date Defaults to "+30d"
        :param tzinfo: timezone, instance of datetime.tzinfo subclass
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        return self.date_time_between(
            start_date='+1s', end_date=end_date, tzinfo=tzinfo,
        )


Instruction:
Write a Python 3 script to
get a DateTime object based on a random date between start_date and end_date.

Response:
def past_datetime(self, start_date='-30d', tzinfo=None):
        """
        Get a DateTime object based on a random date between a given date and 1
        second ago.
        Accepts date strings that can be recognized by strtotime().

        :param start_date Defaults to "-30d"
        :param tzinfo: timezone, instance of datetime.tzinfo subclass
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        return self.date_time_between(
            start_date=start_date, end_date='-1s', tzinfo=tzinfo,
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def date_time_between_dates(
            self,
            datetime_start=None,
            datetime_end=None,
            tzinfo=None):
        """
        Takes two DateTime objects and returns a random datetime between the two
        given datetimes.
        Accepts DateTime objects.

        :param datetime_start: DateTime
        :param datetime_end: DateTime
        :param tzinfo: timezone, instance of datetime.tzinfo subclass
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        if datetime_start is None:
            datetime_start = datetime.now(tzinfo)

        if datetime_end is None:
            datetime_end = datetime.now(tzinfo)

        timestamp = self.generator.random.randint(
            datetime_to_timestamp(datetime_start),
            datetime_to_timestamp(datetime_end),
        )
        try:
            if tzinfo is None:
                pick = datetime.fromtimestamp(timestamp, tzlocal())
                pick = pick.astimezone(tzutc()).replace(tzinfo=None)
            else:
                pick = datetime.fromtimestamp(timestamp, tzinfo)
        except OverflowError:
            raise OverflowError(
                "You specified an end date with a timestamp bigger than the maximum allowed on this"
                " system. Please specify an earlier date.",
            )
        return pick

Response: Returns a random datetime between the two datetimes.