Instruction:
Given the following Python 3 function, write the documentation
def _migrate_ledger(data_directory,
                    old_ledger_file, new_ledger_file,
                    serializer: MappingSerializer = None):
    """
    Test for the directory, open old and new ledger, migrate data, rename directories
    """

    # we should have ChunkedFileStorage implementation of the Ledger
    if not os.path.isdir(os.path.join(data_directory, old_ledger_file)):
        msg = 'Could not find directory {} for migration.'.format(
            old_ledger_file)
        logger.error(msg)
        raise Exception(msg)

    # open the current ledger using the specified serializer
    old_txn_log_store = ChunkedFileStore(data_directory,
                                         old_ledger_file,
                                         isLineNoKey=True,
                                         storeContentHash=False)
    logger.info("Old ledger folder: {}, {}".format(
        data_directory, old_ledger_file))
    old_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        txn_serializer=serializer,
                        hash_serializer=serializer,
                        fileName=old_ledger_file,
                        transactionLogStore=old_txn_log_store)
    logger.info("old size for {}: {}".format(
        old_ledger_file, str(old_ledger.size)))

    # open the new ledger with new serialization
    new_ledger_file_backup = new_ledger_file + "_new"
    logger.info("New ledger folder: {}, {}".format(
        data_directory, new_ledger_file_backup))
    new_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        fileName=new_ledger_file_backup)

    # add all txns into the new ledger
    for _, txn in old_ledger.getAllTxn():
        if txn[TXN_TYPE] == SCHEMA:
            if DATA in txn:
                txn[DATA] = json.loads(txn[DATA])
        if txn[TXN_TYPE] == CLAIM_DEF:
            if DATA in txn:
                txn[DATA] = json.loads(txn[DATA])
        new_ledger.add(txn)
    logger.info("new size for {}: {}".format(
        new_ledger_file, str(new_ledger.size)))

    old_ledger.stop()
    new_ledger.stop()

    # now that everything succeeded, remove the old files and move the new
    # files into place
    shutil.rmtree(
        os.path.join(data_directory, old_ledger_file))
    os.rename(
        os.path.join(data_directory, new_ledger_file_backup),
        os.path.join(data_directory, new_ledger_file))

    logger.info("Final new ledger folder: {}".format(
        os.path.join(data_directory, new_ledger_file)))

Response: Open the old and new ledger and migrate data


Instruction:
Make a summary of the following Python 3 code
def getNym(self, nym, role=None, isCommitted=True):
        try:
            seqNo, txnTime, ta, actual_role, verkey = self.get(nym, isCommitted)
        except KeyError:
            return None
        if role and role != actual_role:
            return None
        return {
            ROLE: actual_role or None,
            VERKEY: verkey or None,
            f.IDENTIFIER.nm: ta or None,
            f.SEQ_NO.nm: seqNo or None,
            TXN_TIME: txnTime or None,
        }

Response: Get a nym from the cache.


Instruction:
How would you explain what the following Python 3 function does
def _unscheduleAction(self):
        logger.trace("{} unscheduling actions".format(self))
        self.aqStash = deque()
        self.scheduledAction = None

Response:
Unschedule current action

        Note that it does not add record to action log and does not do
        required steps to resume previous action. If you need this - use
        _cancelScheduledAction


Instruction:
How would you code a function in Python 3 to
find rule_id for incoming action_id and return AuthConstraint instance

Response:
def get_auth_constraint(self, action_id: str) -> AbstractAuthConstraint:
        """
        Find rule_id for incoming action_id and return AuthConstraint instance
        """
        if self.anyone_can_write_map:
            return self._find_auth_constraint(action_id, self.anyone_can_write_map, from_local=True)

        return self._find_auth_constraint(action_id, self.auth_map)


Instruction:
Make a summary of the following Python 3 code
def _append(self, ev_type: Enum, data: ActionLogData) -> None:
        event = ActionLogEvent(None, ev_type, data, types=self._event_types)
        with open(self._file_path, mode='a+', newline='') as f:
            f.write(event.pack(delimiter=self._delimiter))
        self._items.append(event)

Response: Append an event to the log.


Instruction:
Can you create a Python 3 function that
updates the state of the current entry in the state trie.

Response:
def update_state(self, txn, prev_result, is_committed=True) -> None:
        """
        The state trie stores the hash of the whole attribute data at:
            the did+attribute name if the data is plaintext (RAW)
            the did+hash(attribute) if the data is encrypted (ENC)
        If the attribute is HASH, then nothing is stored in attribute store,
        the trie stores a blank value for the key did+hash
        """
        self._validate_txn_type(txn)
        attr_type, path, value, hashed_value, value_bytes = domain.prepare_attr_for_state(txn)
        self.state.set(path, value_bytes)
        if attr_type != HASH:
            self.database_manager.attribute_store.set(hashed_value, value)


Instruction:
Write a Python 3 function that can
create an auth strategy based on the current configuration.

Response:
def create_auth_strategy(self):
        """depends on config"""
        if self.config.authPolicy == LOCAL_AUTH_POLICY:
            return LocalAuthStrategy(auth_map=self.auth_map,
                                     anyone_can_write_map=self.anyone_can_write_map if self.anyone_can_write else None)
        elif self.config.authPolicy == CONFIG_LEDGER_AUTH_POLICY:
            return ConfigLedgerAuthStrategy(auth_map=self.auth_map,
                                            state=self.config_state,
                                            serializer=self.state_serializer,
                                            anyone_can_write_map=self.anyone_can_write_map if self.anyone_can_write else None,
                                            metrics=self.metrics)


Instruction:
Write a Python 3 script to
generate the path to state as str type

Response:
def gen_txn_path(self, txn):

        """Return path to state as 'str' type or None"""
        txn_type = get_type(txn)
        if txn_type not in self.state_update_handlers:
            logger.error('Cannot generate id for txn of type {}'.format(txn_type))
            return None

        if txn_type == NYM:
            nym = get_payload_data(txn).get(TARGET_NYM)
            binary_digest = domain.make_state_path_for_nym(nym)
            return hexlify(binary_digest).decode()
        elif txn_type == ATTRIB:
            path = domain.prepare_attr_for_state(txn, path_only=True)
            return path.decode()
        elif txn_type == SCHEMA:
            path = domain.prepare_schema_for_state(txn, path_only=True)
            return path.decode()
        elif txn_type == CLAIM_DEF:
            path = domain.prepare_claim_def_for_state(txn, path_only=True)
            return path.decode()
        elif txn_type == REVOC_REG_DEF:
            path = domain.prepare_revoc_def_for_state(txn, path_only=True)
            return path.decode()
        elif txn_type == REVOC_REG_ENTRY:
            path = domain.prepare_revoc_reg_entry_for_state(txn, path_only=True)
            return path.decode()

        raise NotImplementedError("path construction is not implemented for type {}".format(txn_type))


Instruction:
Here you have a function in Python 3, explain what it does
def handleGetRevocRegDelta(self, request: Request):
        req_ts_from = request.operation.get(FROM, None)
        req_ts_to = request.operation.get(TO)
        revoc_reg_def_id = request.operation.get(REVOC_REG_DEF_ID)
        reply = None
        """
        Get root hash for "to" timestamp
        Get REVOC_REG_ENTRY and ACCUM record for timestamp "to"
        """
        path_to_reg_entry = domain.make_state_path_for_revoc_reg_entry(revoc_reg_def_id=revoc_reg_def_id)
        path_to_reg_entry_accum = domain.make_state_path_for_revoc_reg_entry_accum(revoc_reg_def_id=revoc_reg_def_id)

        entry_to = self._get_reg_entry_by_timestamp(req_ts_to, path_to_reg_entry)
        accum_to = self._get_reg_entry_accum_by_timestamp(req_ts_to, path_to_reg_entry_accum)
        entry_from = StateValue()
        accum_from = StateValue()

        if accum_to.value and entry_to.value:
            """Get issuance type from REVOC_REG_DEF"""
            encoded_revoc_reg_def = self.state.get_for_root_hash(entry_to.root_hash,
                                                                 revoc_reg_def_id)
            if encoded_revoc_reg_def:
                revoc_reg_def, _, _ = domain.decode_state_value(encoded_revoc_reg_def)
                strategy_cls = self.get_revocation_strategy(revoc_reg_def[VALUE][ISSUANCE_TYPE])
                issued_to = entry_to.value[VALUE].get(ISSUED, [])
                revoked_to = entry_to.value[VALUE].get(REVOKED, [])
                if req_ts_from:
                    """Get REVOC_REG_ENTRY and ACCUM records for timestamp from if exist"""
                    entry_from = self._get_reg_entry_by_timestamp(req_ts_from, path_to_reg_entry)
                    accum_from = self._get_reg_entry_accum_by_timestamp(req_ts_from, path_to_reg_entry_accum)
                if req_ts_from and entry_from.value and accum_from.value:
                    """Compute issued/revoked lists corresponding with ISSUANCE_TYPE strategy"""
                    issued_from = entry_from.value[VALUE].get(ISSUED, [])
                    revoked_from = entry_from.value[VALUE].get(REVOKED, [])
                    result_issued, result_revoked = strategy_cls.get_delta({ISSUED: issued_to,
                                                                            REVOKED: revoked_to},
                                                                           {ISSUED: issued_from,
                                                                            REVOKED: revoked_from})
                else:
                    result_issued, result_revoked = strategy_cls.get_delta({ISSUED: issued_to,
                                                                            REVOKED: revoked_to},
                                                                           None)
                reply = {
                    REVOC_REG_DEF_ID: revoc_reg_def_id,
                    REVOC_TYPE: revoc_reg_def.get(REVOC_TYPE),
                    VALUE: {
                        ACCUM_TO: accum_to.value if entry_from.value else entry_to.value,
                        ISSUED: result_issued,
                        REVOKED: result_revoked
                    }

                }
                """If we got "from" timestamp, then add state proof into "data" section of reply"""
                if req_ts_from and accum_from.value:
                    reply[STATE_PROOF_FROM] = accum_from.proof
                    reply[VALUE][ACCUM_FROM] = accum_from.value

        if accum_to and entry_to:
            seq_no = accum_to.seq_no if entry_from.value else entry_to.seq_no
            update_time = accum_to.update_time if entry_from.value else entry_to.update_time
            proof = accum_to.proof if entry_from.value else entry_to.proof
        else:
            seq_no = None
            update_time = None
            proof = None

        return self.make_domain_result(request=request,
                                       data=reply,
                                       last_seq_no=seq_no,
                                       update_time=update_time,
                                       proof=proof)

