Instruction:
Can you create a Python 3 function that
converts html to text.

Response:
def extract_text(html,
                 guess_punct_space=True,
                 guess_layout=True,
                 newline_tags=NEWLINE_TAGS,
                 double_newline_tags=DOUBLE_NEWLINE_TAGS):
    """
    Convert html to text, cleaning invisible content such as styles.

    Almost the same as normalize-space xpath, but this also
    adds spaces between inline elements (like <span>) which are
    often used as block elements in html markup, and adds appropriate
    newlines to make output better formatted.

    html should be a unicode string or an already parsed lxml.html element.

    ``html_text.etree_to_text`` is a lower-level function which only accepts
    an already parsed lxml.html Element, and is not doing html cleaning itself.

    When guess_punct_space is True (default), no extra whitespace is added
    for punctuation. This has a slight (around 10%) performance overhead
    and is just a heuristic.

    When guess_layout is True (default), a newline is added
    before and after ``newline_tags`` and two newlines are added before
    and after ``double_newline_tags``. This heuristic makes the extracted
    text more similar to how it is rendered in the browser.

    Default newline and double newline tags can be found in
    `html_text.NEWLINE_TAGS` and `html_text.DOUBLE_NEWLINE_TAGS`.
    """
    if html is None:
        return ''
    cleaned = _cleaned_html_tree(html)
    return etree_to_text(
        cleaned,
        guess_punct_space=guess_punct_space,
        guess_layout=guess_layout,
        newline_tags=newline_tags,
        double_newline_tags=double_newline_tags,
    )


Instruction:
Write a Python 3 function for
getting the JSON file from ArcGIS

Response:
def get_json(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'):
        """
        Gets the JSON file from ArcGIS
        """
        params = {
                'where': where,
                'outFields': ", ".join(fields),
                'returnGeometry': True,
                'outSR': srid,
                'f': "pjson",
                'orderByFields': self.object_id_field,
                'returnCountOnly': count_only
            }
        if self.token:
            params['token'] = self.token
        if self.geom_type:
            params.update({'geometryType': self.geom_type})
        response = requests.get(self._build_query_request(layer), params=params)
        return response.json()


Instruction:
Here you have a function in Python 3, explain what it does
def get_descriptor_for_layer(self, layer):
        if not layer in self._layer_descriptor_cache:
            params = {'f': 'pjson'}
            if self.token:
                params['token'] = self.token
            response = requests.get(self._build_request(layer), params=params)
            self._layer_descriptor_cache[layer] = response.json()
        return self._layer_descriptor_cache[layer]

Response: Returns the standard JSON descriptor for the layer.


Instruction:
Can you create a Python 3 function that
enumerates all of the field names for a given layer.

Response:
def enumerate_layer_fields(self, layer):
        """
        Pulls out all of the field names for a layer.
        """
        descriptor = self.get_descriptor_for_layer(layer)
        return [field['name'] for field in descriptor['fields']]


Instruction:
Can you create a Python 3 function that
gets a single object from the KMZ.

Response:
def get(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'):
        """
        Gets a layer and returns it as honest to God GeoJSON.

        WHERE 1 = 1 causes us to get everything. We use OBJECTID in the WHERE clause
        to paginate, so don't use OBJECTID in your WHERE clause unless you're going to
        query under 1000 objects.
        """
        base_where = where
        # By default we grab all of the fields. Technically I think
        # we can just do "*" for all fields, but I found this was buggy in
        # the KMZ mode. I'd rather be explicit.
        fields = fields or self.enumerate_layer_fields(layer)

        jsobj = self.get_json(layer, where, fields, count_only, srid)

        # Sometimes you just want to know how far there is to go.
        if count_only:
            return jsobj.get('count')

        # If there is no geometry, we default to assuming it's a Table type
        # data format, and we dump a simple (non-geo) json of all of the data.
        if not jsobj.get('geometryType', None):
            return self.getTable(layer, where, fields, jsobj=jsobj)

        # From what I can tell, the entire layer tends to be of the same type,
        # so we only have to determine the parsing function once.
        geom_parser = self._determine_geom_parser(jsobj.get('geometryType'))

        features = []
        # We always want to run once, and then break out as soon as we stop
        # getting exceededTransferLimit.
        while True:
            features += [self.esri_to_geojson(feat, geom_parser) for feat in jsobj.get('features')]
            if jsobj.get('exceededTransferLimit', False) == False:
                break
            # If we've hit the transfer limit we offset by the last OBJECTID
            # returned and keep moving along.
            where = "%s > %s" % (self.object_id_field, features[-1]['properties'].get(self.object_id_field))
            if base_where != "1 = 1" :
                # If we have another WHERE filter we needed to tack that back on.
                where += " AND %s" % base_where
            jsobj = self.get_json(layer, where, fields, count_only, srid)

        return {
            'type': "FeatureCollection",
            'features': features
        }


Instruction:
Here you have a function in Python 3, explain what it does
def getMultiple(self, layers, where="1 = 1", fields=[], srid='4326', layer_name_field=None):
        features = []
        for layer in layers:
            get_fields = fields or self.enumerate_layer_fields(layer)
            this_layer = self.get(layer, where, get_fields, False, srid).get('features')
            if layer_name_field:
                descriptor = self.get_descriptor_for_layer(layer)
                layer_name = descriptor.get('name')
                for feature in this_layer:
                    feature['properties'][layer_name_field] = layer_name
            features += this_layer
        return {
            'type': "FeatureCollection",
            'features': features
        }

Response: Get a bunch of layers and concatenate them together into one.


Instruction:
Here you have a function in Python 3, explain what it does
def get_version(extension, workflow_file):
    '''Determines the version of a .py, .wdl, or .cwl file.'''
    if extension == 'py' and two_seven_compatible(workflow_file):
        return '2.7'
    elif extension == 'cwl':
        return yaml.load(open(workflow_file))['cwlVersion']
    else:  # Must be a wdl file.
        # Borrowed from https://github.com/Sage-Bionetworks/synapse-orchestrator/blob/develop/synorchestrator/util.py#L142
        try:
            return [l.lstrip('version') for l in workflow_file.splitlines() if 'version' in l.split(' ')][0]
        except IndexError:
            return 'draft-2'

Response: Determines the version of a. py wdl or. cwl file.


Instruction:
Write a Python 3 script for
returning the version of the file and the file extension.

Response:
def wf_info(workflow_path):
    """
    Returns the version of the file and the file extension.

    Assumes that the file path is to the file directly ie, ends with a valid file extension.Supports checking local
    files as well as files at http:// and https:// locations. Files at these remote locations are recreated locally to
    enable our approach to version checking, then removed after version is extracted.
    """

    supported_formats = ['py', 'wdl', 'cwl']
    file_type = workflow_path.lower().split('.')[-1]  # Grab the file extension
    workflow_path = workflow_path if ':' in workflow_path else 'file://' + workflow_path

    if file_type in supported_formats:
        if workflow_path.startswith('file://'):
            version = get_version(file_type, workflow_path[7:])
        elif workflow_path.startswith('https://') or workflow_path.startswith('http://'):
            # If file not local go fetch it.
            html = urlopen(workflow_path).read()
            local_loc = os.path.join(os.getcwd(), 'fetchedFromRemote.' + file_type)
            with open(local_loc, 'w') as f:
                f.write(html.decode())
            version = wf_info('file://' + local_loc)[0]  # Don't take the file_type here, found it above.
            os.remove(local_loc)  # TODO: Find a way to avoid recreating file before version determination.
        else:
            raise NotImplementedError('Unsupported workflow file location: {}. Must be local or HTTP(S).'.format(workflow_path))
    else:
        raise TypeError('Unsupported workflow type: .{}. Must be {}.'.format(file_type, '.py, .cwl, or .wdl'))
    return version, file_type.upper()


Instruction:
Can you write a function in Python 3 where it
modifies relative paths in a json / yaml file to be relative to where the json / yaml file is located.

Response:
def modify_jsonyaml_paths(jsonyaml_file):
    """
    Changes relative paths in a json/yaml file to be relative
    to where the json/yaml file is located.

    :param jsonyaml_file: Path to a json/yaml file.
    """
    loader = schema_salad.ref_resolver.Loader({
        "location": {"@type": "@id"},
        "path": {"@type": "@id"}
    })
    input_dict, _ = loader.resolve_ref(jsonyaml_file, checklinks=False)
    basedir = os.path.dirname(jsonyaml_file)

    def fixpaths(d):
        """Make sure all paths have a URI scheme."""
        if isinstance(d, dict):
            if "path" in d:
                if ":" not in d["path"]:
                    local_path = os.path.normpath(os.path.join(os.getcwd(), basedir, d["path"]))
                    d["location"] = pathname2url(local_path)
                else:
                    d["location"] = d["path"]
                del d["path"]

    visit(input_dict, fixpaths)
    return json.dumps(input_dict)


Instruction:
Implement a Python 3 function for
building a WES request from a cwl file and a json file.

Response:
def build_wes_request(workflow_file, json_path, attachments=None):
    """
    :param str workflow_file: Path to cwl/wdl file.  Can be http/https/file.
    :param json_path: Path to accompanying json file.
    :param attachments: Any other files needing to be uploaded to the server.

    :return: A list of tuples formatted to be sent in a post to the wes-server (Swagger API).
    """
    workflow_file = "file://" + workflow_file if ":" not in workflow_file else workflow_file
    wfbase = None
    if json_path.startswith("file://"):
        wfbase = os.path.dirname(json_path[7:])
        json_path = json_path[7:]
        with open(json_path) as f:
            wf_params = json.dumps(json.load(f))
    elif json_path.startswith("http"):
        wf_params = modify_jsonyaml_paths(json_path)
    else:
        wf_params = json_path
    wf_version, wf_type = wf_info(workflow_file)

    parts = [("workflow_params", wf_params),
             ("workflow_type", wf_type),
             ("workflow_type_version", wf_version)]

    if workflow_file.startswith("file://"):
        if wfbase is None:
            wfbase = os.path.dirname(workflow_file[7:])
        parts.append(("workflow_attachment", (os.path.basename(workflow_file[7:]), open(workflow_file[7:], "rb"))))
        parts.append(("workflow_url", os.path.basename(workflow_file[7:])))
    else:
        parts.append(("workflow_url", workflow_file))

    if wfbase is None:
        wfbase = os.getcwd()
    if attachments:
        for attachment in attachments:
            if attachment.startswith("file://"):
                attachment = attachment[7:]
                attach_f = open(attachment, "rb")
                relpath = os.path.relpath(attachment, wfbase)
            elif attachment.startswith("http"):
                attach_f = urlopen(attachment)
                relpath = os.path.basename(attach_f)

            parts.append(("workflow_attachment", (relpath, attach_f)))

    return parts


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_service_info(self):
        postresult = requests.get("%s://%s/ga4gh/wes/v1/service-info" % (self.proto, self.host),
                                  headers=self.auth)
        return wes_reponse(postresult)

Response: Get information about the workflow execution service.


Instruction:
Make a summary of the following Python 3 code
def run(self, wf, jsonyaml, attachments):
        attachments = list(expand_globs(attachments))
        parts = build_wes_request(wf, jsonyaml, attachments)
        postresult = requests.post("%s://%s/ga4gh/wes/v1/runs" % (self.proto, self.host),
                                   files=parts,
                                   headers=self.auth)
        return wes_reponse(postresult)

Response: Builds and sends a post request that signals the wes server to run a workflow.


Instruction:
Can you write a function in Python 3 where it
cancels a running workflow.

Response:
def cancel(self, run_id):
        """
        Cancel a running workflow.

        :param run_id: String (typically a uuid) identifying the run.
        :param str auth: String to send in the auth header.
        :param proto: Schema where the server resides (http, https)
        :param host: Port where the post request will be sent and the wes server listens at (default 8080)
        :return: The body of the delete result as a dictionary.
        """
        postresult = requests.post("%s://%s/ga4gh/wes/v1/runs/%s/cancel" % (self.proto, self.host, run_id),
                                   headers=self.auth)
        return wes_reponse(postresult)


Instruction:
Write a Python 3 function that can
get detailed info about a running workflow.

Response:
def get_run_log(self, run_id):
        """
        Get detailed info about a running workflow.

        :param run_id: String (typically a uuid) identifying the run.
        :param str auth: String to send in the auth header.
        :param proto: Schema where the server resides (http, https)
        :param host: Port where the post request will be sent and the wes server listens at (default 8080)
        :return: The body of the get result as a dictionary.
        """
        postresult = requests.get("%s://%s/ga4gh/wes/v1/runs/%s" % (self.proto, self.host, run_id),
                                  headers=self.auth)
        return wes_reponse(postresult)


Instruction:
How would you code a function in Python 3 to
construct a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file or request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file) JSON File: request["workflow_params"] == input json text (to be written to a file) :param dict request: A dictionary containing the cwl/json information. :param wes_service.util.WESBackend opts: contains the user's arguments; specifically the runner and runner options :return: {"run_id": self.run_id, "state": state}

Response:
def run(self, request, tempdir, opts):
        """
        Constructs a command to run a cwl/json from requests and opts,
        runs it, and deposits the outputs in outdir.

        Runner:
        opts.getopt("runner", default="cwl-runner")

        CWL (url):
        request["workflow_url"] == a url to a cwl file
        or
        request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)

        JSON File:
        request["workflow_params"] == input json text (to be written to a file)

        :param dict request: A dictionary containing the cwl/json information.
        :param wes_service.util.WESBackend opts: contains the user's arguments;
                                                 specifically the runner and runner options
        :return: {"run_id": self.run_id, "state": state}
        """
        with open(os.path.join(self.workdir, "request.json"), "w") as f:
            json.dump(request, f)

        with open(os.path.join(self.workdir, "cwl.input.json"), "w") as inputtemp:
            json.dump(request["workflow_params"], inputtemp)

        workflow_url = request.get("workflow_url")  # Will always be local path to descriptor cwl, or url.

        output = open(os.path.join(self.workdir, "cwl.output.json"), "w")
        stderr = open(os.path.join(self.workdir, "stderr"), "w")

        runner = opts.getopt("runner", default="cwl-runner")
        extra = opts.getoptlist("extra")

        # replace any locally specified outdir with the default
        for e in extra:
            if e.startswith('--outdir='):
                extra.remove(e)
        extra.append('--outdir=' + self.outdir)

        # link the cwl and json into the tempdir/cwd
        if workflow_url.startswith('file://'):
            os.symlink(workflow_url[7:], os.path.join(tempdir, "wes_workflow.cwl"))
            workflow_url = os.path.join(tempdir, "wes_workflow.cwl")
        os.symlink(inputtemp.name, os.path.join(tempdir, "cwl.input.json"))
        jsonpath = os.path.join(tempdir, "cwl.input.json")

        # build args and run
        command_args = [runner] + extra + [workflow_url, jsonpath]
        proc = subprocess.Popen(command_args,
                                stdout=output,
                                stderr=stderr,
                                close_fds=True,
                                cwd=tempdir)
        output.close()
        stderr.close()
        with open(os.path.join(self.workdir, "pid"), "w") as pid:
            pid.write(str(proc.pid))

        return self.getstatus()


Instruction:
Create a Python 3 function for
returning the state of the current user s log entry.

Response:
def getstate(self):
        """
        Returns RUNNING, -1
                COMPLETE, 0
                or
                EXECUTOR_ERROR, 255
        """
        state = "RUNNING"
        exit_code = -1

        exitcode_file = os.path.join(self.workdir, "exit_code")
        pid_file = os.path.join(self.workdir, "pid")

        if os.path.exists(exitcode_file):
            with open(exitcode_file) as f:
                exit_code = int(f.read())
        elif os.path.exists(pid_file):
            with open(pid_file, "r") as pid:
                pid = int(pid.read())
            try:
                (_pid, exit_status) = os.waitpid(pid, os.WNOHANG)
                if _pid != 0:
                    exit_code = exit_status >> 8
                    with open(exitcode_file, "w") as f:
                        f.write(str(exit_code))
                    os.unlink(pid_file)
            except OSError:
                os.unlink(pid_file)
                exit_code = 255

        if exit_code == 0:
            state = "COMPLETE"
        elif exit_code != -1:
            state = "EXECUTOR_ERROR"

        return state, exit_code


Instruction:
How would you code a function in Python 3 to
write a cwl wdl or python file as appropriate from the request dictionary.

Response:
def write_workflow(self, request, opts, cwd, wftype='cwl'):
        """Writes a cwl, wdl, or python file as appropriate from the request dictionary."""

        workflow_url = request.get("workflow_url")

        # link the cwl and json into the cwd
        if workflow_url.startswith('file://'):
            os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype))
            workflow_url = os.path.join(cwd, "wes_workflow." + wftype)
        os.link(self.input_json, os.path.join(cwd, "wes_input.json"))
        self.input_json = os.path.join(cwd, "wes_input.json")

        extra_options = self.sort_toil_options(opts.getoptlist("extra"))
        if wftype == 'cwl':
            command_args = ['toil-cwl-runner'] + extra_options + [workflow_url, self.input_json]
        elif wftype == 'wdl':
            command_args = ['toil-wdl-runner'] + extra_options + [workflow_url, self.input_json]
        elif wftype == 'py':
            command_args = ['python'] + extra_options + [workflow_url]
        else:
            raise RuntimeError('workflow_type is not "cwl", "wdl", or "py": ' + str(wftype))

        return command_args


