Instruction:
How would you explain what the following Python 3 function does
def generate_hub_key(resolver_id, hub_id, repository_id, entity_type, entity_id=None):
    parsed = urlparse(resolver_id)
    if not parsed.scheme:
        parsed = parsed._replace(scheme=PROTOCOL, netloc=idna_encode(parsed.path.lower()), path=u'')
    else:
        parsed = parsed._replace(netloc=idna_encode(parsed.netloc.lower()))

    resolver_id = urlunparse(parsed)

    hub_id = url_quote(hub_id.lower())

    if not entity_id:
        entity_id = str(uuid.uuid4()).replace('-', '')
    else:
        match_part(entity_id, 'entity_id')

    # If any of these checks fail a ValueError exception is raised
    match_part(resolver_id, 'resolver_id')
    match_part(hub_id, 'hub_id')
    match_part(repository_id, 'repository_id')
    match_part(entity_type, 'entity_type')

    hub_key = SEPARATOR.join(
        [resolver_id, SCHEMA, hub_id, repository_id, entity_type, entity_id])
    return hub_key

Response: Generate and return a hub key


Instruction:
Can you implement a function in Python 3 that
compacts a CouchDB database with optional synchronicity.

Response:
def compact(db_spec, poll_interval=0):

    """
    Compact a CouchDB database with optional synchronicity.

    The ``compact`` function will compact a CouchDB database stored on an
    running CouchDB server. By default, this process occurs *asynchronously*,
    meaning that the compaction will occur in the background. Often, you'll want
    to know when the process has completed; for this reason, ``compact`` will
    return a function which, when called, will return the state of the
    compaction. If it has completed, ``True`` will be returned; otherwise,
    ``False``. This may be called multiple times.

    Alternatively, you may opt to run ``compact`` in synchronous mode, for
    debugging or profiling purposes. If this is the case, an optional keyword
    argument ``poll_interval`` is accepted, which should be a number (in
    seconds) representing the time to take between polls. A sensible default
    may be around 0.5 (seconds).

    Because this function operates on database specifiers, you can choose to
    operate on the local server or any remote server.
    """

    server = get_server_from_specifier(db_spec)
    db = get_db_from_specifier(db_spec)
    # Get logger
    logger = logging.getLogger('relax.couchdb.compact')
    logger.info('Pre-compact size of %r: %s' % (db_spec,
        repr_bytes(db.info()['disk_size']),))
    logger.debug('POST ' + urlparse.urljoin(db.resource.uri + '/', '_compact'))
    # Start compaction process by issuing a POST to '/<db_name>/_compact'.
    resp_headers, resp_body = db.resource.post('/_compact')
    # Asynchronous compaction
    if not poll_interval:
        if not (resp_body.get('ok', False) and
            resp_headers['status'] == '202'):
            err = CompactionError('Compaction of %r failed.')
            # Give the exception some useful information.
            err.response = (resp_headers, resp_body)
            raise err
        # Return a function which, when called, will return whether or not the
        # compaction process is still running.
        def check_completed():
            logger.debug(
                'Polling database to check if compaction has completed')
            logger.debug('GET ' + db.resource.uri + '/')
            db_info = db.info()
            completed = not db_info.get('compact_running', False)
            if completed and db_info.get('disk_size', None):
                logger.info('Post-compact size of %r: %s' % (db_spec,
                    repr_bytes(db_info['disk_size'])))
            return completed
        return check_completed
    # Synchronous compaction
    elif poll_interval > 0:
        logger.debug(
            'Polling database to check if compaction has completed')
        logger.debug('GET ' + db.resource.uri + '/')
        # Shows whether compaction is running or not.
        running = db.info().get('compact_running', False)
        # Poll the running state of the compaction.
        while running:
            time.sleep(poll_interval)
            logger.debug(
                'Polling database to check if compaction has completed')
            logger.debug('GET ' + db.resource.uri + '/')
            running = db.info().get('compact_running', False)
        size_after = db.info().get('disk_size', None)
        if size_after:
            logger.info('Post-compact size of %r: %s' % (db_spec,
                repr_bytes(size_after)))
        return True
    else:
        raise ValueError('Poll interval must be greater than zero.')


Instruction:
Implement a Python 3 function for
applying default settings to commands

Response:
def apply_defaults(self, commands):
        """ apply default settings to commands
            not static, shadow "self" in eval
        """
        for command in commands:
            if 'action' in command and "()" in command['action']:
                command['action'] = eval("self.{}".format(command['action']))
            if command['keys'][0].startswith('-'):
                if 'required' not in command:
                    command['required'] = False


Instruction:
Make a summary of the following Python 3 code
def create_commands(self, commands, parser):
        self.apply_defaults(commands)
        def create_single_command(command):
            keys = command['keys']
            del command['keys']
            kwargs = {}
            for item in command:
                kwargs[item] = command[item]
            parser.add_argument(*keys, **kwargs)

        if len(commands) > 1:
            for command in commands:
                create_single_command(command)
        else:
            create_single_command(commands[0])

Response: add commands to parser


Instruction:
Make a summary of the following Python 3 code
def create_subparsers(self, parser):
        subparsers = parser.add_subparsers()
        for name in self.config['subparsers']:
            subparser = subparsers.add_parser(name)
            self.create_commands(self.config['subparsers'][name], subparser)

Response: get config for subparser and create commands


Instruction:
Write a Python 3 function for
returning the consumer and oauth tokens with three - legged OAuth process and save in a yaml file in the user home directory.

Response:
def new_user(yaml_path):
    '''
    Return the consumer and oauth tokens with three-legged OAuth process and
    save in a yaml file in the user's home directory.
    '''

    print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/'
    api_key = raw_input('Shirts.io API Key: ')

    tokens = {
        'api_key': api_key,
    }

    yaml_file = open(yaml_path, 'w+')
    yaml.dump(tokens, yaml_file, indent=2)
    yaml_file.close()

    return tokens


Instruction:
Here you have a function in Python 3, explain what it does
def _AddPropertiesForExtensions(descriptor, cls):
  extension_dict = descriptor.extensions_by_name
  for extension_name, extension_field in extension_dict.items():
    constant_name = extension_name.upper() + "_FIELD_NUMBER"
    setattr(cls, constant_name, extension_field.number)

Response: Adds properties for all fields in this protocol message type.


Instruction:
Can you create a Python 3 function that
unpacks Any message and returns the unpacked message.

Response:
def _InternalUnpackAny(msg):
  """Unpacks Any message and returns the unpacked message.

  This internal method is differnt from public Any Unpack method which takes
  the target message as argument. _InternalUnpackAny method does not have
  target message type and need to find the message type in descriptor pool.

  Args:
    msg: An Any message to be unpacked.

  Returns:
    The unpacked message.
  """
  type_url = msg.type_url
  db = symbol_database.Default()

  if not type_url:
    return None

  # TODO(haberman): For now we just strip the hostname.  Better logic will be
  # required.
  type_name = type_url.split("/")[-1]
  descriptor = db.pool.FindMessageTypeByName(type_name)

  if descriptor is None:
    return None

  message_class = db.GetPrototype(descriptor)
  message = message_class()

  message.ParseFromString(msg.value)
  return message