Response: Handles the GET_REVOC_REG_DELTA request.


Instruction:
Write a Python 3 function that can
query state for data on specified path and returns the value last_seq_no last_update_time and proof.

Response:
def lookup(self, path, isCommitted=True, with_proof=False) -> (str, int):
        """
        Queries state for data on specified path

        :param path: path to data
        :param isCommitted: queries the committed state root if True else the uncommitted root
        :param with_proof: creates proof if True
        :return: data
        """
        assert path is not None
        head_hash = self.state.committedHeadHash if isCommitted else self.state.headHash
        encoded, proof = self.get_value_from_state(path, head_hash, with_proof=with_proof)
        if encoded:
            value, last_seq_no, last_update_time = domain.decode_state_value(encoded)
            return value, last_seq_no, last_update_time, proof
        return None, None, None, proof


Instruction:
Can you write a function in Python 3 where it
adds an attribute to the state trie.

Response:
def _addAttr(self, txn, isCommitted=False) -> None:
        """
        The state trie stores the hash of the whole attribute data at:
            the did+attribute name if the data is plaintext (RAW)
            the did+hash(attribute) if the data is encrypted (ENC)
        If the attribute is HASH, then nothing is stored in attribute store,
        the trie stores a blank value for the key did+hash
        """
        assert get_type(txn) == ATTRIB
        attr_type, path, value, hashed_value, value_bytes = domain.prepare_attr_for_state(txn)
        self.state.set(path, value_bytes)
        if attr_type != HASH:
            self.attributeStore.set(hashed_value, value)


Instruction:
Can you implement a function in Python 3 that
transforms a transaction to be stored in the ledger

Response:
def transform_txn_for_ledger(txn):
        """
        Some transactions need to be transformed before they can be stored in the
        ledger, eg. storing certain payload in another data store and only its
        hash in the ledger
        """
        if get_type(txn) == ATTRIB:
            txn = DomainReqHandler.transform_attrib_for_ledger(txn)
        return txn


Instruction:
How would you explain what the following Python 3 function does
def transform_attrib_for_ledger(txn):
        txn = deepcopy(txn)
        txn_data = get_payload_data(txn)
        attr_type, _, value = domain.parse_attr_txn(txn_data)
        if attr_type in [RAW, ENC]:
            txn_data[attr_type] = domain.hash_of(value) if value else ''

        return txn

Response: Transform the attribute of a ledger transaction so that they can be used by the ledger.


Instruction:
Can you generate the documentation for the following Python 3 function
def getSymmetricallyEncryptedVal(val, secretKey: Union[str, bytes] = None) -> \
        Tuple[str, str]:
    """
    Encrypt the provided value with symmetric encryption

    :param val: the value to encrypt
    :param secretKey: Optional key, if provided should be either in hex or bytes
    :return: Tuple of the encrypted value and secret key encoded in hex
    """

    if isinstance(val, str):
        val = val.encode("utf-8")
    if secretKey:
        if isHex(secretKey):
            secretKey = bytes(bytearray.fromhex(secretKey))
        elif not isinstance(secretKey, bytes):
            error("Secret key must be either in hex or bytes")
        box = libnacl.secret.SecretBox(secretKey)
    else:
        box = libnacl.secret.SecretBox()

    return box.encrypt(val).hex(), box.sk.hex()

Response: Encrypt the provided value with symmetric encryption with the specified secret key.


Instruction:
How would you explain what the following Python 3 function does
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:
    try:
        return next(i for i, v in enumerate(items) if predicateFn(v))
    except StopIteration:
        return -1

Response: Finds the index of an item in list which satisfies predicateFn


Instruction:
Make a summary of the following Python 3 code
def getImageByTag(tag):
    '''Check if an image with a given tag exists. No side-effects. Idempotent.
    Handles ImageNotFound and APIError exceptions, but only reraises APIError.
    '''
    require_str("tag", tag)

    image = None
    try:
        image = client.images.get(tag)
        print("Found image", tag, "...")
    except ImageNotFound:
        print("Image", tag, "does not exist ...")
    except APIError as exc:
        eprint("Unhandled error while getting image", tag)
        raise exc

    return image

Response: Check if an image with a given tag exists. No side - effects. Idempotent.


Instruction:
Here you have a function in Python 3, explain what it does
def getImage(path, dockerfile, tag):
    '''Check if an image with a given tag exists. If not, build an image from
    using a given dockerfile in a given path, tagging it with a given tag.
    No extra side effects. Handles and reraises BuildError, TypeError, and
    APIError exceptions.
    '''
    image = getImageByTag(tag)

    if not image:
        # Build an Image using the dockerfile in the path
        try:
            image = client.images.build(
              path=path,
              dockerfile=dockerfile,
              tag=tag
            )
        except BuildError as exc:
            eprint("Failed to build docker image")
            raise exc
        except TypeError as exc:
            eprint("You must give a path to the build environemnt.")
            raise exc
        except APIError as exc:
            eprint("Unhandled error while building image", tag)
            raise exc

    return image

Response: Build an image from a given path using a given dockerfile in a given path.


Instruction:
Here you have a function in Python 3, explain what it does
def runContainer(image, **kwargs):
    '''Run a docker container using a given image; passing keyword arguments
    documented to be accepted by docker's client.containers.run function
    No extra side effects. Handles and reraises ContainerError, ImageNotFound,
    and APIError exceptions.
    '''
    container = None
    try:
        container = client.containers.run(image, **kwargs)
        if "name" in kwargs.keys():
          print("Container", kwargs["name"], "is now running.")
    except ContainerError as exc:
        eprint("Failed to run container")
        raise exc
    except ImageNotFound as exc:
        eprint("Failed to find image to run as a docker container")
        raise exc
    except APIError as exc:
        eprint("Unhandled error")
        raise exc

    return container

Response: Run a docker container using a given image


Instruction:
Write a Python 3 function that can
get the container with the given name or ID.

Response:
def getContainer(name_or_id):
    '''Get the container with the given name or ID (str). No side effects.
    Idempotent. Returns None if the container does not exist. Otherwise, the
    continer is returned'''
    require_str("name_or_id", name_or_id)

    container = None
    try:
        container = client.containers.get(name_or_id)
    except NotFound as exc:
        # Return None when the container is not found
        pass
    except APIError as exc:
        eprint("Unhandled error")
        raise exc

    return container


Instruction:
Given the following Python 3 function, write the documentation
def containerIsRunning(name_or_id):
    '''Check if container with the given name or ID (str) is running. No side
    effects. Idempotent. Returns True if running, False if not.'''
    require_str("name_or_id", name_or_id)

    try:
        container = getContainer(name_or_id)
        # Refer to the latest status list here: https://docs.docker.com/engine/
        #   api/v1.33/#operation/ContainerList
        if container:
            if container.status == 'created':
              return False
            elif container.status == 'restarting':
              return True
            elif container.status == 'running':
              return True
            elif container.status == 'removing':
              return False
            elif container.status == 'paused':
              return False
            elif container.status == 'exited':
              return False
            elif container.status == 'dead':
              return False
            else:
              return False
    except NotFound as exc:
        return False

    return False

Response:
Check if a container with the given name or ID is running. No side
    effects. Idempotent. Returns True if running False if not.


Instruction:
Create a Python 3 function for
checking if a container with a given tag exists. No side - effects. Idempotent. Returns None if the container is not found.

Response:
def getContainerByTag(tag):
    '''Check if a container with a given tag exists. No side-effects.
    Idempotent. Handles NotFound and APIError exceptions, but only reraises
    APIError. Returns None if the container is not found. Otherwise, returns the
    container.'''
    require_str("tag", tag)

    container = None
    try:
        container = client.containers.get(tag)
        print("Found container", tag, "...")
    except NotFound:
        #print("Container", tag, "does not exist ...")
        pass
    except APIError as exc:
        eprint("Unhandled error while getting container", tag)
        raise exc

    return container


Instruction:
Can you generate a brief explanation for the following Python 3 code
def removeContainer(tag):
    '''Check if a container with a given tag exists. Kill it if it exists.
    No extra side effects. Handles and reraises TypeError, and
    APIError exceptions.
    '''
    container = getContainerByTag(tag)

    if container:
        # Build an Image using the dockerfile in the path
        try:
            container.remove(force=True)
            #print("Removed container", tag, "...")
        except APIError as exc:
            eprint("Unhandled error while removing container", tag)
            raise exc

Response: Remove a container with a given tag.


Instruction:
Write a Python 3 script to
start the indy_pool docker container iff it is not already running.