Instruction:
Write a Python 3 function for
calling a command with Popen.

Response:
def call_cmd(self, cmd, cwd):
        """
        Calls a command with Popen.
        Writes stdout, stderr, and the command to separate files.

        :param cmd: A string or array of strings.
        :param tempdir:
        :return: The pid of the command.
        """
        with open(self.cmdfile, 'w') as f:
            f.write(str(cmd))
        stdout = open(self.outfile, 'w')
        stderr = open(self.errfile, 'w')
        logging.info('Calling: ' + ' '.join(cmd))
        process = subprocess.Popen(cmd,
                                   stdout=stdout,
                                   stderr=stderr,
                                   close_fds=True,
                                   cwd=cwd)
        stdout.close()
        stderr.close()

        return process.pid


Instruction:
Write a Python 3 function for
constructing a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file or request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file) JSON File: request["workflow_params"] == input json text (to be written to a file) :param dict request: A dictionary containing the cwl/json information. :param str tempdir: Folder where input files have been staged and the cwd to run at. :param wes_service.util.WESBackend opts: contains the user's arguments; specifically the runner and runner options :return: {"run_id": self.run_id, "state": state}

Response:
def run(self, request, tempdir, opts):
        """
        Constructs a command to run a cwl/json from requests and opts,
        runs it, and deposits the outputs in outdir.

        Runner:
        opts.getopt("runner", default="cwl-runner")

        CWL (url):
        request["workflow_url"] == a url to a cwl file
        or
        request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)

        JSON File:
        request["workflow_params"] == input json text (to be written to a file)

        :param dict request: A dictionary containing the cwl/json information.
        :param str tempdir: Folder where input files have been staged and the cwd to run at.
        :param wes_service.util.WESBackend opts: contains the user's arguments;
                                                 specifically the runner and runner options
        :return: {"run_id": self.run_id, "state": state}
        """
        wftype = request['workflow_type'].lower().strip()
        version = request['workflow_type_version']

        if version != 'v1.0' and wftype == 'cwl':
            raise RuntimeError('workflow_type "cwl" requires '
                               '"workflow_type_version" to be "v1.0": ' + str(version))
        if version != '2.7' and wftype == 'py':
            raise RuntimeError('workflow_type "py" requires '
                               '"workflow_type_version" to be "2.7": ' + str(version))

        logging.info('Beginning Toil Workflow ID: ' + str(self.run_id))

        with open(self.starttime, 'w') as f:
            f.write(str(time.time()))
        with open(self.request_json, 'w') as f:
            json.dump(request, f)
        with open(self.input_json, "w") as inputtemp:
            json.dump(request["workflow_params"], inputtemp)

        command_args = self.write_workflow(request, opts, tempdir, wftype=wftype)
        pid = self.call_cmd(command_args, tempdir)

        with open(self.endtime, 'w') as f:
            f.write(str(time.time()))
        with open(self.pidfile, 'w') as f:
            f.write(str(pid))

        return self.getstatus()