Response:
def startIndyPool(**kwargs):
    '''Start the indy_pool docker container iff it is not already running. See
    <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures
    that the indy_pool container is up and running.'''

    # TODO: Decide if we need a separate docker container for testing and one for
    #       development. The indy_sdk tests setup and teardown "indy_pool" on
    #       ports 9701-9708. Perhaps we need an "indy_dev_pool" on 9709-9716? I'm
    #       not quite sure where all of our dependencies are on port 9701-9708.
    #       If the test harness (mocks) are hardcoding 9701-9708, then an
    #       indy_dev_pool on different ports will not work.

    print("Starting indy_pool ...")

    # Check if indy_pool is running
    if containerIsRunning("indy_pool"):
        print("... already running")
        exit(0)
    else:
        # If the container already exists and isn't running, force remove it and
        # readd it. This is brute force, but is sufficient and simple.
        container = getContainer("indy_pool")
        if container:
          container.remove(force=True)

    # Build and run indy_pool if it is not already running
    # Build the indy_pool image from the dockerfile in:
    #   /vagrant/indy-sdk/ci/indy-pool.dockerfile
    #
    # In shell using docker cli:
    # cd /vagrant/indy-sdk
    # sudo docker build -f ci/indy-pool.dockerfile -t indy_pool .
    #
    # NOTE: https://jira.hyperledger.org/browse/IS-406 prevents indy_pool from
    #       starting on the `rc` branch. Apply the patch in the Jira issue to
    #       overcome this problem.

    try:
      # indy-sdk won't be in /vagrant if the indy-sdk is cloned to a directory outside
      # the Vagrant project. Regardless of where indy-sdk is cloned, it will be found
      # in /src/indy-sdk in the Vagrant VM.
      image = getImage(path="/src/indy-sdk", dockerfile="ci/indy-pool.dockerfile",
        tag="indy_pool")
    except TypeError as exc:
      image = getImage(path="/vagrant/indy-sdk", dockerfile="ci/indy-pool.dockerfile",
        tag="indy_pool")
    except:
      print("Failed to find indy-pool.dockerfile in /vagrant/indy-sdk or /src/indy-sdk")

    # Run a container using the image
    #
    # In shell using docker cli:
    # sudo docker run -itd -p 9701-9708:9701-9708 indy_pool
    #
    # NOTE: {'2222/tcp': 3333} is sufficient. A tuple of (address, port) if you
    #       want to specify the host interface.
    container = runContainer(image, ports={
        '9701/tcp': ('0.0.0.0', 9701),
        '9702/tcp': ('0.0.0.0', 9702),
        '9703/tcp': ('0.0.0.0', 9703),
        '9704/tcp': ('0.0.0.0', 9704),
        '9705/tcp': ('0.0.0.0', 9705),
        '9706/tcp': ('0.0.0.0', 9706),
        '9707/tcp': ('0.0.0.0', 9707),
        '9708/tcp': ('0.0.0.0', 9708)
      }, detach=True, name="indy_pool"
    )

    print("...started")


Instruction:
Can you generate the documentation for the following Python 3 function
def restartIndyPool(**kwargs):
    '''Restart the indy_pool docker container. Idempotent. Ensures that the
    indy_pool container is a new running instance.'''
    print("Restarting...")
    try:
      stopIndyPool()
      startIndyPool()
      print("...restarted")
    except Exception as exc:
      eprint("...failed to restart")
      raise exc

Response: Restart the indy_pool docker container. Idempotent. Ensures that the indy_pool docker container is a new running instance.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def signingPayloadState(self, identifier=None):
        if self.operation.get(TXN_TYPE) == ATTRIB:
            d = deepcopy(super().signingPayloadState(identifier=identifier))
            op = d[OPERATION]
            keyName = {RAW, ENC, HASH}.intersection(set(op.keys())).pop()
            op[keyName] = sha256(op[keyName].encode()).hexdigest()
            return d
        return super().signingPayloadState(identifier=identifier)

Response:
Special signing state where the data for an attribute is hashed
        before signing
       .


Instruction:
Make a summary of the following Python 3 code
def _migrate_ledger(data_directory,
                    old_ledger_file, new_ledger_file,
                    serializer: MappingSerializer = None):
    """
    Test for the directory, open old and new ledger, migrate data, rename directories
    """

    # we should have ChunkedFileStorage implementation of the Ledger
    if not os.path.isdir(os.path.join(data_directory, old_ledger_file)):
        msg = 'Could not find directory {} for migration.'.format(
            old_ledger_file)
        logger.error(msg)
        raise Exception(msg)

    # open the old ledger using the specified serializer
    old_ledger_file_backup = old_ledger_file + "_new"
    old_txn_log_store = ChunkedFileStore(data_directory,
                                         old_ledger_file_backup,
                                         isLineNoKey=True,
                                         storeContentHash=False)
    old_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        txn_serializer=serializer,
                        hash_serializer=serializer,
                        fileName=old_ledger_file_backup,
                        transactionLogStore=old_txn_log_store)

    # open the new ledger with new serialization
    new_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        fileName=new_ledger_file)
    logger.info("new size for {}: {}".format(
        old_ledger_file_backup, str(new_ledger.size)))

    # add all txns into the old ledger
    for _, txn in new_ledger.getAllTxn():
        old_ledger.add(txn)
    logger.info("old size for {}: {}".format(
        new_ledger_file, str(old_ledger.size)))

    old_ledger.stop()
    new_ledger.stop()

    # now that everything succeeded, remove the new files and move the old
    # files into place
    shutil.rmtree(
        os.path.join(data_directory, new_ledger_file))
    os.rename(
        os.path.join(data_directory, old_ledger_file_backup),
        os.path.join(data_directory, old_ledger_file))

Response: Test for the directory open old and new ledger and migrate data


Instruction:
Can you generate the documentation for the following Python 3 function
def get_role(self, request: Request):
        idr = request.identifier
        return self._get_role(idr)

Response: Returns the role corresponding to the DID in the request.


Instruction:
Can you generate the documentation for the following Python 3 function
def handleConfigTxn(self, txn) -> None:
        if get_type(txn) == POOL_CONFIG:
            self.writes = get_payload_data(txn)[WRITES]

Response: Handles transaction of type POOL_CONFIG


Instruction:
How would you explain what the following Python 3 function does
def processLedger(self) -> None:
        logger.debug('{} processing config ledger for any POOL_CONFIGs'.format(
            self), extra={"tags": ["pool-config"]})
        for _, txn in self.ledger.getAllTxn():
            if get_type(txn) == POOL_CONFIG:
                self.handleConfigTxn(txn)

Response: Checks ledger config txns and perfomes recent one


Instruction:
Make a summary of the following Python 3 code
def handleRestartRequest(self, req: Request) -> None:
        txn = req.operation
        if txn[TXN_TYPE] != POOL_RESTART:
            return

        action = txn[ACTION]
        if action == START:
            when = dateutil.parser.parse(txn[DATETIME]) \
                if DATETIME in txn.keys() and txn[DATETIME] not in ["0", "", None] \
                else None
            fail_timeout = txn.get(TIMEOUT, self.defaultActionTimeout)
            self.requestRestart(when, fail_timeout)
            return

        if action == CANCEL:
            if self.scheduledAction:
                self._cancelScheduledRestart()
                logger.info("Node '{}' cancels restart".format(
                    self.nodeName))
            return

        logger.error(
            "Got {} transaction with unsupported action {}".format(
                POOL_RESTART, action))

Response: Handles a POOL_RESTART transaction.


Instruction:
Here you have a function in Python 3, explain what it does
def _scheduleRestart(self,
                         when: Union[datetime, str],
                         failTimeout) -> None:
        """
        Schedules node restart to a newer version

        :param version: version to restart to
        :param when: restart time
        """
        logger.info("{}'s restarter processing restart"
                    .format(self))
        if isinstance(when, str):
            when = dateutil.parser.parse(when)
        now = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())

        logger.info(
            "Restart of node '{}' has been scheduled on {}".format(
                self.nodeName, when))

        ev_data = RestartLogData(when)
        self._actionLog.append_scheduled(ev_data)

        callAgent = partial(self._callRestartAgent, ev_data,
                            failTimeout)
        delay = 0
        if now < when:
            delay = (when - now).total_seconds()
        self.scheduledAction = ev_data
        self._schedule(callAgent, delay)

Response: Schedules a restart of the node to a newer version.


Instruction:
Given the following Python 3 function, write the documentation
def _cancelScheduledRestart(self, justification=None) -> None:

        if self.scheduledAction:
            why_prefix = ": "
            why = justification
            if justification is None:
                why_prefix = ", "
                why = "cancellation reason not specified"

            ev_data = self.scheduledAction
            logger.info("Cancelling restart"
                        " of node {}"
                        " scheduled on {}"
                        "{}{}"
                        .format(self.nodeName,
                                ev_data.when,
                                why_prefix,
                                why))

            self._unscheduleAction()
            self._actionLog.append_cancelled(ev_data)
            logger.info(
                "Restart of node '{}'"
                "has been cancelled due to {}".format(
                    self.nodeName, why))

Response: Cancels scheduled restart of the current node.


Instruction:
Given the following Python 3 function, write the documentation
def _callRestartAgent(self, ev_data: RestartLogData, failTimeout) -> None:

        logger.info("{}'s restart calling agent for restart".format(self))
        self._actionLog.append_started(ev_data)
        self._action_start_callback()
        self.scheduledAction = None
        asyncio.ensure_future(
            self._sendUpdateRequest(ev_data, failTimeout))

Response: Callback which is called when restart time come.


Instruction:
Given the following Python 3 function, write the documentation
def _declareTimeoutExceeded(self, ev_data: RestartLogData):
        logger.info("Timeout exceeded for {}".format(ev_data.when))
        last = self._actionLog.last_event
        if (last and last.ev_type == RestartLog.Events.failed and
                last.data == ev_data):
            return None

        self._action_failed(ev_data,
                            reason="exceeded restart timeout")

        self._unscheduleAction()
        self._actionFailedCallback()

Response: This function is called when time for restart is up.


Instruction:
Write a Python 3 script to
process the config ledger for any upgrades and schedules upgrade for the most recent one

Response:
def processLedger(self) -> None:
        """
        Checks ledger for planned but not yet performed upgrades
        and schedules upgrade for the most recent one

        Assumption: Only version is enough to identify a release, no hash
        checking is done
        :return:
        """
        logger.debug(
            '{} processing config ledger for any upgrades'.format(self))
        last_pool_upgrade_txn_start = self.get_upgrade_txn(
            lambda txn: get_type(txn) == POOL_UPGRADE and get_payload_data(txn)[ACTION] == START, reverse=True)
        if last_pool_upgrade_txn_start:
            logger.info('{} found upgrade START txn {}'.format(
                self, last_pool_upgrade_txn_start))
            last_pool_upgrade_txn_seq_no = get_seq_no(last_pool_upgrade_txn_start)

            # searching for CANCEL for this upgrade submitted after START txn
            last_pool_upgrade_txn_cancel = self.get_upgrade_txn(
                lambda txn:
                get_type(txn) == POOL_UPGRADE and get_payload_data(txn)[ACTION] == CANCEL and
                get_payload_data(txn)[VERSION] == get_payload_data(last_pool_upgrade_txn_start)[VERSION],
                start_no=last_pool_upgrade_txn_seq_no + 1)
            if last_pool_upgrade_txn_cancel:
                logger.info('{} found upgrade CANCEL txn {}'.format(
                    self, last_pool_upgrade_txn_cancel))
                return

            self.handleUpgradeTxn(last_pool_upgrade_txn_start)


Instruction:
Explain what the following Python 3 code does
def didLastExecutedUpgradeSucceeded(self) -> bool:
        lastEventInfo = self.lastActionEventInfo
        if lastEventInfo:
            ev_data = lastEventInfo.data
            currentPkgVersion = NodeControlUtil.curr_pkg_info(ev_data.pkg_name)[0]
            if currentPkgVersion:
                return currentPkgVersion.upstream == ev_data.version
            else:
                logger.warning(
                    "{} failed to get information about package {} "
                    "scheduled for last upgrade"
                    .format(self, ev_data.pkg_name)
                )
        return False

Response: Checks if the last record in upgrade log is about scheduling upgrade. If so checks whether current version is equal to the one in that record. If so checks whether current version is equal to the one in that record. If so returns True.


Instruction:
How would you explain what the following Python 3 function does
def handleUpgradeTxn(self, txn) -> None:
        FINALIZING_EVENT_TYPES = [UpgradeLog.Events.succeeded, UpgradeLog.Events.failed]

        if get_type(txn) != POOL_UPGRADE:
            return

        logger.info("Node '{}' handles upgrade txn {}".format(self.nodeName, txn))
        txn_data = get_payload_data(txn)
        action = txn_data[ACTION]
        version = txn_data[VERSION]
        justification = txn_data.get(JUSTIFICATION)
        pkg_name = txn_data.get(PACKAGE, self.config.UPGRADE_ENTRY)
        upgrade_id = self.get_action_id(txn)

        # TODO test
        try:
            version = src_version_cls(pkg_name)(version)
        except InvalidVersionError as exc:
            logger.warning(
                "{} can't handle upgrade txn with version {} for package {}: {}"
                .format(self, version, pkg_name, exc)
            )
            return

        if action == START:
            # forced txn could have partial schedule list
            if self.nodeId not in txn_data[SCHEDULE]:
                logger.info("Node '{}' disregards upgrade txn {}".format(
                    self.nodeName, txn))
                return

            last_event = self.lastActionEventInfo
            if last_event:
                if (last_event.data.upgrade_id == upgrade_id and
                        last_event.ev_type in FINALIZING_EVENT_TYPES):
                    logger.info(
                        "Node '{}' has already performed an upgrade with upgrade_id {}. "
                        "Last recorded event is {}"
                        .format(self.nodeName, upgrade_id, last_event.data))
                    return

            when = txn_data[SCHEDULE][self.nodeId]
            failTimeout = txn_data.get(TIMEOUT, self.defaultActionTimeout)

            if isinstance(when, str):
                when = dateutil.parser.parse(when)

            new_ev_data = UpgradeLogData(when, version, upgrade_id, pkg_name)

            if self.scheduledAction:
                if self.scheduledAction == new_ev_data:
                    logger.debug(
                        "Node {} already scheduled upgrade to version '{}' "
                        .format(self.nodeName, version))
                    return
                else:
                    logger.info(
                        "Node '{}' cancels previous upgrade and schedules a new one to {}"
                        .format(self.nodeName, version))
                    self._cancelScheduledUpgrade(justification)

            logger.info("Node '{}' schedules upgrade to {}".format(self.nodeName, version))

            self._scheduleUpgrade(new_ev_data, failTimeout)
            return

        if action == CANCEL:
            if (self.scheduledAction and
                    self.scheduledAction.version == version):
                self._cancelScheduledUpgrade(justification)
                logger.info("Node '{}' cancels upgrade to {}".format(
                    self.nodeName, version))
            return

        logger.error(
            "Got {} transaction with unsupported action {}".format(
                POOL_UPGRADE, action))

Response: Handles the transaction of type POOL_UPGRADE and returns the new version of the upgrade.


Instruction:
Given the following Python 3 function, write the documentation
def _scheduleUpgrade(self,
                         ev_data: UpgradeLogData,
                         failTimeout) -> None:
        """
        Schedules node upgrade to a newer version

        :param ev_data: upgrade event parameters
        """
        logger.info(
            "{}'s upgrader processing upgrade for version {}={}"
            .format(self, ev_data.pkg_name, ev_data.version))
        now = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())

        self._notifier.sendMessageUponNodeUpgradeScheduled(
            "Upgrade of package {} on node '{}' to version {} "
            "has been scheduled on {}"
            .format(ev_data.pkg_name, self.nodeName,
                    ev_data.version, ev_data.when))
        self._actionLog.append_scheduled(ev_data)

        callAgent = partial(self._callUpgradeAgent, ev_data, failTimeout)
        delay = 0
        if now < ev_data.when:
            delay = (ev_data.when - now).total_seconds()
        self.scheduledAction = ev_data
        self._schedule(callAgent, delay)

Response: Schedules a node upgrade to a newer version.


Instruction:
Given the following Python 3 function, write the documentation
def _cancelScheduledUpgrade(self, justification=None) -> None:

        if self.scheduledAction:
            why_prefix = ": "
            why = justification
            if justification is None:
                why_prefix = ", "
                why = "cancellation reason not specified"

            ev_data = self.scheduledAction
            logger.info("Cancelling upgrade {}"
                        " of node {}"
                        " of package {}"
                        " to version {}"
                        " scheduled on {}"
                        "{}{}"
                        .format(ev_data.upgrade_id,
                                self.nodeName,
                                ev_data.pkg_name,
                                ev_data.version,
                                ev_data.when,
                                why_prefix,
                                why))

            self._unscheduleAction()
            self._actionLog.append_cancelled(ev_data)
            self._notifier.sendMessageUponPoolUpgradeCancel(
                "Upgrade of package {} on node '{}' to version {} "
                "has been cancelled due to {}"
                .format(ev_data.pkg_name, self.nodeName,
                        ev_data.version, why))

Response: Cancels scheduled upgrade of the current version of the package.


Instruction:
Can you generate the documentation for the following Python 3 function
def _callUpgradeAgent(self, ev_data, failTimeout) -> None:

        logger.info("{}'s upgrader calling agent for upgrade".format(self))
        self._actionLog.append_started(ev_data)
        self._action_start_callback()
        self.scheduledAction = None
        asyncio.ensure_future(
            self._sendUpgradeRequest(ev_data, failTimeout))

Response: Callback which is called when upgrade time come.


Instruction:
How would you implement a function in Python 3 that
checks if the schedule of planned node upgrades is valid.

Response:
def isScheduleValid(self, schedule, node_srvs, force) -> (bool, str):
        """
        Validates schedule of planned node upgrades

        :param schedule: dictionary of node ids and upgrade times
        :param node_srvs: dictionary of node ids and services
        :return: a 2-tuple of whether schedule valid or not and the reason
        """

        # flag "force=True" ignore basic checks! only datetime format is
        # checked
        times = []
        non_demoted_nodes = set([k for k, v in node_srvs.items() if v])
        if not force and set(schedule.keys()) != non_demoted_nodes:
            return False, 'Schedule should contain id of all nodes'
        now = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
        for dateStr in schedule.values():
            try:
                when = dateutil.parser.parse(dateStr)
                if when <= now and not force:
                    return False, '{} is less than current time'.format(when)
                times.append(when)
            except ValueError:
                return False, '{} cannot be parsed to a time'.format(dateStr)
        if force:
            return True, ''
        times = sorted(times)
        for i in range(len(times) - 1):
            diff = (times[i + 1] - times[i]).total_seconds()
            if diff < self.config.MinSepBetweenNodeUpgrades:
                return False, 'time span between upgrades is {} ' \
                              'seconds which is less than specified ' \
                              'in the config'.format(diff)
        return True, ''


Instruction:
Here you have a function in Python 3, explain what it does
def get_token(self, url):
        # A hack to avoid url-encoding the url, since the authorization service
        # doesn't work with correctly encoded urls

        parsed_url = urlparse.urlsplit(url)
        parsed_url = parsed_url._replace(path='/authorization/api')
        self.url = urlparse.urlunsplit(parsed_url)

        response = self.request(method='GET', url='/v1/token?url=' + url)
        return response.result.text

Response: Retrieves a temporary access token for the given url.