Instruction:
Write a Python 3 script for
returning QUEUED INITIALIZING EXECUTOR_ERROR 255

Response:
def getstate(self):
        """
        Returns QUEUED,          -1
                INITIALIZING,    -1
                RUNNING,         -1
                COMPLETE,         0
                or
                EXECUTOR_ERROR, 255
        """
        # the jobstore never existed
        if not os.path.exists(self.jobstorefile):
            logging.info('Workflow ' + self.run_id + ': QUEUED')
            return "QUEUED", -1

        # completed earlier
        if os.path.exists(self.statcompletefile):
            logging.info('Workflow ' + self.run_id + ': COMPLETE')
            return "COMPLETE", 0

        # errored earlier
        if os.path.exists(self.staterrorfile):
            logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
            return "EXECUTOR_ERROR", 255

        # the workflow is staged but has not run yet
        if not os.path.exists(self.errfile):
            logging.info('Workflow ' + self.run_id + ': INITIALIZING')
            return "INITIALIZING", -1

        # TODO: Query with "toil status"
        completed = False
        with open(self.errfile, 'r') as f:
            for line in f:
                if 'Traceback (most recent call last)' in line:
                    logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
                    open(self.staterrorfile, 'a').close()
                    return "EXECUTOR_ERROR", 255
                # run can complete successfully but fail to upload outputs to cloud buckets
                # so save the completed status and make sure there was no error elsewhere
                if 'Finished toil run successfully.' in line:
                    completed = True
        if completed:
            logging.info('Workflow ' + self.run_id + ': COMPLETE')
            open(self.statcompletefile, 'a').close()
            return "COMPLETE", 0

        logging.info('Workflow ' + self.run_id + ': RUNNING')
        return "RUNNING", -1


Instruction:
How would you explain what the following Python 3 function does
def getopt(self, p, default=None):
        for k, v in self.pairs:
            if k == p:
                return v
        return default

Response: Returns the first option value stored that matches p or default.


Instruction:
Implement a function in Python 3 to
return all option values stored that match p as a list.

Response:
def getoptlist(self, p):
        """Returns all option values stored that match p as a list."""
        optlist = []
        for k, v in self.pairs:
            if k == p:
                optlist.append(v)
        return optlist


Instruction:
Given the following Python 3 function, write the documentation
def catch_exceptions(orig_func):

    @functools.wraps(orig_func)
    def catch_exceptions_wrapper(self, *args, **kwargs):
        try:
            return orig_func(self, *args, **kwargs)
        except arvados.errors.ApiError as e:
            logging.exception("Failure")
            return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status)
        except subprocess.CalledProcessError as e:
            return {"msg": str(e), "status_code": 500}, 500
        except MissingAuthorization:
            return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401
        except ValueError as e:
            return {"msg": str(e), "status_code": 400}, 400
        except Exception as e:
            return {"msg": str(e), "status_code": 500}, 500

    return catch_exceptions_wrapper

Response: Catch uncaught exceptions and turn them into http errors


Instruction:
Write a Python 3 script to
convert the file name to ASCII and normalize the string.

Response:
def _safe_name(file_name, sep):
    """Convert the file name to ASCII and normalize the string."""
    file_name = stringify(file_name)
    if file_name is None:
        return
    file_name = ascii_text(file_name)
    file_name = category_replace(file_name, UNICODE_CATEGORIES)
    file_name = collapse_spaces(file_name)
    if file_name is None or not len(file_name):
        return
    return file_name.replace(WS, sep)


Instruction:
Can you implement a function in Python 3 that
creates a secure filename for plain file system storage.

Response:
def safe_filename(file_name, sep='_', default=None, extension=None):
    """Create a secure filename for plain file system storage."""
    if file_name is None:
        return decode_path(default)

    file_name = decode_path(file_name)
    file_name = os.path.basename(file_name)
    file_name, _extension = os.path.splitext(file_name)
    file_name = _safe_name(file_name, sep=sep)
    if file_name is None:
        return decode_path(default)
    file_name = file_name[:MAX_LENGTH]
    extension = _safe_name(extension or _extension, sep=sep)
    if extension is not None:
        file_name = '.'.join((file_name, extension))
        file_name = file_name[:MAX_LENGTH]
    return file_name


Instruction:
How would you explain what the following Python 3 function does
def stringify(value, encoding_default='utf-8', encoding=None):
    if value is None:
        return None

    if not isinstance(value, six.text_type):
        if isinstance(value, (date, datetime)):
            return value.isoformat()
        elif isinstance(value, (float, Decimal)):
            return Decimal(value).to_eng_string()
        elif isinstance(value, six.binary_type):
            if encoding is None:
                encoding = guess_encoding(value, default=encoding_default)
            value = value.decode(encoding, 'replace')
            value = remove_byte_order_mark(value)
            value = remove_unsafe_chars(value)
        else:
            value = six.text_type(value)

    # XXX: is this really a good idea?
    value = value.strip()
    if not len(value):
        return None
    return value

Response: Brute - force convert a given object into a string.


Instruction:
Given the following Python 3 function, write the documentation
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
    if encoding is None:
        return default
    encoding = encoding.lower().strip()
    if encoding in ['', 'ascii']:
        return default
    try:
        codecs.lookup(encoding)
        return encoding
    except LookupError:
        return default

Response: Normalize the encoding name replace ASCII w / UTF - 8 w / DEFAULT_ENCODING.


Instruction:
Can you write a function in Python 3 where it
interprets a chardet result.

Response:
def normalize_result(result, default, threshold=0.2):
    """Interpret a chardet result."""
    if result is None:
        return default
    if result.get('confidence') is None:
        return default
    if result.get('confidence') < threshold:
        return default
    return normalize_encoding(result.get('encoding'),
                              default=default)


Instruction:
How would you explain what the following Python 3 function does
def guess_encoding(text, default=DEFAULT_ENCODING):
    result = chardet.detect(text)
    return normalize_result(result, default=default)

Response: Guess encoding of a piece of text.


Instruction:
Write a Python 3 script for
guessing encoding from a file handle.

Response:
def guess_file_encoding(fh, default=DEFAULT_ENCODING):
    """Guess encoding from a file handle."""
    start = fh.tell()
    detector = chardet.UniversalDetector()
    while True:
        data = fh.read(1024 * 10)
        if not data:
            detector.close()
            break
        detector.feed(data)
        if detector.done:
            break

    fh.seek(start)
    return normalize_result(detector.result, default=default)


Instruction:
Here you have a function in Python 3, explain what it does
def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
    with io.open(file_path, 'rb') as fh:
        return guess_file_encoding(fh, default=default)

Response: Try to guess the encoding of a file.


Instruction:
Here you have a function in Python 3, explain what it does
def decompose_nfkd(text):
    if text is None:
        return None
    if not hasattr(decompose_nfkd, '_tr'):
        decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD')
    return decompose_nfkd._tr.transliterate(text)

Response: Perform unicode compatibility decomposition.


Instruction:
Explain what the following Python 3 code does
def category_replace(text, replacements=UNICODE_CATEGORIES):
    if text is None:
        return None
    characters = []
    for character in decompose_nfkd(text):
        cat = category(character)
        replacement = replacements.get(cat, character)
        if replacement is not None:
            characters.append(replacement)
    return u''.join(characters)

Response: Remove characters from a string based on unicode classes.


Instruction:
Explain what the following Python 3 code does
def remove_unsafe_chars(text):
    if isinstance(text, six.string_types):
        text = UNSAFE_RE.sub('', text)
    return text

Response: Remove unsafe unicode characters from a piece of text.


Instruction:
How would you implement a function in Python 3 that
removes newlines tabs and multiple spaces with single spaces.

Response:
def collapse_spaces(text):
    """Remove newlines, tabs and multiple spaces with single spaces."""
    if not isinstance(text, six.string_types):
        return text
    return COLLAPSE_RE.sub(WS, text).strip(WS)


Instruction:
Can you tell what is the following Python 3 function doing
def slugify(text, sep='-'):
    text = stringify(text)
    if text is None:
        return None
    text = text.replace(sep, WS)
    text = normalize(text, ascii=True)
    if text is None:
        return None
    return text.replace(WS, sep)

Response: A simple slug generator.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def latinize_text(text, ascii=False):
    if text is None or not isinstance(text, six.string_types) or not len(text):
        return text

    if ascii:
        if not hasattr(latinize_text, '_ascii'):
            # Transform to latin, separate accents, decompose, remove
            # symbols, compose, push to ASCII
            latinize_text._ascii = Transliterator.createInstance('Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII')  # noqa
        return latinize_text._ascii.transliterate(text)

    if not hasattr(latinize_text, '_tr'):
        latinize_text._tr = Transliterator.createInstance('Any-Latin')
    return latinize_text._tr.transliterate(text)

Response: Transliterate the given text to the latin script.


Instruction:
Make a summary of the following Python 3 code
def ascii_text(text):
    text = latinize_text(text, ascii=True)
    if isinstance(text, six.text_type):
        text = text.encode('ascii', 'ignore').decode('ascii')
    return text

Response: Transliterate the given text and make sure it ends up as ASCII.


Instruction:
Create a Python 3 function for
returning default message for this element

Response:
def message(self):
        """Return default message for this element
        """
        if self.code != 200:
            for code in self.response_codes:
                if code.code == self.code:
                    return code.message

            raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.code, self.name))

        return "OK"


Instruction:
Create a Python 3 function for
returning default value for the element

Response:
def get_default_sample(self):
        """Return default value for the element
        """
        if self.type not in Object.Types or self.type is Object.Types.type:
            return self.type_object.get_sample()
        else:
            return self.get_object().get_sample()


Instruction:
How would you implement a function in Python 3 that
returns a proper object of the specified type and version

Response:
def factory(cls, str_type, version):
        """Return a proper object
        """
        type = Object.Types(str_type)

        if type is Object.Types.object:
            object = ObjectObject()
        elif type is Object.Types.array:
            object = ObjectArray()
        elif type is Object.Types.number:
            object = ObjectNumber()
        elif type is Object.Types.integer:
            object = ObjectInteger()
        elif type is Object.Types.string:
            object = ObjectString()
        elif type is Object.Types.boolean:
            object = ObjectBoolean()
        elif type is Object.Types.reference:
            object = ObjectReference()
        elif type is Object.Types.type:
            object = ObjectType()
        elif type is Object.Types.none:
            object = ObjectNone()
        elif type is Object.Types.dynamic:
            object = ObjectDynamic()
        elif type is Object.Types.const:
            object = ObjectConst()
        elif type is Object.Types.enum:
            object = ObjectEnum()
        else:
            object = Object()
        object.type = type
        object.version = version
        return object


Instruction:
Explain what the following Python 3 code does
def main():
    configParser = FileParser()
    logging.config.dictConfig(
        configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml'))
    )
    ApiDoc().main()

Response: Main function to run command


Instruction:
Implement a Python 3 function for
initializing the command s configuration from the command s arguments

Response:
def _init_config(self):
        """return command's configuration from call's arguments
        """
        options = self.parser.parse_args()
        if options.config is None and options.input is None:
            self.parser.print_help()
            sys.exit(2)

        if options.config is not None:
            configFactory = ConfigFactory()
            config = configFactory.load_from_file(options.config)
        else:
            config = ConfigObject()

        if options.input is not None:
            config["input"]["locations"] = [str(x) for x in options.input]
        if options.arguments is not None:
            config["input"]["arguments"] = dict((x.partition("=")[0], x.partition("=")[2]) for x in options.arguments)

        if options.output is not None:
            config["output"]["location"] = options.output

        if options.no_validate is not None:
            config["input"]["validate"] = not options.no_validate

        if options.dry_run is not None:
            self.dry_run = options.dry_run
        if options.watch is not None:
            self.watch = options.watch
        if options.traceback is not None:
            self.traceback = options.traceback

        if options.quiet is not None:
            self.logger.setLevel(logging.WARNING)
        if options.silence is not None:
            logging.disable(logging.CRITICAL)

        configService = ConfigService()
        configService.validate(config)
        self.config = config


Instruction:
Explain what the following Python 3 code does
def _watch_refresh_source(self, event):
        self.logger.info("Sources changed...")

        try:
            self.sources = self._get_sources()
            self._render_template(self.sources)
        except:
            pass

Response: Refresh sources and templates


Instruction:
Can you tell what is the following Python 3 function doing
def _watch_refresh_template(self, event):
        self.logger.info("Template changed...")

        try:
            self._render_template(self.sources)
        except:
            pass

Response: Refreshes the template s contents


Instruction:
Can you write a function in Python 3 where it
adds a property to a class

Response:
def add_property(attribute, type):
    """Add a property to a class
    """
    def decorator(cls):
        """Decorator
        """
        private = "_" + attribute

        def getAttr(self):
            """Property getter
            """
            if getattr(self, private) is None:
                setattr(self, private, type())
            return getattr(self, private)

        def setAttr(self, value):
            """Property setter
            """
            setattr(self, private, value)

        setattr(cls, attribute, property(getAttr, setAttr))
        setattr(cls, private, None)
        return cls

    return decorator


Instruction:
Implement a Python 3 function for
combining the input files to a big output file

Response:
def _merge_files(self, input_files, output_file):
        """Combine the input files to a big output file"""
        # we assume that all the input files have the same charset
        with open(output_file, mode='wb') as out:
            for input_file in input_files:
                out.write(open(input_file, mode='rb').read())


Instruction:
Implement a Python 3 function for
creating a populated object from a dictionary datas

Response:
def create_from_name_and_dictionary(self, name, datas):
        """Return a populated object Object from dictionary datas
        """
        if "type" not in datas:
            str_type = "any"
        else:
            str_type = str(datas["type"]).lower()

        if str_type not in ObjectRaw.Types:
            type = ObjectRaw.Types("type")
        else:
            type = ObjectRaw.Types(str_type)

        if type is ObjectRaw.Types.object:
            object = ObjectObject()
            if "properties" in datas:
                object.properties = self.create_dictionary_of_element_from_dictionary("properties", datas)
            if "patternProperties" in datas:
                object.pattern_properties = self.create_dictionary_of_element_from_dictionary("patternProperties", datas)
            if "additionalProperties" in datas:
                if isinstance(datas["additionalProperties"], dict):
                    object.additional_properties = self.create_from_name_and_dictionary("additionalProperties", datas["additionalProperties"])
                elif not to_boolean(datas["additionalProperties"]):
                    object.additional_properties = None
                else:
                    raise ValueError("AdditionalProperties doe not allow empty value (yet)")
        elif type is ObjectRaw.Types.array:
            object = ObjectArray()
            if "items" in datas:
                object.items = self.create_from_name_and_dictionary("items", datas["items"])
            else:
                object.items = ObjectObject()
            if "sample_count" in datas:
                object.sample_count = int(datas["sample_count"])
        elif type is ObjectRaw.Types.number:
            object = ObjectNumber()
        elif type is ObjectRaw.Types.integer:
            object = ObjectInteger()
        elif type is ObjectRaw.Types.string:
            object = ObjectString()
        elif type is ObjectRaw.Types.boolean:
            object = ObjectBoolean()
            if "sample" in datas:
                object.sample = to_boolean(datas["sample"])
        elif type is ObjectRaw.Types.reference:
            object = ObjectReference()
            if "reference" in datas:
                object.reference_name = str(datas["reference"])
        elif type is ObjectRaw.Types.type:
            object = ObjectType()
            object.type_name = str(datas["type"])
        elif type is ObjectRaw.Types.none:
            object = ObjectNone()
        elif type is ObjectRaw.Types.dynamic:
            object = ObjectDynamic()
            if "items" in datas:
                object.items = self.create_from_name_and_dictionary("items", datas["items"])
            if "sample" in datas:
                if isinstance(datas["sample"], dict):
                    object.sample = {}
                    for k, v in datas["sample"].items():
                        object.sample[str(k)] = str(v)
                else:
                    raise ValueError("A dictionnary is expected for dynamic\s object in \"%s\"" % name)
        elif type is ObjectRaw.Types.const:
            object = ObjectConst()
            if "const_type" in datas:
                const_type = str(datas["const_type"])
                if const_type not in ObjectConst.Types:
                    raise ValueError("Const type \"%s\" unknwon" % const_type)
            else:
                const_type = ObjectConst.Types.string
            object.const_type = const_type
            if "value" not in datas:
                raise ValueError("Missing const value")
            object.value = datas["value"]
        elif type is ObjectRaw.Types.enum:
            object = ObjectEnum()
            if "values" not in datas or not isinstance(datas['values'], list):
                raise ValueError("Missing enum values")
            object.values = [str(value) for value in datas["values"]]
            if "descriptions" in datas and isinstance(datas['descriptions'], dict):
                for (value_name, value_description) in datas["descriptions"].items():
                    value = EnumValue()
                    value.name = value_name
                    value.description = value_description
                    object.descriptions.append(value)

            descriptions = [description.name for description in object.descriptions]
            for value_name in [x for x in object.values if x not in descriptions]:
                value = EnumValue()
                value.name = value_name
                object.descriptions.append(value)
        else:
            object = ObjectRaw()

        self.set_common_datas(object, name, datas)
        if isinstance(object, Constraintable):
            self.set_constraints(object, datas)
        object.type = type

        if "optional" in datas:
            object.optional = to_boolean(datas["optional"])

        return object


Instruction:
Can you tell what is the following Python 3 function doing
def merge_extends(self, target, extends, inherit_key="inherit", inherit=False):
        if isinstance(target, dict):
            if inherit and inherit_key in target and not to_boolean(target[inherit_key]):
                return
            if not isinstance(extends, dict):
                raise ValueError("Unable to merge: Dictionnary expected")
            for key in extends:
                if key not in target:
                    target[str(key)] = extends[key]
                else:
                    self.merge_extends(target[key], extends[key], inherit_key, True)
        elif isinstance(target, list):
            if not isinstance(extends, list):
                raise ValueError("Unable to merge: List expected")
            target += extends

Response: Merge extended dicts into target


Instruction:
Write a Python 3 script for
merging sources files with new sources files

Response:
def merge_sources(self, datas):
        """Merge sources files
        """
        datas = [data for data in datas if data is not None]

        if len(datas) == 0:
            raise ValueError("Data missing")

        if len(datas) == 1:
            return datas[0]

        if isinstance(datas[0], list):
            if len([x for x in datas if not isinstance(x, list)]) > 0:
                raise TypeError("Unable to merge: List expected")
            base = []
            for x in datas:
                base = base + x
            return base

        if isinstance(datas[0], dict):
            if len([x for x in datas if not isinstance(x, dict)]) > 0:
                raise TypeError("Unable to merge: Dictionnary expected")
            result = {}
            for element in datas:
                for key in element:
                    if key in result:
                        result[key] = self.merge_sources([result[key], element[key]])
                    else:
                        result[key] = element[key]
            return result

        if len([x for x in datas if isinstance(x, (dict, list))]) > 0:
            raise TypeError("Unable to merge: List not expected")

        raise ValueError("Unable to merge: Conflict")