Instruction:
Explain what the following Python 3 code does
def synthesize_using_websocket(self,
                                   text,
                                   synthesize_callback,
                                   accept=None,
                                   voice=None,
                                   timings=None,
                                   customization_id=None,
                                   http_proxy_host=None,
                                   http_proxy_port=None,
                                   **kwargs):
        """
        Synthesizes text to spoken audio using web sockets. It supports the use of
        the SSML <mark> element to identify the location of user-specified markers in the audio.
        It can also return timing information for all strings of the input text.
        Note:The service processes one request per connection.

        :param str text: Provides the text that is to be synthesized. The client can pass plain
        text or text that is annotated with the Speech Synthesis Markup Language (SSML). For more
        information, see [Specifying input text](https://console.bluemix.net/docs/services/text-to-speech/http.html#input).
        SSML input can also include the <mark> element;
        see [Specifying an SSML mark](https://console.bluemix.net/docs/services/text-to-speech/word-timing.html#mark).
        The client can pass a maximum of 5 KB of text with the request.
        :param SynthesizeCallback synthesize_callback: The callback method for the websocket.
        :param str accept: Specifies the requested format (MIME type) of the audio. For more information, see [Specifying
        an audio format](https://console.bluemix.net/docs/services/text-to-speech/http.html#format). In addition to the
        supported specifications, you can use */* to specify the default audio format, audio/ogg;codecs=opus.
        :param str voice: The voice to use for synthesis.
        :param list[str] timings: Specifies that the service is to return word timing information for all strings of the
        input text. The service returns the start and end time of each string of the input. Specify words as the lone element
        of the array to request word timings. Specify an empty array or omit the parameter to receive no word timings. For
        more information, see [Obtaining word timings](https://console.bluemix.net/docs/services/text-to-speech/word-timing.html#timing).
        Not supported for Japanese input text.
        :param str customization_id: Specifies the globally unique identifier (GUID) for a custom voice model that is to be used for the
        synthesis. A custom voice model is guaranteed to work only if it matches the language of the voice that is used for the synthesis.
        If you include a customization ID, you must call the method with the service credentials of the custom model's owner. Omit the
        parameter to use the specified voice with no customization. For more information, see [Understanding customization]
        (https://console.bluemix.net/docs/services/text-to-speech/custom-intro.html#customIntro).
        :param str http_proxy_host: http proxy host name.
        :param str http_proxy_port: http proxy port. If not set, set to 80.
        :param dict headers: A `dict` containing the request headers
        :return: A `dict` containing the `SpeechRecognitionResults` response.
        :rtype: dict
        """
        if text is None:
            raise ValueError('text must be provided')
        if synthesize_callback is None:
            raise ValueError('synthesize_callback must be provided')
        if not isinstance(synthesize_callback, SynthesizeCallback):
            raise Exception(
                'Callback is not a derived class of SynthesizeCallback')

        headers = {}
        if self.default_headers is not None:
            headers = self.default_headers.copy()
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))

        if self.token_manager:
            access_token = self.token_manager.get_token()
            headers['Authorization'] = '{0} {1}'.format(BEARER, access_token)
        else:
            authstring = "{0}:{1}".format(self.username, self.password)
            base64_authorization = base64.b64encode(authstring.encode('utf-8')).decode('utf-8')
            headers['Authorization'] = 'Basic {0}'.format(base64_authorization)

        url = self.url.replace('https:', 'wss:')
        params = {
            'voice': voice,
            'customization_id': customization_id,
        }
        params = dict([(k, v) for k, v in params.items() if v is not None])
        url += '/v1/synthesize?{0}'.format(urlencode(params))

        options = {
            'text': text,
            'accept': accept,
            'timings': timings
        }
        options = dict([(k, v) for k, v in options.items() if v is not None])

        SynthesizeListener(options,
                           synthesize_callback,
                           url,
                           headers,
                           http_proxy_host,
                           http_proxy_port,
                           self.verify)

Response: Synthesizes text using web sockets.


Instruction:
Write a Python 3 function that can
classify images. Classify images with built-in or custom classifiers. :param file images_file: An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. :param str images_filename: The filename for images_file. :param str images_file_content_type: The content type of images_file. :param str url: The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. The maximum image size is 10 MB. You can also include images with the **images_file** parameter. :param float threshold: The minimum score a class must have to be displayed in the response. Set the threshold to `0.0` to return all identified classes. :param list[str] owners: The categories of classifiers to apply. The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** is empty. - Use `IBM` to classify against the `default` general classifier. You get the same result if both **classifier_ids** and **owners** parameters are empty. - Use `me` to classify against all your custom classifiers. However, for better performance use **classifier_ids** to specify the specific custom classifiers to apply. - Use both `IBM` and `me` to analyze the image against both classifier categories. :param list[str] classifier_ids: Which classifiers to apply. Overrides the **owners** parameter. You can specify both custom and built-in classifier IDs. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. The following built-in classifier IDs require no training: - `default`: Returns classes from thousands of general tags. - `food`: Enhances specificity and accuracy for images of food items. - `explicit`: Evaluates whether the image might be pornographic. :param str accept_language: The desired language of parts of the response. See the response for details. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse

Response:
def classify(self,
                 images_file=None,
                 images_filename=None,
                 images_file_content_type=None,
                 url=None,
                 threshold=None,
                 owners=None,
                 classifier_ids=None,
                 accept_language=None,
                 **kwargs):
        """
        Classify images.

        Classify images with built-in or custom classifiers.

        :param file images_file: An image file (.gif, .jpg, .png, .tif) or .zip file with
        images. Maximum image size is 10 MB. Include no more than 20 images and limit the
        .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain
        non-ASCII characters. The service assumes UTF-8 encoding if it encounters
        non-ASCII characters.
        You can also include an image with the **url** parameter.
        :param str images_filename: The filename for images_file.
        :param str images_file_content_type: The content type of images_file.
        :param str url: The URL of an image (.gif, .jpg, .png, .tif) to analyze. The
        minimum recommended pixel density is 32X32 pixels, but the service tends to
        perform better with images that are at least 224 x 224 pixels. The maximum image
        size is 10 MB.
        You can also include images with the **images_file** parameter.
        :param float threshold: The minimum score a class must have to be displayed in the
        response. Set the threshold to `0.0` to return all identified classes.
        :param list[str] owners: The categories of classifiers to apply. The
        **classifier_ids** parameter overrides **owners**, so make sure that
        **classifier_ids** is empty.
        - Use `IBM` to classify against the `default` general classifier. You get the same
        result if both **classifier_ids** and **owners** parameters are empty.
        - Use `me` to classify against all your custom classifiers. However, for better
        performance use **classifier_ids** to specify the specific custom classifiers to
        apply.
        - Use both `IBM` and `me` to analyze the image against both classifier categories.
        :param list[str] classifier_ids: Which classifiers to apply. Overrides the
        **owners** parameter. You can specify both custom and built-in classifier IDs. The
        built-in `default` classifier is used if both **classifier_ids** and **owners**
        parameters are empty.
        The following built-in classifier IDs require no training:
        - `default`: Returns classes from thousands of general tags.
        - `food`: Enhances specificity and accuracy for images of food items.
        - `explicit`: Evaluates whether the image might be pornographic.
        :param str accept_language: The desired language of parts of the response. See the
        response for details.
        :param dict headers: A `dict` containing the request headers
        :return: A `DetailedResponse` containing the result, headers and HTTP status code.
        :rtype: DetailedResponse
        """

        headers = {'Accept-Language': accept_language}
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))
        sdk_headers = get_sdk_headers('watson_vision_combined', 'V3',
                                      'classify')
        headers.update(sdk_headers)

        params = {'version': self.version}

        form_data = {}
        if images_file:
            if not images_filename and hasattr(images_file, 'name'):
                images_filename = basename(images_file.name)
            if not images_filename:
                raise ValueError('images_filename must be provided')
            form_data['images_file'] = (images_filename, images_file,
                                        images_file_content_type or
                                        'application/octet-stream')
        if url:
            form_data['url'] = (None, url, 'text/plain')
        if threshold:
            form_data['threshold'] = (None, threshold, 'application/json')
        if owners:
            owners = self._convert_list(owners)
            form_data['owners'] = (None, owners, 'application/json')
        if classifier_ids:
            classifier_ids = self._convert_list(classifier_ids)
            form_data['classifier_ids'] = (None, classifier_ids,
                                           'application/json')

        url = '/v3/classify'
        response = self.request(
            method='POST',
            url=url,
            headers=headers,
            params=params,
            files=form_data,
            accept_json=True)
        return response