Instruction:
Can you generate the documentation for the following Python 3 function
def merge_configs(self, config, datas):
        if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0:
            raise TypeError("Unable to merge: Dictionnary expected")

        for key, value in config.items():
            others = [x[key] for x in datas if key in x]
            if len(others) > 0:
                if isinstance(value, dict):
                    config[key] = self.merge_configs(value, others)
                else:
                    config[key] = others[-1]
        return config

Response: Merge the configs of the datas into the config


Instruction:
Given the following Python 3 function, write the documentation
def factory(cls, object_raw):
        if object_raw is None:
            return None
        if object_raw.type is ObjectRaw.Types.object:
            return ObjectObject(object_raw)
        elif object_raw.type is ObjectRaw.Types.type:
            return ObjectType(object_raw)
        elif object_raw.type is ObjectRaw.Types.array:
            return ObjectArray(object_raw)
        elif object_raw.type is ObjectRaw.Types.dynamic:
            return ObjectDynamic(object_raw)
        elif object_raw.type is ObjectRaw.Types.const:
            return ObjectConst(object_raw)
        elif object_raw.type is ObjectRaw.Types.enum:
            return ObjectEnum(object_raw)
        else:
            return Object(object_raw)

Response: Return a proper object


Instruction:
Here you have a function in Python 3, explain what it does
def render(self, sources, config, out=sys.stdout):
        logger = logging.getLogger()
        template = self.env.get_template(self.input)
        output = template.render(sources=sources, layout=config["output"]["layout"], config=config["output"])
        if self.output == "stdout":
            out.write(output)
        else:
            dir = os.path.dirname(self.output)
            if dir and not os.path.exists(dir):
                try:
                    os.makedirs(dir)
                except IOError as ioerror:
                    logger.error('Error on creating dir "{}": {}'.format(dir, str(ioerror)))
                    return
            if config["output"]["template"] == "default":
                if config["output"]["componants"] == "local":
                    for template_dir in self.env.loader.searchpath:
                        files = (
                            os.path.join(template_dir, "resource", "js", "combined.js"),
                            os.path.join(template_dir, "resource", "css", "combined.css"),
                            os.path.join(template_dir, "resource", "font", "apidoc.eot"),
                            os.path.join(template_dir, "resource", "font", "apidoc.woff"),
                            os.path.join(template_dir, "resource", "font", "apidoc.ttf"),
                            os.path.join(template_dir, "resource", "font", "source-code-pro.eot"),
                            os.path.join(template_dir, "resource", "font", "source-code-pro.woff"),
                            os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"),
                        )

                        for file in files:
                            filename = os.path.basename(file)
                            dirname = os.path.basename(os.path.dirname(file))

                            if not os.path.exists(os.path.join(dir, dirname)):
                                os.makedirs(os.path.join(dir, dirname))
                            if os.path.exists(file):
                                shutil.copyfile(file, os.path.join(dir, dirname, filename))
                            else:
                                logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources"))

                if config["output"]["componants"] == "remote":
                    for template_dir in self.env.loader.searchpath:
                        files = (
                            os.path.join(template_dir, "resource", "js", "combined.js"),
                            os.path.join(template_dir, "resource", "css", "combined-embedded.css"),
                            os.path.join(template_dir, "resource", "font", "apidoc.eot"),
                            os.path.join(template_dir, "resource", "font", "apidoc.woff"),
                            os.path.join(template_dir, "resource", "font", "apidoc.ttf"),
                            os.path.join(template_dir, "resource", "font", "source-code-pro.eot"),
                            os.path.join(template_dir, "resource", "font", "source-code-pro.woff"),
                            os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"),
                        )

                        for file in files:
                            filename = os.path.basename(file)
                            dirname = os.path.basename(os.path.dirname(file))

                            if not os.path.exists(os.path.join(dir, dirname)):
                                os.makedirs(os.path.join(dir, dirname))
                            if os.path.exists(file):
                                shutil.copyfile(file, os.path.join(dir, dirname, filename))
                            else:
                                logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources"))

            open(self.output, "w").write(output)

Response: Render the documentation as defined in config


Instruction:
Implement a function in Python 3 to
create an object Configuration from a dictionary datas

Response:
def create_from_dictionary(self, datas):
        """Return a populated object Configuration from dictionnary datas
        """
        configuration = ObjectConfiguration()

        if "uri" in datas:
            configuration.uri = str(datas["uri"])
        if "title" in datas:
            configuration.title = str(datas["title"])
        if "description" in datas:
            configuration.description = str(datas["description"])

        return configuration


Instruction:
Can you tell what is the following Python 3 function doing
def create_from_name_and_dictionary(self, name, datas):
        parameter = ObjectParameter()
        self.set_common_datas(parameter, name, datas)

        if "optional" in datas:
            parameter.optional = to_boolean(datas["optional"])
        if "type" in datas:
            parameter.type = str(datas["type"])
        if "generic" in datas:
            parameter.generic = to_boolean(datas["generic"])

        return parameter

Response: Create an object Parameter from a name and dictionary datas.


Instruction:
Make a summary of the following Python 3 code
def validate(self, sources):
        if not isinstance(sources, Root):
            raise Exception("Source object expected")

        parameters = self.get_uri_with_missing_parameters(sources)
        for parameter in parameters:
            logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versions "%s"' % (parameter["name"], parameter["method"], parameter["version"]))

Response: Validate the format of sources


Instruction:
Create a Python 3 function for
validating that the source file is ok .

Response:
def validate(self, config):
        """Validate that the source file is ok
        """
        if not isinstance(config, ConfigObject):
            raise Exception("Config object expected")

        if config["output"]["componants"] not in ("local", "remote", "embedded", "without"):
            raise ValueError("Unknown componant \"%s\"." % config["output"]["componants"])

        if config["output"]["layout"] not in ("default", "content-only"):
            raise ValueError("Unknown layout \"%s\"." % config["output"]["layout"])

        if config["input"]["locations"] is not None:
            unknown_locations = [x for x in config["input"]["locations"] if not os.path.exists(x)]
            if len(unknown_locations) > 0:
                raise ValueError(
                    "Location%s \"%s\" does not exists"
                    % ("s" if len(unknown_locations) > 1 else "", ("\" and \"").join(unknown_locations))
                )

            config["input"]["locations"] = [os.path.realpath(x) for x in config["input"]["locations"]]

        if config["input"]["arguments"] is not None:
            if not isinstance(config["input"]["arguments"], dict):
                raise ValueError(
                    "Sources arguments \"%s\" are not a dict" % config["input"]["arguments"]
                )


Instruction:
Make a summary of the following Python 3 code
def get_template_from_config(self, config):
        if config["output"]["template"] == "default":
            return os.path.join(
                os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                'template',
                'default.html'
            )
        else:
            return os.path.abspath(config["output"]["template"])

Response: Retrieve a template path from the config object


Instruction:
Create a Python 3 function to
create an object ResponseCode from a dictionary datas.

Response:
def create_from_dictionary(self, datas):
        """Return a populated object ResponseCode from dictionary datas
        """
        if "code" not in datas:
            raise ValueError("A response code must contain a code in \"%s\"." % repr(datas))

        code = ObjectResponseCode()
        self.set_common_datas(code, str(datas["code"]), datas)

        code.code = int(datas["code"])
        if "message" in datas:
            code.message = str(datas["message"])
        elif code.code in self.default_messages.keys():
            code.message = self.default_messages[code.code]
        if "generic" in datas:
            code.generic = to_boolean(datas["generic"])

        return code


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_handler(self, path, handler):
        self.signatures[path] = self.get_path_signature(path)
        self.handlers[path] = handler

Response: Add a handler to the watch queue.


Instruction:
Can you tell what is the following Python 3 function doing
def get_path_signature(self, path):
        if not os.path.exists(path):
            return None
        if os.path.isdir(path):
            merge = {}
            for root, dirs, files in os.walk(path):
                for name in files:
                    full_name = os.path.join(root, name)
                    merge[full_name] = os.stat(full_name)
            return merge
        else:
            return os.stat(path)

Response: generate a unique signature for a file contained in path


Instruction:
Make a summary of the following Python 3 code
def check(self):
        for (path, handler) in self.handlers.items():
            current_signature = self.signatures[path]
            new_signature = self.get_path_signature(path)
            if new_signature != current_signature:
                self.signatures[path] = new_signature
                handler.on_change(Event(path))

Response: Check if a file is changed


Instruction:
Explain what the following Python 3 code does
def get_comparable_values(self):
        return (int(self.major), int(self.minor), str(self.label), str(self.name))

Response: Return a tupple of values representing the unicity of the object


Instruction:
How would you implement a function in Python 3 that
returns a tupple of values representing the unicity of the object

Response:
def get_comparable_values(self):
        """Return a tupple of values representing the unicity of the object
        """
        return (int(self.order), str(self.label), str(self.name))


Instruction:
Can you generate the documentation for the following Python 3 function
def get_comparable_values(self):
        return (not self.generic, str(self.name), str(self.description))

Response: Return a tupple of values representing the unicity of the object


Instruction:
Can you implement a function in Python 3 that
returns a tupple of values representing the unicity of the object

Response:
def get_comparable_values_for_ordering(self):
        """Return a tupple of values representing the unicity of the object
        """

        return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description))


Instruction:
Here you have a function in Python 3, explain what it does
def get_comparable_values(self):
        return (not self.generic, int(self.code), str(self.message), str(self.description))

Response: Return a tupple of values representing the unicity of the object


Instruction:
Can you generate the documentation for the following Python 3 function
def factory(cls, object_source):
        if object_source.type is ObjectRaw.Types.object:
            return ObjectObject(object_source)
        elif object_source.type not in ObjectRaw.Types or object_source.type is ObjectRaw.Types.type:
            return ObjectType(object_source)
        elif object_source.type is ObjectRaw.Types.array:
            return ObjectArray(object_source)
        elif object_source.type is ObjectRaw.Types.dynamic:
            return ObjectDynamic(object_source)
        elif object_source.type is ObjectRaw.Types.const:
            return ObjectConst(object_source)
        elif object_source.type is ObjectRaw.Types.enum:
            return ObjectEnum(object_source)
        else:
            return Object(object_source)

Response: Return a proper object from an object source


Instruction:
Given the following Python 3 function, write the documentation
def get_comparable_values(self):
        return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self, Constraintable) else "")

Response: Return a tupple of values representing the unicity of the object


Instruction:
Create a Python 3 function for
returning a tupple of values representing the unicity of the object

Response:
def get_comparable_values(self):
        """Return a tupple of values representing the unicity of the object
        """
        return (str(self.name), str(self.description), str(self.constraints))


Instruction:
Given the following Python 3 function, write the documentation
def create_from_name_and_dictionary(self, name, datas):
        category = ObjectCategory(name)
        self.set_common_datas(category, name, datas)

        if "order" in datas:
            category.order = int(datas["order"])

        return category

Response: Create an object Category from a name and dictionary datas.


Instruction:
Can you create a Python 3 function that
loads a config file into a dictionary

Response:
def load_from_file(self, file_path, format=None):
        """Return dict from a file config
        """
        if format is None:
            base_name, file_extension = os.path.splitext(file_path)
            if file_extension in (".yaml", ".yml"):
                format = "yaml"
            elif file_extension in (".json"):
                format = "json"
            else:
                raise ValueError("Config file \"%s\" undetermined" % file_extension)

        if format == "yaml":
            return yaml.load(open(file_path), Loader=yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader)
        elif format == "json":
            return json.load(open(file_path))
        else:
            raise ValueError("Format \"%s\" unknwon" % format)


Instruction:
Explain what the following Python 3 code does
def load_all_from_directory(self, directory_path):
        datas = []
        for root, folders, files in os.walk(directory_path):
            for f in files:
                datas.append(self.load_from_file(os.path.join(root, f)))

        return datas

Response: Return a list of dict from a directory containing files


Instruction:
Can you generate a brief explanation for the following Python 3 code
def json_repr(obj):

    def serialize(obj):
        """Recursively walk object's hierarchy.
        """
        if obj is None:
            return None
        if isinstance(obj, Enum):
            return str(obj)
        if isinstance(obj, (bool, int, float, str)):
            return obj
        if isinstance(obj, dict):
            obj = obj.copy()
            for key in sorted(obj.keys()):
                obj[key] = serialize(obj[key])
            return obj
        if isinstance(obj, list):
            return [serialize(item) for item in obj]
        if isinstance(obj, tuple):
            return tuple(serialize([item for item in obj]))
        if hasattr(obj, '__dict__'):
            return serialize(obj.__dict__)
        return repr(obj)

    return json.dumps(serialize(obj))

Response: Represent an object as JSON.


Instruction:
Make a summary of the following Python 3 code
def create_from_root(self, root_source):

        root_dto = ObjectRoot()

        root_dto.configuration = root_source.configuration
        root_dto.versions = [Version(x) for x in root_source.versions.values()]

        for version in sorted(root_source.versions.values()):
            hydrator = Hydrator(version, root_source.versions, root_source.versions[version.name].types)
            for method in version.methods.values():
                hydrator.hydrate_method(root_dto, root_source, method)
            for type in version.types.values():
                hydrator.hydrate_type(root_dto, root_source, type)

        self.define_changes_status(root_dto)

        return root_dto

Response: Create an object root from a dictionnary datas


Instruction:
Create a Python 3 function for
populating common data for an element from dictionnary datas

Response:
def set_common_datas(self, element, name, datas):
        """Populated common data for an element from dictionnary datas
        """
        element.name = str(name)
        if "description" in datas:
            element.description = str(datas["description"]).strip()

        if isinstance(element, Sampleable) and element.sample is None and "sample" in datas:
            element.sample = str(datas["sample"]).strip()

        if isinstance(element, Displayable):
            if "display" in datas:
                element.display = to_boolean(datas["display"])

            if "label" in datas:
                element.label = datas["label"]
            else:
                element.label = element.name


Instruction:
Create a Python 3 function for
populating a dictionary of elements from a dictionary of datas

Response:
def create_dictionary_of_element_from_dictionary(self, property_name, datas):
        """Populate a dictionary of elements
        """
        response = {}
        if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], collections.Iterable):
            for key, value in datas[property_name].items():
                response[key] = self.create_from_name_and_dictionary(key, value)

        return response


Instruction:
Can you create a Python 3 function that
populates a list of elements from a dictionary

Response:
def create_list_of_element_from_dictionary(self, property_name, datas):
        """Populate a list of elements
        """
        response = []
        if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], list):
            for value in datas[property_name]:
                response.append(self.create_from_dictionary(value))

        return response


Instruction:
Can you implement a function in Python 3 that
creates a template object from a config object

Response:
def create_from_config(self, config):
        """Create a template object file defined in the config object
        """

        configService = ConfigService()
        template = TemplateService()

        template.output = config["output"]["location"]

        template_file = configService.get_template_from_config(config)
        template.input = os.path.basename(template_file)
        template.env = Environment(loader=FileSystemLoader(os.path.dirname(template_file)))

        return template


Instruction:
Explain what the following Python 3 code does
def deploy(self, id_networkv4):

        data = dict()
        uri = 'api/networkv4/%s/equipments/' % id_networkv4

        return super(ApiNetworkIPv4, self).post(uri, data=data)

Response: Deploy network in equipments and set column active = 1 in tables redeipv4


Instruction:
Can you write a function in Python 3 where it
gets IPv4 network by ID

Response:
def get_by_id(self, id_networkv4):
        """Get IPv4 network

        :param id_networkv4: ID for NetworkIPv4

        :return: IPv4 Network
        """

        uri = 'api/networkv4/%s/' % id_networkv4

        return super(ApiNetworkIPv4, self).get(uri)


Instruction:
Can you generate the documentation for the following Python 3 function
def list(self, environment_vip=None):

        uri = 'api/networkv4/?'
        if environment_vip:
            uri += 'environment_vip=%s' % environment_vip

        return super(ApiNetworkIPv4, self).get(uri)

Response: List IPv4 networks with specific environment vip


Instruction:
Can you implement a function in Python 3 that
removes deployment of network in equipments and set column active = 0 in tables redeipv4

Response:
def undeploy(self, id_networkv4):
        """Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ]

        :param id_networkv4: ID for NetworkIPv4

        :return: Equipments configuration output
        """

        uri = 'api/networkv4/%s/equipments/' % id_networkv4

        return super(ApiNetworkIPv4, self).delete(uri)


Instruction:
Implement a function in Python 3 to
check available ip in environment vip

Response:
def check_vip_ip(self, ip, environment_vip):
        """
        Check available ip in environment vip
        """
        uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip)

        return super(ApiNetworkIPv4, self).get(uri)


Instruction:
Can you generate the documentation for the following Python 3 function
def delete_ipv4(self, ipv4_id):
        uri = 'api/ipv4/%s/' % (ipv4_id)

        return super(ApiNetworkIPv4, self).delete(uri)

Response: Method to delete ipv4


Instruction:
How would you explain what the following Python 3 function does
def search(self, **kwargs):

        return super(ApiNetworkIPv4, self).get(self.prepare_url('api/v3/networkv4/',
                                                                kwargs))

Response: Method to search ipv4 s based on extends search.


Instruction:
Explain what the following Python 3 code does
def delete(self, ids):
        url = build_uri_with_ids('api/v3/networkv4/%s/', ids)

        return super(ApiNetworkIPv4, self).delete(url)

Response: Method to delete network - ipv4 s by their ids


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

        data = {'networks': networkipv4s}
        networkipv4s_ids = [str(networkipv4.get('id'))
                            for networkipv4 in networkipv4s]

        return super(ApiNetworkIPv4, self).put('api/v3/networkv4/%s/' %
                                               ';'.join(networkipv4s_ids), data)

Response: Method to update network - ipv4 s


Instruction:
Write a Python 3 function for
inserting a new Division Dc and returns its identifier.

Response:
def inserir(self, name):
        """Inserts a new Division Dc and returns its identifier.

        :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters

        :return: Dictionary with the following structure:

        ::

            {'division_dc': {'id': < id_division_dc >}}

        :raise InvalidParameterError: Name is null and invalid.
        :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        division_dc_map = dict()
        division_dc_map['name'] = name

        code, xml = self.submit(
            {'division_dc': division_dc_map}, 'POST', 'divisiondc/')

        return self.response(code, xml)


Instruction:
Write a Python 3 script for
changing Division Dc from by the identifier.

Response:
def alterar(self, id_divisiondc, name):
        """Change Division Dc from by the identifier.

        :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.
        :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters

        :return: None

        :raise InvalidParameterError: The identifier of Division Dc or name is null and invalid.
        :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.
        :raise DivisaoDcNaoExisteError: Division Dc not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_divisiondc):
            raise InvalidParameterError(
                u'The identifier of Division Dc is invalid or was not informed.')

        url = 'divisiondc/' + str(id_divisiondc) + '/'

        division_dc_map = dict()
        division_dc_map['name'] = name

        code, xml = self.submit({'division_dc': division_dc_map}, 'PUT', url)

        return self.response(code, xml)


Instruction:
Make a summary of the following Python 3 code
def remover(self, id_divisiondc):

        if not is_valid_int_param(id_divisiondc):
            raise InvalidParameterError(
                u'The identifier of Division Dc is invalid or was not informed.')

        url = 'divisiondc/' + str(id_divisiondc) + '/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)