Instruction:
Can you tell what is the following Python 3 function doing
def create_classifier(self,
                          name,
                          positive_examples,
                          negative_examples=None,
                          negative_examples_filename=None,
                          **kwargs):
        """
        Create a classifier.

        Train a new multi-faceted classifier on the uploaded image data. Create your
        custom classifier with positive or negative examples. Include at least two sets of
        examples, either two positive example files or one positive and one negative file.
        You can upload a maximum of 256 MB per call.
        Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image
        file names, and classifier and class names). The service assumes UTF-8 encoding if
        it encounters non-ASCII characters.

        :param str name: The name of the new classifier. Encode special characters in
        UTF-8.
        :param dict positive_examples: A dictionary that contains the value for each
        classname. The value is a .zip file of images that depict the visual subject of a
        class in the new classifier. You can include more than one positive example file
        in a call.
        Specify the parameter name by appending `_positive_examples` to the class name.
        For example, `goldenretriever_positive_examples` creates the class
        **goldenretriever**.
        Include at least 10 images in .jpg or .png format. The minimum recommended image
        resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100
        MB per .zip file.
        Encode special characters in the file name in UTF-8.
        :param file negative_examples: A .zip file of images that do not depict the visual
        subject of any of the classes of the new classifier. Must contain a minimum of 10
        images.
        Encode special characters in the file name in UTF-8.
        :param str negative_examples_filename: The filename for negative_examples.
        :param dict headers: A `dict` containing the request headers
        :return: A `DetailedResponse` containing the result, headers and HTTP status code.
        :rtype: DetailedResponse
        """

        if name is None:
            raise ValueError('name must be provided')
        if not positive_examples:
            raise ValueError('positive_examples must be provided')

        headers = {}
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))
        sdk_headers = get_sdk_headers('watson_vision_combined', 'V3',
                                      'create_classifier')
        headers.update(sdk_headers)

        params = {'version': self.version}

        form_data = {}
        form_data['name'] = (None, name, 'text/plain')
        for key in positive_examples.keys():
            part_name = '%s_positive_examples' % (key)
            value = positive_examples[key]
            if hasattr(value, 'name'):
                filename = basename(value.name)
            form_data[part_name] = (filename, value, 'application/octet-stream')
        if negative_examples:
            if not negative_examples_filename and hasattr(
                    negative_examples, 'name'):
                negative_examples_filename = basename(negative_examples.name)
            if not negative_examples_filename:
                raise ValueError('negative_examples_filename must be provided')
            form_data['negative_examples'] = (negative_examples_filename,
                                              negative_examples,
                                              'application/octet-stream')

        url = '/v3/classifiers'
        response = self.request(
            method='POST',
            url=url,
            headers=headers,
            params=params,
            files=form_data,
            accept_json=True)
        return response

Response: Create a new multi - faceted classifier.


Instruction:
Make a summary of the following Python 3 code
def delete_classifier(self, classifier_id, **kwargs):

        if classifier_id is None:
            raise ValueError('classifier_id must be provided')

        headers = {}
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))
        sdk_headers = get_sdk_headers('watson_vision_combined', 'V3',
                                      'delete_classifier')
        headers.update(sdk_headers)

        params = {'version': self.version}

        url = '/v3/classifiers/{0}'.format(
            *self._encode_path_vars(classifier_id))
        response = self.request(
            method='DELETE',
            url=url,
            headers=headers,
            params=params,
            accept_json=True)
        return response

Response:
Delete a classifier.

        :param str classifier_id: The ID of the classifier.
        :param dict headers: A `dict` containing the request headers
        :return: A `DetailedResponse` containing the result, headers and HTTP status code.
        :rtype: DetailedResponse


Instruction:
Can you generate the documentation for the following Python 3 function
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'class_name') and self.class_name is not None:
            _dict['class'] = self.class_name
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Implement a Python 3 function for
returning a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'class_name') and self.class_name is not None:
            _dict['class'] = self.class_name
        if hasattr(self, 'score') and self.score is not None:
            _dict['score'] = self.score
        if hasattr(self, 'type_hierarchy') and self.type_hierarchy is not None:
            _dict['type_hierarchy'] = self.type_hierarchy
        return _dict


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _from_dict(cls, _dict):
        args = {}
        if 'source_url' in _dict:
            args['source_url'] = _dict.get('source_url')
        if 'resolved_url' in _dict:
            args['resolved_url'] = _dict.get('resolved_url')
        if 'image' in _dict:
            args['image'] = _dict.get('image')
        if 'error' in _dict:
            args['error'] = ErrorInfo._from_dict(_dict.get('error'))
        if 'classifiers' in _dict:
            args['classifiers'] = [
                ClassifierResult._from_dict(x)
                for x in (_dict.get('classifiers'))
            ]
        else:
            raise ValueError(
                'Required property \'classifiers\' not present in ClassifiedImage JSON'
            )
        return cls(**args)

Response: Initialize a ClassifiedImage object from a json dictionary.


Instruction:
Create a Python 3 function to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'source_url') and self.source_url is not None:
            _dict['source_url'] = self.source_url
        if hasattr(self, 'resolved_url') and self.resolved_url is not None:
            _dict['resolved_url'] = self.resolved_url
        if hasattr(self, 'image') and self.image is not None:
            _dict['image'] = self.image
        if hasattr(self, 'error') and self.error is not None:
            _dict['error'] = self.error._to_dict()
        if hasattr(self, 'classifiers') and self.classifiers is not None:
            _dict['classifiers'] = [x._to_dict() for x in self.classifiers]
        return _dict


Instruction:
Make a summary of the following Python 3 code
def _from_dict(cls, _dict):
        args = {}
        if 'classifier_id' in _dict:
            args['classifier_id'] = _dict.get('classifier_id')
        else:
            raise ValueError(
                'Required property \'classifier_id\' not present in Classifier JSON'
            )
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        else:
            raise ValueError(
                'Required property \'name\' not present in Classifier JSON')
        if 'owner' in _dict:
            args['owner'] = _dict.get('owner')
        if 'status' in _dict:
            args['status'] = _dict.get('status')
        if 'core_ml_enabled' in _dict:
            args['core_ml_enabled'] = _dict.get('core_ml_enabled')
        if 'explanation' in _dict:
            args['explanation'] = _dict.get('explanation')
        if 'created' in _dict:
            args['created'] = string_to_datetime(_dict.get('created'))
        if 'classes' in _dict:
            args['classes'] = [
                Class._from_dict(x) for x in (_dict.get('classes'))
            ]
        if 'retrained' in _dict:
            args['retrained'] = string_to_datetime(_dict.get('retrained'))
        if 'updated' in _dict:
            args['updated'] = string_to_datetime(_dict.get('updated'))
        return cls(**args)

Response: Initialize a Classifier object from a json dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'classifier_id') and self.classifier_id is not None:
            _dict['classifier_id'] = self.classifier_id
        if hasattr(self, 'name') and self.name is not None:
            _dict['name'] = self.name
        if hasattr(self, 'owner') and self.owner is not None:
            _dict['owner'] = self.owner
        if hasattr(self, 'status') and self.status is not None:
            _dict['status'] = self.status
        if hasattr(self,
                   'core_ml_enabled') and self.core_ml_enabled is not None:
            _dict['core_ml_enabled'] = self.core_ml_enabled
        if hasattr(self, 'explanation') and self.explanation is not None:
            _dict['explanation'] = self.explanation
        if hasattr(self, 'created') and self.created is not None:
            _dict['created'] = datetime_to_string(self.created)
        if hasattr(self, 'classes') and self.classes is not None:
            _dict['classes'] = [x._to_dict() for x in self.classes]
        if hasattr(self, 'retrained') and self.retrained is not None:
            _dict['retrained'] = datetime_to_string(self.retrained)
        if hasattr(self, 'updated') and self.updated is not None:
            _dict['updated'] = datetime_to_string(self.updated)
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
How would you code a function in Python 3 to
initialize a ClassifierResult object from a json dictionary.

Response:
def _from_dict(cls, _dict):
        """Initialize a ClassifierResult object from a json dictionary."""
        args = {}
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        else:
            raise ValueError(
                'Required property \'name\' not present in ClassifierResult JSON'
            )
        if 'classifier_id' in _dict:
            args['classifier_id'] = _dict.get('classifier_id')
        else:
            raise ValueError(
                'Required property \'classifier_id\' not present in ClassifierResult JSON'
            )
        if 'classes' in _dict:
            args['classes'] = [
                ClassResult._from_dict(x) for x in (_dict.get('classes'))
            ]
        else:
            raise ValueError(
                'Required property \'classes\' not present in ClassifierResult JSON'
            )
        return cls(**args)


Instruction:
Here you have a function in Python 3, explain what it does
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'name') and self.name is not None:
            _dict['name'] = self.name
        if hasattr(self, 'classifier_id') and self.classifier_id is not None:
            _dict['classifier_id'] = self.classifier_id
        if hasattr(self, 'classes') and self.classes is not None:
            _dict['classes'] = [x._to_dict() for x in self.classes]
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Can you write a function in Python 3 where it
returns a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'classifiers') and self.classifiers is not None:
            _dict['classifiers'] = [x._to_dict() for x in self.classifiers]
        return _dict


Instruction:
Can you create a Python 3 function that
initializes a DetectedFaces object from a json dictionary.

Response:
def _from_dict(cls, _dict):
        """Initialize a DetectedFaces object from a json dictionary."""
        args = {}
        if 'images_processed' in _dict:
            args['images_processed'] = _dict.get('images_processed')
        else:
            raise ValueError(
                'Required property \'images_processed\' not present in DetectedFaces JSON'
            )
        if 'images' in _dict:
            args['images'] = [
                ImageWithFaces._from_dict(x) for x in (_dict.get('images'))
            ]
        else:
            raise ValueError(
                'Required property \'images\' not present in DetectedFaces JSON'
            )
        if 'warnings' in _dict:
            args['warnings'] = [
                WarningInfo._from_dict(x) for x in (_dict.get('warnings'))
            ]
        return cls(**args)


Instruction:
Write a Python 3 script to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self,
                   'images_processed') and self.images_processed is not None:
            _dict['images_processed'] = self.images_processed
        if hasattr(self, 'images') and self.images is not None:
            _dict['images'] = [x._to_dict() for x in self.images]
        if hasattr(self, 'warnings') and self.warnings is not None:
            _dict['warnings'] = [x._to_dict() for x in self.warnings]
        return _dict


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'code') and self.code is not None:
            _dict['code'] = self.code
        if hasattr(self, 'description') and self.description is not None:
            _dict['description'] = self.description
        if hasattr(self, 'error_id') and self.error_id is not None:
            _dict['error_id'] = self.error_id
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Write a Python 3 function for
initializing a Face object from a json dictionary.