Response: Remove Division Dc from by the identifier.


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

        return super(ApiObjectType, self).get(self.prepare_url('api/v3/object-type/',
                                                               kwargs))

Response: Method to search object types based on extends search.


Instruction:
Create a Python 3 function to
find vlans in the database.

Response:
def find_vlans(
            self,
            number,
            name,
            iexact,
            environment,
            net_type,
            network,
            ip_version,
            subnet,
            acl,
            pagination):
        """
        Find vlans by all search parameters

        :param number: Filter by vlan number column
        :param name: Filter by vlan name column
        :param iexact: Filter by name will be exact?
        :param environment: Filter by environment ID related
        :param net_type: Filter by network_type ID related
        :param network: Filter by each octs in network
        :param ip_version: Get only version (0:ipv4, 1:ipv6, 2:all)
        :param subnet: Filter by octs will search by subnets?
        :param acl: Filter by vlan acl column
        :param pagination: Class with all data needed to paginate

        :return: Following dictionary:

        ::

          {'vlan': {'id': < id_vlan >,
          'nome': < nome_vlan >,
          'num_vlan': < num_vlan >,
          'id_ambiente': < id_ambiente >,
          'descricao': < descricao >,
          'acl_file_name': < acl_file_name >,
          'acl_valida': < acl_valida >,
          'acl_file_name_v6': < acl_file_name_v6 >,
          'acl_valida_v6': < acl_valida_v6 >,
          'ativada': < ativada >,
          'ambiente_name': < divisao_dc-ambiente_logico-grupo_l3 >
          'redeipv4': [ { all networkipv4 related } ],
          'redeipv6': [ { all networkipv6 related } ] },
          'total': {< total_registros >} }

        :raise InvalidParameterError: Some parameter was invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not isinstance(pagination, Pagination):
            raise InvalidParameterError(
                u"Invalid parameter: pagination must be a class of type 'Pagination'.")

        vlan_map = dict()

        vlan_map['start_record'] = pagination.start_record
        vlan_map['end_record'] = pagination.end_record
        vlan_map['asorting_cols'] = pagination.asorting_cols
        vlan_map['searchable_columns'] = pagination.searchable_columns
        vlan_map['custom_search'] = pagination.custom_search

        vlan_map['numero'] = number
        vlan_map['nome'] = name
        vlan_map['exato'] = iexact
        vlan_map['ambiente'] = environment
        vlan_map['tipo_rede'] = net_type
        vlan_map['rede'] = network
        vlan_map['versao'] = ip_version
        vlan_map['subrede'] = subnet
        vlan_map['acl'] = acl

        url = 'vlan/find/'

        code, xml = self.submit({'vlan': vlan_map}, 'POST', url)

        key = 'vlan'
        return get_list_map(
            self.response(
                code, xml, [
                    key, 'redeipv4', 'redeipv6', 'equipamentos']), key)


Instruction:
Can you generate the documentation for the following Python 3 function
def listar_por_ambiente(self, id_ambiente):
        if not is_valid_int_param(id_ambiente):
            raise InvalidParameterError(u'Environment id is none or invalid.')

        url = 'vlan/ambiente/' + str(id_ambiente) + '/'

        code, xml = self.submit(None, 'GET', url)

        key = 'vlan'
        return get_list_map(self.response(code, xml, [key]), key)

Response: List all VLANs from an environment.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def alocar(
            self,
            nome,
            id_tipo_rede,
            id_ambiente,
            descricao,
            id_ambiente_vip=None,
            vrf=None):
        """Inserts a new VLAN.

        :param nome: Name of Vlan. String with a maximum of 50 characters.
        :param id_tipo_rede: Identifier of the Network Type. Integer value and greater than zero.
        :param id_ambiente: Identifier of the Environment. Integer value and greater than zero.
        :param descricao: Description of Vlan. String with a maximum of 200 characters.
        :param id_ambiente_vip: Identifier of the Environment Vip. Integer value and greater than zero.

        :return: Following dictionary:

        ::

          {'vlan': {'id': < id_vlan >,
          'nome': < nome_vlan >,
          'num_vlan': < num_vlan >,
          'id_tipo_rede': < id_tipo_rede >,
          'id_ambiente': < id_ambiente >,
          'rede_oct1': < rede_oct1 >,
          'rede_oct2': < rede_oct2 >,
          'rede_oct3': < rede_oct3 >,
          'rede_oct4': < rede_oct4 >,
          'bloco': < bloco >,
          'mascara_oct1': < mascara_oct1 >,
          'mascara_oct2': < mascara_oct2 >,
          'mascara_oct3': < mascara_oct3 >,
          'mascara_oct4': < mascara_oct4 >,
          'broadcast': < broadcast >,
          'descricao': < descricao >,
          'acl_file_name': < acl_file_name >,
          'acl_valida': < acl_valida >,
          'ativada': < ativada >}}

        :raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
        :raise VlanNaoExisteError: VLAN not found.
        :raise TipoRedeNaoExisteError: Network Type not registered.
        :raise AmbienteNaoExisteError: Environment not registered.
        :raise EnvironmentVipNotFoundError: Environment VIP not registered.
        :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
        :raise IPNaoDisponivelError: There is no network address is available to create the VLAN.
        :raise ConfigEnvironmentInvalidError: Invalid Environment Configuration or not registered
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        vlan_map = dict()
        vlan_map['nome'] = nome
        vlan_map['id_tipo_rede'] = id_tipo_rede
        vlan_map['id_ambiente'] = id_ambiente
        vlan_map['descricao'] = descricao
        vlan_map['id_ambiente_vip'] = id_ambiente_vip
        vlan_map['vrf'] = vrf

        code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/')

        return self.response(code, xml)

Response: Inserts a new VLAN in the cache.


Instruction:
How would you code a function in Python 3 to
insert a new VLAN into the database.

Response:
def insert_vlan(
            self,
            environment_id,
            name,
            number,
            description,
            acl_file,
            acl_file_v6,
            network_ipv4,
            network_ipv6,
            vrf=None):
        """Create new VLAN

        :param environment_id: ID for Environment.
        :param name: The name of VLAN.
        :param description: Some description to VLAN.
        :param number: Number of Vlan
        :param acl_file: Acl IPv4 File name to VLAN.
        :param acl_file_v6: Acl IPv6 File name to VLAN.
        :param network_ipv4: responsible for generating a network attribute ipv4 automatically.
        :param network_ipv6: responsible for generating a network attribute ipv6 automatically.

        :return: Following dictionary:

        ::

          {'vlan': {'id': < id_vlan >,
          'nome': < nome_vlan >,
          'num_vlan': < num_vlan >,
          'id_ambiente': < id_ambiente >,
          'descricao': < descricao >,
          'acl_file_name': < acl_file_name >,
          'acl_valida': < acl_valida >,
          'ativada': < ativada >
          'acl_file_name_v6': < acl_file_name_v6 >,
          'acl_valida_v6': < acl_valida_v6 >, } }

        :raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available.
        :raise VlanNaoExisteError: VLAN not found.
        :raise AmbienteNaoExisteError: Environment not registered.
        :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(environment_id):
            raise InvalidParameterError(u'Environment id is none or invalid.')

        if not is_valid_int_param(number):
            raise InvalidParameterError(u'Vlan number is none or invalid')

        vlan_map = dict()
        vlan_map['environment_id'] = environment_id
        vlan_map['name'] = name
        vlan_map['description'] = description
        vlan_map['acl_file'] = acl_file
        vlan_map['acl_file_v6'] = acl_file_v6
        vlan_map['number'] = number
        vlan_map['network_ipv4'] = network_ipv4
        vlan_map['network_ipv6'] = network_ipv6
        vlan_map['vrf'] = vrf

        code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/insert/')

        return self.response(code, xml)


Instruction:
How would you implement a function in Python 3 that
edits a VLAN in the specified Environment.

Response:
def edit_vlan(
            self,
            environment_id,
            name,
            number,
            description,
            acl_file,
            acl_file_v6,
            id_vlan):
        """Edit a VLAN

        :param id_vlan: ID for Vlan
        :param environment_id: ID for Environment.
        :param name: The name of VLAN.
        :param description: Some description to VLAN.
        :param number: Number of Vlan
        :param acl_file: Acl IPv4 File name to VLAN.
        :param acl_file_v6: Acl IPv6 File name to VLAN.

        :return: None

        :raise VlanError: VLAN name already exists, DC division of the environment invalid or there is no VLAN number available.
        :raise VlanNaoExisteError: VLAN not found.
        :raise AmbienteNaoExisteError: Environment not registered.
        :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'Vlan id is invalid or was not informed.')

        if not is_valid_int_param(environment_id):
            raise InvalidParameterError(u'Environment id is none or invalid.')

        if not is_valid_int_param(number):
            raise InvalidParameterError(u'Vlan number is none or invalid')

        vlan_map = dict()
        vlan_map['vlan_id'] = id_vlan
        vlan_map['environment_id'] = environment_id
        vlan_map['name'] = name
        vlan_map['description'] = description
        vlan_map['acl_file'] = acl_file
        vlan_map['acl_file_v6'] = acl_file_v6
        vlan_map['number'] = number

        code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/edit/')

        return self.response(code, xml)


Instruction:
Write a Python 3 script for
setting column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None

Response:
def create_vlan(self, id_vlan):
        """ Set column 'ativada = 1'.

        :param id_vlan: VLAN identifier.

        :return: None
        """

        vlan_map = dict()

        vlan_map['vlan_id'] = id_vlan

        code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/')

        return self.response(code, xml)


Instruction:
Can you generate the documentation for the following Python 3 function
def allocate_without_network(self, environment_id, name, description, vrf=None):
        vlan_map = dict()
        vlan_map['environment_id'] = environment_id
        vlan_map['name'] = name
        vlan_map['description'] = description
        vlan_map['vrf'] = vrf

        code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/no-network/')

        return self.response(code, xml)