Response:
def _from_dict(cls, _dict):
        """Initialize a Face object from a json dictionary."""
        args = {}
        if 'age' in _dict:
            args['age'] = FaceAge._from_dict(_dict.get('age'))
        if 'gender' in _dict:
            args['gender'] = FaceGender._from_dict(_dict.get('gender'))
        if 'face_location' in _dict:
            args['face_location'] = FaceLocation._from_dict(
                _dict.get('face_location'))
        return cls(**args)


Instruction:
Write a Python 3 script for
returning a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'age') and self.age is not None:
            _dict['age'] = self.age._to_dict()
        if hasattr(self, 'gender') and self.gender is not None:
            _dict['gender'] = self.gender._to_dict()
        if hasattr(self, 'face_location') and self.face_location is not None:
            _dict['face_location'] = self.face_location._to_dict()
        return _dict


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'min') and self.min is not None:
            _dict['min'] = self.min
        if hasattr(self, 'max') and self.max is not None:
            _dict['max'] = self.max
        if hasattr(self, 'score') and self.score is not None:
            _dict['score'] = self.score
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
How would you code a function in Python 3 to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'gender') and self.gender is not None:
            _dict['gender'] = self.gender
        if hasattr(self, 'gender_label') and self.gender_label is not None:
            _dict['gender_label'] = self.gender_label
        if hasattr(self, 'score') and self.score is not None:
            _dict['score'] = self.score
        return _dict


Instruction:
Write a Python 3 function that can
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'width') and self.width is not None:
            _dict['width'] = self.width
        if hasattr(self, 'height') and self.height is not None:
            _dict['height'] = self.height
        if hasattr(self, 'left') and self.left is not None:
            _dict['left'] = self.left
        if hasattr(self, 'top') and self.top is not None:
            _dict['top'] = self.top
        return _dict


Instruction:
Write a Python 3 script for
returning a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'warning_id') and self.warning_id is not None:
            _dict['warning_id'] = self.warning_id
        if hasattr(self, 'description') and self.description is not None:
            _dict['description'] = self.description
        return _dict


Instruction:
Given the following Python 3 function, write the documentation
def message(self,
                assistant_id,
                session_id,
                input=None,
                context=None,
                **kwargs):
        """
        Send user input to assistant.

        Send user input to an assistant and receive a response.
        There is no rate limit for this operation.

        :param str assistant_id: Unique identifier of the assistant. You can find the
        assistant ID of an assistant on the **Assistants** tab of the Watson Assistant
        tool. For information about creating assistants, see the
        [documentation](https://console.bluemix.net/docs/services/assistant/assistant-add.html#assistant-add-task).
        **Note:** Currently, the v2 API does not support creating assistants.
        :param str session_id: Unique identifier of the session.
        :param MessageInput input: An input object that includes the input text.
        :param MessageContext context: State information for the conversation. The context
        is stored by the assistant on a per-session basis. You can use this property to
        set or modify context variables, which can also be accessed by dialog nodes.
        :param dict headers: A `dict` containing the request headers
        :return: A `DetailedResponse` containing the result, headers and HTTP status code.
        :rtype: DetailedResponse
        """

        if assistant_id is None:
            raise ValueError('assistant_id must be provided')
        if session_id is None:
            raise ValueError('session_id must be provided')
        if input is not None:
            input = self._convert_model(input, MessageInput)
        if context is not None:
            context = self._convert_model(context, MessageContext)

        headers = {}
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))
        sdk_headers = get_sdk_headers('conversation', 'V2', 'message')
        headers.update(sdk_headers)

        params = {'version': self.version}

        data = {'input': input, 'context': context}

        url = '/v2/assistants/{0}/sessions/{1}/message'.format(
            *self._encode_path_vars(assistant_id, session_id))
        response = self.request(
            method='POST',
            url=url,
            headers=headers,
            params=params,
            json=data,
            accept_json=True)
        return response

Response:
Send user input to assistant.

        Send user input to an assistant and receive a response.
        There is no rate limit for this operation.

        :param str assistant_id: Unique identifier of the assistant. You can find the
        assistant ID of an assistant on the **Assistants** tab of the Watson Assistant
        tool. For information about creating assistants, see the
        [documentation](https://console.bluemix.net/docs/services/assistant/assistant-add.html#assistant-add-task).
        **Note:** Currently, the v2 API does not support creating assistants.
        :param str session_id: Unique identifier of the session.
        :param MessageInput input: An input object that includes the input text.
        :param MessageContext context: State information for the conversation. The context
        is stored by the assistant on a per-session basis. You can use this property to
        set or modify context variables, which can also be accessed by dialog nodes.
        :param dict headers: A `dict` containing the request headers
        :return: A `DetailedResponse` containing the result, headers and HTTP status code.
        :rtype: DetailedResponse


Instruction:
Can you tell what is the following Python 3 function doing
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'group') and self.group is not None:
            _dict['group'] = self.group
        if hasattr(self, 'location') and self.location is not None:
            _dict['location'] = self.location
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Implement a function in Python 3 to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'level') and self.level is not None:
            _dict['level'] = self.level
        if hasattr(self, 'message') and self.message is not None:
            _dict['message'] = self.message
        return _dict


Instruction:
Can you create a Python 3 function that
returns a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'name') and self.name is not None:
            _dict['name'] = self.name
        if hasattr(self, 'action_type') and self.action_type is not None:
            _dict['type'] = self.action_type
        if hasattr(self, 'parameters') and self.parameters is not None:
            _dict['parameters'] = self.parameters
        if hasattr(self,
                   'result_variable') and self.result_variable is not None:
            _dict['result_variable'] = self.result_variable
        if hasattr(self, 'credentials') and self.credentials is not None:
            _dict['credentials'] = self.credentials
        return _dict


Instruction:
Write a Python 3 script to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'input') and self.input is not None:
            _dict['input'] = self.input._to_dict()
        return _dict


Instruction:
Can you write a function in Python 3 where it
returns a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'dialog_node') and self.dialog_node is not None:
            _dict['dialog_node'] = self.dialog_node
        if hasattr(self, 'title') and self.title is not None:
            _dict['title'] = self.title
        if hasattr(self, 'conditions') and self.conditions is not None:
            _dict['conditions'] = self.conditions
        return _dict


Instruction:
Here you have a function in Python 3, explain what it does
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'label') and self.label is not None:
            _dict['label'] = self.label
        if hasattr(self, 'value') and self.value is not None:
            _dict['value'] = self.value._to_dict()
        if hasattr(self, 'output') and self.output is not None:
            _dict['output'] = self.output
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
How would you explain what the following Python 3 function does
def _from_dict(cls, _dict):
        args = {}
        if 'global' in _dict:
            args['global_'] = MessageContextGlobal._from_dict(
                _dict.get('global'))
        if 'skills' in _dict:
            args['skills'] = MessageContextSkills._from_dict(
                _dict.get('skills'))
        return cls(**args)

Response: Initialize a MessageContext object from a json dictionary.


Instruction:
Implement a Python 3 function for
returning a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'global_') and self.global_ is not None:
            _dict['global'] = self.global_._to_dict()
        if hasattr(self, 'skills') and self.skills is not None:
            _dict['skills'] = self.skills._to_dict()
        return _dict


Instruction:
Can you implement a function in Python 3 that
returns a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'system') and self.system is not None:
            _dict['system'] = self.system._to_dict()
        return _dict


Instruction:
Can you tell what is the following Python 3 function doing
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'timezone') and self.timezone is not None:
            _dict['timezone'] = self.timezone
        if hasattr(self, 'user_id') and self.user_id is not None:
            _dict['user_id'] = self.user_id
        if hasattr(self, 'turn_count') and self.turn_count is not None:
            _dict['turn_count'] = self.turn_count
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Implement a Python 3 function for
initializing a MessageInput object from a json dictionary.

Response:
def _from_dict(cls, _dict):
        """Initialize a MessageInput object from a json dictionary."""
        args = {}
        if 'message_type' in _dict:
            args['message_type'] = _dict.get('message_type')
        if 'text' in _dict:
            args['text'] = _dict.get('text')
        if 'options' in _dict:
            args['options'] = MessageInputOptions._from_dict(
                _dict.get('options'))
        if 'intents' in _dict:
            args['intents'] = [
                RuntimeIntent._from_dict(x) for x in (_dict.get('intents'))
            ]
        if 'entities' in _dict:
            args['entities'] = [
                RuntimeEntity._from_dict(x) for x in (_dict.get('entities'))
            ]
        if 'suggestion_id' in _dict:
            args['suggestion_id'] = _dict.get('suggestion_id')
        return cls(**args)


Instruction:
Implement a function in Python 3 to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'message_type') and self.message_type is not None:
            _dict['message_type'] = self.message_type
        if hasattr(self, 'text') and self.text is not None:
            _dict['text'] = self.text
        if hasattr(self, 'options') and self.options is not None:
            _dict['options'] = self.options._to_dict()
        if hasattr(self, 'intents') and self.intents is not None:
            _dict['intents'] = [x._to_dict() for x in self.intents]
        if hasattr(self, 'entities') and self.entities is not None:
            _dict['entities'] = [x._to_dict() for x in self.entities]
        if hasattr(self, 'suggestion_id') and self.suggestion_id is not None:
            _dict['suggestion_id'] = self.suggestion_id
        return _dict


Instruction:
Make a summary of the following Python 3 code
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'debug') and self.debug is not None:
            _dict['debug'] = self.debug
        if hasattr(self, 'restart') and self.restart is not None:
            _dict['restart'] = self.restart
        if hasattr(self,
                   'alternate_intents') and self.alternate_intents is not None:
            _dict['alternate_intents'] = self.alternate_intents
        if hasattr(self, 'return_context') and self.return_context is not None:
            _dict['return_context'] = self.return_context
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Write a Python 3 script for
initializing a MessageOutput object from a json dictionary.

Response:
def _from_dict(cls, _dict):
        """Initialize a MessageOutput object from a json dictionary."""
        args = {}
        if 'generic' in _dict:
            args['generic'] = [
                DialogRuntimeResponseGeneric._from_dict(x)
                for x in (_dict.get('generic'))
            ]
        if 'intents' in _dict:
            args['intents'] = [
                RuntimeIntent._from_dict(x) for x in (_dict.get('intents'))
            ]
        if 'entities' in _dict:
            args['entities'] = [
                RuntimeEntity._from_dict(x) for x in (_dict.get('entities'))
            ]
        if 'actions' in _dict:
            args['actions'] = [
                DialogNodeAction._from_dict(x) for x in (_dict.get('actions'))
            ]
        if 'debug' in _dict:
            args['debug'] = MessageOutputDebug._from_dict(_dict.get('debug'))
        if 'user_defined' in _dict:
            args['user_defined'] = _dict.get('user_defined')
        return cls(**args)


Instruction:
How would you explain what the following Python 3 function does
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'generic') and self.generic is not None:
            _dict['generic'] = [x._to_dict() for x in self.generic]
        if hasattr(self, 'intents') and self.intents is not None:
            _dict['intents'] = [x._to_dict() for x in self.intents]
        if hasattr(self, 'entities') and self.entities is not None:
            _dict['entities'] = [x._to_dict() for x in self.entities]
        if hasattr(self, 'actions') and self.actions is not None:
            _dict['actions'] = [x._to_dict() for x in self.actions]
        if hasattr(self, 'debug') and self.debug is not None:
            _dict['debug'] = self.debug._to_dict()
        if hasattr(self, 'user_defined') and self.user_defined is not None:
            _dict['user_defined'] = self.user_defined
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Write a Python 3 function that can
initialize a MessageOutputDebug object from a json dictionary.

Response:
def _from_dict(cls, _dict):
        """Initialize a MessageOutputDebug object from a json dictionary."""
        args = {}
        if 'nodes_visited' in _dict:
            args['nodes_visited'] = [
                DialogNodesVisited._from_dict(x)
                for x in (_dict.get('nodes_visited'))
            ]
        if 'log_messages' in _dict:
            args['log_messages'] = [
                DialogLogMessage._from_dict(x)
                for x in (_dict.get('log_messages'))
            ]
        if 'branch_exited' in _dict:
            args['branch_exited'] = _dict.get('branch_exited')
        if 'branch_exited_reason' in _dict:
            args['branch_exited_reason'] = _dict.get('branch_exited_reason')
        return cls(**args)


Instruction:
Explain what the following Python 3 code does
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'nodes_visited') and self.nodes_visited is not None:
            _dict['nodes_visited'] = [x._to_dict() for x in self.nodes_visited]
        if hasattr(self, 'log_messages') and self.log_messages is not None:
            _dict['log_messages'] = [x._to_dict() for x in self.log_messages]
        if hasattr(self, 'branch_exited') and self.branch_exited is not None:
            _dict['branch_exited'] = self.branch_exited
        if hasattr(self, 'branch_exited_reason'
                  ) and self.branch_exited_reason is not None:
            _dict['branch_exited_reason'] = self.branch_exited_reason
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
How would you explain what the following Python 3 function does
def _from_dict(cls, _dict):
        args = {}
        if 'output' in _dict:
            args['output'] = MessageOutput._from_dict(_dict.get('output'))
        else:
            raise ValueError(
                'Required property \'output\' not present in MessageResponse JSON'
            )
        if 'context' in _dict:
            args['context'] = MessageContext._from_dict(_dict.get('context'))
        return cls(**args)

Response: Initialize a MessageResponse object from a json dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'output') and self.output is not None:
            _dict['output'] = self.output._to_dict()
        if hasattr(self, 'context') and self.context is not None:
            _dict['context'] = self.context._to_dict()
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Can you tell what is the following Python 3 function doing
def _from_dict(cls, _dict):
        args = {}
        if 'entity' in _dict:
            args['entity'] = _dict.get('entity')
        else:
            raise ValueError(
                'Required property \'entity\' not present in RuntimeEntity JSON'
            )
        if 'location' in _dict:
            args['location'] = _dict.get('location')
        else:
            raise ValueError(
                'Required property \'location\' not present in RuntimeEntity JSON'
            )
        if 'value' in _dict:
            args['value'] = _dict.get('value')
        else:
            raise ValueError(
                'Required property \'value\' not present in RuntimeEntity JSON')
        if 'confidence' in _dict:
            args['confidence'] = _dict.get('confidence')
        if 'metadata' in _dict:
            args['metadata'] = _dict.get('metadata')
        if 'groups' in _dict:
            args['groups'] = [
                CaptureGroup._from_dict(x) for x in (_dict.get('groups'))
            ]
        return cls(**args)

Response: Initialize a RuntimeEntity object from a json dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def _to_dict(self):
        _dict = {}
        if hasattr(self, 'entity') and self.entity is not None:
            _dict['entity'] = self.entity
        if hasattr(self, 'location') and self.location is not None:
            _dict['location'] = self.location
        if hasattr(self, 'value') and self.value is not None:
            _dict['value'] = self.value
        if hasattr(self, 'confidence') and self.confidence is not None:
            _dict['confidence'] = self.confidence
        if hasattr(self, 'metadata') and self.metadata is not None:
            _dict['metadata'] = self.metadata
        if hasattr(self, 'groups') and self.groups is not None:
            _dict['groups'] = [x._to_dict() for x in self.groups]
        return _dict

Response: Return a json dictionary representing this model.


Instruction:
Write a Python 3 script for
returning a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'intent') and self.intent is not None:
            _dict['intent'] = self.intent
        if hasattr(self, 'confidence') and self.confidence is not None:
            _dict['confidence'] = self.confidence
        return _dict


Instruction:
Write a Python 3 script to
return a json dictionary representing this model.

Response:
def _to_dict(self):
        """Return a json dictionary representing this model."""
        _dict = {}
        if hasattr(self, 'session_id') and self.session_id is not None:
            _dict['session_id'] = self.session_id
        return _dict


Instruction:
Given the following Python 3 function, write the documentation
def analyze(self,
                features,
                text=None,
                html=None,
                url=None,
                clean=None,
                xpath=None,
                fallback_to_raw=None,
                return_analyzed_text=None,
                language=None,
                limit_text_characters=None,
                **kwargs):
        """
        Analyze text.

        Analyzes text, HTML, or a public webpage for the following features:
        - Categories
        - Concepts
        - Emotion
        - Entities
        - Keywords
        - Metadata
        - Relations
        - Semantic roles
        - Sentiment
        - Syntax (Experimental).

        :param Features features: Specific features to analyze the document for.
        :param str text: The plain text to analyze. One of the `text`, `html`, or `url`
        parameters is required.
        :param str html: The HTML file to analyze. One of the `text`, `html`, or `url`
        parameters is required.
        :param str url: The webpage to analyze. One of the `text`, `html`, or `url`
        parameters is required.
        :param bool clean: Set this to `false` to disable webpage cleaning. To learn more
        about webpage cleaning, see the [Analyzing
        webpages](https://cloud.ibm.com/docs/services/natural-language-understanding/analyzing-webpages.html)
        documentation.
        :param str xpath: An [XPath
        query](https://cloud.ibm.com/docs/services/natural-language-understanding/analyzing-webpages.html#xpath)
        to perform on `html` or `url` input. Results of the query will be appended to the
        cleaned webpage text before it is analyzed. To analyze only the results of the
        XPath query, set the `clean` parameter to `false`.
        :param bool fallback_to_raw: Whether to use raw HTML content if text cleaning
        fails.
        :param bool return_analyzed_text: Whether or not to return the analyzed text.
        :param str language: ISO 639-1 code that specifies the language of your text. This
        overrides automatic language detection. Language support differs depending on the
        features you include in your analysis. See [Language
        support](https://www.bluemix.net/docs/services/natural-language-understanding/language-support.html)
        for more information.
        :param int limit_text_characters: Sets the maximum number of characters that are
        processed by the service.
        :param dict headers: A `dict` containing the request headers
        :return: A `DetailedResponse` containing the result, headers and HTTP status code.
        :rtype: DetailedResponse
        """

        if features is None:
            raise ValueError('features must be provided')
        features = self._convert_model(features, Features)

        headers = {}
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))
        sdk_headers = get_sdk_headers('natural-language-understanding', 'V1',
                                      'analyze')
        headers.update(sdk_headers)

        params = {'version': self.version}

        data = {
            'features': features,
            'text': text,
            'html': html,
            'url': url,
            'clean': clean,
            'xpath': xpath,
            'fallback_to_raw': fallback_to_raw,
            'return_analyzed_text': return_analyzed_text,
            'language': language,
            'limit_text_characters': limit_text_characters
        }

        url = '/v1/analyze'
        response = self.request(
            method='POST',
            url=url,
            headers=headers,
            params=params,
            json=data,
            accept_json=True)
        return response

Response: Analyze the text of a specific language.


Instruction:
Make a summary of the following Python 3 code
def list_models(self, **kwargs):

        headers = {}
        if 'headers' in kwargs:
            headers.update(kwargs.get('headers'))
        sdk_headers = get_sdk_headers('natural-language-understanding', 'V1',
                                      'list_models')
        headers.update(sdk_headers)

        params = {'version': self.version}

        url = '/v1/models'
        response = self.request(
            method='GET',
            url=url,
            headers=headers,
            params=params,
            accept_json=True)
        return response

Response: List the available models.