Response: Create new VLAN without add NetworkIPv4.


Instruction:
Explain what the following Python 3 code does
def verificar_permissao(self, id_vlan, nome_equipamento, nome_interface):
        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'Vlan id is invalid or was not informed.')

        url = 'vlan/' + str(id_vlan) + '/check/'

        vlan_map = dict()
        vlan_map['nome'] = nome_equipamento
        vlan_map['nome_interface'] = nome_interface

        code, xml = self.submit({'equipamento': vlan_map}, 'PUT', url)

        return self.response(code, xml)

Response: Check if there is communication permission for VLAN to trunk.


Instruction:
Create a Python 3 function for
returning a dictionary of all the keys that are set in the base class.

Response:
def buscar(self, id_vlan):
        """Get VLAN by its identifier.

        :param id_vlan: VLAN identifier.

        :return: Following dictionary:

        ::

          {'vlan': {'id': < id_vlan >,
          'nome': < nome_vlan >,
          'num_vlan': < num_vlan >,
          'id_ambiente': < id_ambiente >,
          'id_tipo_rede': < id_tipo_rede >,
          'rede_oct1': < rede_oct1 >,
          'rede_oct2': < rede_oct2 >,
          'rede_oct3': < rede_oct3 >,
          'rede_oct4': < rede_oct4 >,
          'bloco': < bloco >,
          'mascara_oct1': < mascara_oct1 >,
          'mascara_oct2': < mascara_oct2 >,
          'mascara_oct3': < mascara_oct3 >,
          'mascara_oct4': < mascara_oct4 >,
          'broadcast': < broadcast >,
          'descricao': < descricao >,
          'acl_file_name': < acl_file_name >,
          'acl_valida': < acl_valida >,
          'ativada': < ativada >}
          OR {'id': < id_vlan >,
          'nome': < nome_vlan >,
          'num_vlan': < num_vlan >,
          'id_tipo_rede': < id_tipo_rede >,
          'id_ambiente': < id_ambiente >,
          'bloco1': < bloco1 >,
          'bloco2': < bloco2 >,
          'bloco3': < bloco3 >,
          'bloco4': < bloco4 >,
          'bloco5': < bloco5 >,
          'bloco6': < bloco6 >,
          'bloco7': < bloco7 >,
          'bloco8': < bloco8 >,
          'bloco': < bloco >,
          'mask_bloco1': < mask_bloco1 >,
          'mask_bloco2': < mask_bloco2 >,
          'mask_bloco3': < mask_bloco3 >,
          'mask_bloco4': < mask_bloco4 >,
          'mask_bloco5': < mask_bloco5 >,
          'mask_bloco6': < mask_bloco6 >,
          'mask_bloco7': < mask_bloco7 >,
          'mask_bloco8': < mask_bloco8 >,
          'broadcast': < broadcast >,
          'descricao': < descricao >,
          'acl_file_name': < acl_file_name >,
          'acl_valida': < acl_valida >,
          'acl_file_name_v6': < acl_file_name_v6 >,
          'acl_valida_v6': < acl_valida_v6 >,
          'ativada': < ativada >}}

        :raise VlanNaoExisteError: VLAN does not exist.
        :raise InvalidParameterError: VLAN id is none or invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """
        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'Vlan id is invalid or was not informed.')

        url = 'vlan/' + str(id_vlan) + '/'

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)


Instruction:
Write a Python 3 script for
getting a VLAN by your primary key.

Response:
def get(self, id_vlan):
        """Get a VLAN by your primary key.
        Network IPv4/IPv6 related will also be fetched.

        :param id_vlan: ID for VLAN.

        :return: Following dictionary:

        ::

          {'vlan': {'id': < id_vlan >,
          'nome': < nome_vlan >,
          'num_vlan': < num_vlan >,
          'id_ambiente': < id_ambiente >,
          'descricao': < descricao >,
          'acl_file_name': < acl_file_name >,
          'acl_valida': < acl_valida >,
          'acl_file_name_v6': < acl_file_name_v6 >,
          'acl_valida_v6': < acl_valida_v6 >,
          'ativada': < ativada >,
          'redeipv4': [ { all networkipv4 related } ],
          'redeipv6': [ { all networkipv6 related } ] } }

        :raise InvalidParameterError: Invalid ID for VLAN.
        :raise VlanNaoExisteError: VLAN not found.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """
        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'Parameter id_vlan is invalid. Value: ' +
                id_vlan)

        url = 'vlan/' + str(id_vlan) + '/network/'

        code, xml = self.submit(None, 'GET', url)

        return get_list_map(
            self.response(
                code, xml, [
                    'redeipv4', 'redeipv6']), 'vlan')


Instruction:
Make a summary of the following Python 3 code
def listar_permissao(self, nome_equipamento, nome_interface):
        vlan_map = dict()
        vlan_map['nome'] = nome_equipamento
        vlan_map['nome_interface'] = nome_interface

        code, xml = self.submit({'equipamento': vlan_map}, 'PUT', 'vlan/list/')

        return self.response(code, xml)

Response: List all VLANS having communication permission to trunk from a port in switch.


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

        url = 'vlan/v4/create/'

        vlan_map = dict()
        vlan_map['id_network_ip'] = id_network_ipv4

        code, xml = self.submit({'vlan': vlan_map}, 'POST', url)

        return self.response(code, xml)

Response: Create a VLAN in layer 2 using script navlan.


Instruction:
Make a summary of the following Python 3 code
def create_ipv6(self, id_network_ipv6):

        url = 'vlan/v6/create/'

        vlan_map = dict()
        vlan_map['id_network_ip'] = id_network_ipv6

        code, xml = self.submit({'vlan': vlan_map}, 'POST', url)

        return self.response(code, xml)

Response: Create a VLAN in layer 2 using script navlan.


Instruction:
Given the following Python 3 function, write the documentation
def apply_acl(self, equipments, vlan, environment, network):
        '''Apply the file acl in equipments

        :param equipments: list of equipments
        :param vlan: Vvlan
        :param environment: Environment
        :param network: v4 or v6

        :raise Exception: Failed to apply acl

        :return: True case Apply and sysout of script
        '''

        vlan_map = dict()
        vlan_map['equipments'] = equipments
        vlan_map['vlan'] = vlan
        vlan_map['environment'] = environment
        vlan_map['network'] = network

        url = 'vlan/apply/acl/'

        code, xml = self.submit({'vlan': vlan_map}, 'POST', url)

        return self.response(code, xml)

Response: Apply the file acl in equipments


Instruction:
Create a Python 3 function to
confirm a vlan insert need to be confirmed

Response:
def confirm_vlan(self, number_net, id_environment_vlan, ip_version=None):
        """Checking if the vlan insert need to be confirmed

        :param number_net: Filter by vlan number column
        :param id_environment_vlan: Filter by environment ID related
        :param ip_version: Ip version for checking

        :return: True is need confirmation, False if no need

        :raise AmbienteNaoExisteError: Ambiente não cadastrado.
        :raise InvalidParameterError: Invalid ID for VLAN.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        url = 'vlan/confirm/' + \
            str(number_net) + '/' + id_environment_vlan + '/' + str(ip_version)

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_number_available(self, id_environment, num_vlan, id_vlan):

        url = 'vlan/check_number_available/' + \
            str(id_environment) + '/' + str(num_vlan) + '/' + str(id_vlan)

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)

Response: Check if environment has a number vlan available


Instruction:
Implement a function in Python 3 to
validate ACL - IPv4 of VLAN from its identifier.

Response:
def validar(self, id_vlan):
        """Validates ACL - IPv4 of VLAN from its identifier.

        Assigns 1 to 'acl_valida'.

        :param id_vlan: Identifier of the Vlan. Integer value and greater than zero.

        :return: None

        :raise InvalidParameterError: Vlan identifier is null and invalid.
        :raise VlanNaoExisteError: Vlan not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'The identifier of Vlan is invalid or was not informed.')

        url = 'vlan/' + str(id_vlan) + '/validate/' + IP_VERSION.IPv4[0] + '/'

        code, xml = self.submit(None, 'PUT', url)

        return self.response(code, xml)


Instruction:
Can you write a function in Python 3 where it
validates ACL - IPv6 of VLAN from its identifier.

Response:
def validate_ipv6(self, id_vlan):
        """Validates ACL - IPv6 of VLAN from its identifier.

        Assigns 1 to 'acl_valida_v6'.

        :param id_vlan: Identifier of the Vlan. Integer value and greater than zero.

        :return: None

        :raise InvalidParameterError: Vlan identifier is null and invalid.
        :raise VlanNaoExisteError: Vlan not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'The identifier of Vlan is invalid or was not informed.')

        url = 'vlan/' + str(id_vlan) + '/validate/' + IP_VERSION.IPv6[0] + '/'

        code, xml = self.submit(None, 'PUT', url)

        return self.response(code, xml)


Instruction:
How would you implement a function in Python 3 that
removes a VLAN by your primary key.

Response:
def remove(self, id_vlan):
        """Remove a VLAN by your primary key.
        Execute script to remove VLAN

        :param id_vlan: ID for VLAN.

        :return: Following dictionary:

        ::

          {‘sucesso’: {‘codigo’: < codigo >,
          ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}}

        :raise InvalidParameterError: Identifier of the VLAN is invalid.
        :raise VlanNaoExisteError: VLAN not found.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'Parameter id_vlan is invalid. Value: ' +
                id_vlan)

        url = 'vlan/' + str(id_vlan) + '/remove/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)


Instruction:
Explain what the following Python 3 code does
def deallocate(self, id_vlan):

        if not is_valid_int_param(id_vlan):
            raise InvalidParameterError(
                u'The identifier of Vlan is invalid or was not informed.')

        url = 'vlan/' + str(id_vlan) + '/deallocate/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)

Response: Deallocate all relationships between Vlan.