Instruction:
Write a Python 3 script for
processing the I { reply } for the specified method and return the result.

Response:
def get_reply(self, method, replyroot):
        """
        Process the I{reply} for the specified I{method} by unmarshalling it
        into into Python object(s).

        @param method: The name of the invoked method.
        @type method: str
        @param replyroot: The reply XML root node received after invoking the
            specified method.
        @type replyroot: L{Element}
        @return: The unmarshalled reply. The returned value is an L{Object} or
            a I{list} depending on whether the service returns a single object
            or a collection.
        @rtype: L{Object} or I{list}

        """
        soapenv = replyroot.getChild("Envelope", envns)
        soapenv.promotePrefixes()
        soapbody = soapenv.getChild("Body", envns)
        soapbody = self.multiref.process(soapbody)
        nodes = self.replycontent(method, soapbody)
        rtypes = self.returned_types(method)
        if len(rtypes) > 1:
            return self.replycomposite(rtypes, nodes)
        if len(rtypes) == 0:
            return
        if rtypes[0].multi_occurrence():
            return self.replylist(rtypes[0], nodes)
        if len(nodes):
            resolved = rtypes[0].resolve(nobuiltin=True)
            return self.unmarshaller().process(nodes[0], resolved)


Instruction:
How would you implement a function in Python 3 that
constructs a list of I{unmarshalled} objects.

Response:
def replylist(self, rt, nodes):
        """
        Construct a I{list} reply.

        Called for replies with possible multiple occurrences.

        @param rt: The return I{type}.
        @type rt: L{suds.xsd.sxbase.SchemaObject}
        @param nodes: A collection of XML nodes.
        @type nodes: [L{Element},...]
        @return: A list of I{unmarshalled} objects.
        @rtype: [L{Object},...]

        """
        resolved = rt.resolve(nobuiltin=True)
        unmarshaller = self.unmarshaller()
        return [unmarshaller.process(node, resolved) for node in nodes]


Instruction:
Make a summary of the following Python 3 code
def mkheader(self, method, hdef, object):
        marshaller = self.marshaller()
        if isinstance(object, (list, tuple)):
            return [self.mkheader(method, hdef, item) for item in object]
        content = Content(tag=hdef[0], value=object, type=hdef[1])
        return marshaller.process(content)

Response: Builds a soapheader for the specified I { method } using the specified header definition and the specified value.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def envelope(self, header, body):
        env = Element("Envelope", ns=envns)
        env.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
        env.append(header)
        env.append(body)
        return env

Response: Builds the SOAP envelope for a SOAP outbound message.


Instruction:
Make a summary of the following Python 3 code
def header(self, content):
        header = Element("Header", ns=envns)
        header.append(content)
        return header

Response: Builds the B{<Body/> element for a SOAP outbound message.


Instruction:
How would you code a function in Python 3 to
get the XML content for the SOAP I{Header node.

Response:
def headercontent(self, method):
        """
        Get the content for the SOAP I{Header} node.

        @param method: A service method.
        @type method: I{service.Method}
        @return: The XML content for the <body/>.
        @rtype: [L{Element},...]

        """
        content = []
        wsse = self.options().wsse
        if wsse is not None:
            content.append(wsse.xml())
        headers = self.options().soapheaders
        if not isinstance(headers, (tuple, list, dict)):
            headers = (headers,)
        elif not headers:
            return content
        pts = self.headpart_types(method)
        if isinstance(headers, (tuple, list)):
            n = 0
            for header in headers:
                if isinstance(header, Element):
                    content.append(deepcopy(header))
                    continue
                if len(pts) == n:
                    break
                h = self.mkheader(method, pts[n], header)
                ns = pts[n][1].namespace("ns0")
                h.setPrefix(ns[0], ns[1])
                content.append(h)
                n += 1
        else:
            for pt in pts:
                header = headers.get(pt[0])
                if header is None:
                    continue
                h = self.mkheader(method, pt, header)
                ns = pt[1].namespace("ns0")
                h.setPrefix(ns[0], ns[1])
                content.append(h)
        return content


Instruction:
Write a Python 3 script for
returning a list of types defined for the specified method.

Response:
def bodypart_types(self, method, input=True):
        """
        Get a list of I{parameter definitions} (pdefs) defined for the
        specified method.

        An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
        while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.

        @param method: A service method.
        @type method: I{service.Method}
        @param input: Defines input/output message.
        @type input: boolean
        @return:  A list of parameter definitions
        @rtype: [I{pdef},...]

        """
        if input:
            parts = method.soap.input.body.parts
        else:
            parts = method.soap.output.body.parts
        return [self.__part_type(p, input) for p in parts]


Instruction:
Explain what the following Python 3 code does
def headpart_types(self, method, input=True):
        if input:
            headers = method.soap.input.headers
        else:
            headers = method.soap.output.headers
        return [self.__part_type(h.part, input) for h in headers]

Response:
Returns a list of header I { part } s defined for the
            specified method.


Instruction:
Given the following Python 3 function, write the documentation
def __part_type(self, part, input):
        if part.element is None:
            query = TypeQuery(part.type)
        else:
            query = ElementQuery(part.element)
        part_type = query.execute(self.schema())
        if part_type is None:
            raise TypeNotFound(query.ref)
        if part.type is not None:
            part_type = PartElement(part.name, part_type)
        if not input:
            return part_type
        if part_type.name is None:
            return part.name, part_type
        return part_type.name, part_type

Response: Returns a list of parameter definitions that are defined for a given body or header or message part.


Instruction:
Create a Python 3 function for
setting the node s xsi : type attribute based on either I { value}'s or the node s text s class.

Response:
def auto(cls, node, value=None):
        """
        Automatically set the node's xsi:type attribute based on either
        I{value}'s or the node text's class. When I{value} is an unmapped
        class, the default type (xs:any) is set.

        @param node: XML node.
        @type node: L{sax.element.Element}
        @param value: Object that is or would be the node's text.
        @type value: I{any}
        @return: Specified node.
        @rtype: L{sax.element.Element}

        """
        if value is None:
            value = node.getText()
        if isinstance(value, Object):
            known = cls.known(value)
            if known.name is None:
                return node
            tm = known.name, known.namespace()
        else:
            tm = cls.types.get(value.__class__, cls.types.get(str))
        cls.manual(node, *tm)
        return node


Instruction:
Make a summary of the following Python 3 code
def manual(cls, node, tval, ns=None):
        xta = ":".join((Namespace.xsins[0], "type"))
        node.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
        if ns is None:
            node.set(xta, tval)
        else:
            ns = cls.genprefix(node, ns)
            qname = ":".join((ns[0], tval))
            node.set(xta, qname)
            node.addPrefix(ns[0], ns[1])
        return node

Response:
Set the node s xsi : type attribute based on either I { value}'s or the
        node text s class. Then adds the referenced prefix to the node s xsi : type attribute mapping.


Instruction:
Write a Python 3 function that can
generate a prefix. @param node: XML node on which the prefix will be used. @type node: L{sax.element.Element} @param ns: Namespace needing a unique prefix. @type ns: (prefix, URI) @return: I{ns} with a new prefix. @rtype: (prefix, URI)

Response:
def genprefix(cls, node, ns):
        """
        Generate a prefix.

        @param node: XML node on which the prefix will be used.
        @type node: L{sax.element.Element}
        @param ns: Namespace needing a unique prefix.
        @type ns: (prefix, URI)
        @return: I{ns} with a new prefix.
        @rtype: (prefix, URI)

        """
        for i in range(1, 1024):
            prefix = "ns%d" % (i,)
            uri = node.resolvePrefix(prefix, default=None)
            if uri in (None, ns[1]):
                return prefix, ns[1]
        raise Exception("auto prefix, exhausted")


Instruction:
Can you generate the documentation for the following Python 3 function
def _getf(self, id):
        try:
            filename = self.__filename(id)
            self.__remove_if_expired(filename)
            return self.__open(filename, "rb")
        except Exception:
            pass

Response: Open a cached file with the given id for reading.


Instruction:
Explain what the following Python 3 code does
def __filename(self, id):
        suffix = self.fnsuffix()
        filename = "%s-%s.%s" % (self.fnprefix, id, suffix)
        return os.path.join(self.location, filename)

Response: Return the cache file name for an entry with a given id.


Instruction:
How would you code a function in Python 3 to
return the current process s default cache location folder.

Response:
def __get_default_location():
        """
        Returns the current process's default cache location folder.

        The folder is determined lazily on first call.

        """
        if not FileCache.__default_location:
            tmp = tempfile.mkdtemp("suds-default-cache")
            FileCache.__default_location = tmp
            import atexit
            atexit.register(FileCache.__remove_default_location)
        return FileCache.__default_location


Instruction:
Create a Python 3 function for
creating the I { location folder if it does not already exist.

Response:
def __mktmp(self):
        """Create the I{location} folder if it does not already exist."""
        try:
            if not os.path.isdir(self.location):
                os.makedirs(self.location)
        except Exception:
            log.debug(self.location, exc_info=1)
        return self


Instruction:
How would you explain what the following Python 3 function does
def __remove_if_expired(self, filename):
        if not self.duration:
            return
        created = datetime.datetime.fromtimestamp(os.path.getctime(filename))
        expired = created + self.duration
        if expired < datetime.datetime.now():
            os.remove(filename)
            log.debug("%s expired, deleted", filename)

Response: Remove a cached file entry if it expired.


Instruction:
Can you create a Python 3 function that
matches by I { targetNamespace excluding those that are equal to the specified namespace.

Response:
def match(self, root, ns):
        """
        Match by I{targetNamespace} excluding those that
        are equal to the specified namespace to prevent
        adding an import to itself.
        @param root: A schema root.
        @type root: L{Element}
        """
        tns = root.get('targetNamespace')
        if len(self.tns):
            matched = ( tns in self.tns )
        else:
            matched = 1
        itself = ( ns == tns )
        return ( matched and not itself )


Instruction:
Explain what the following Python 3 code does
def u2opener(self):
        if self.urlopener is None:
            return urllib2.build_opener(*self.u2handlers())
        return self.urlopener

Response: Create a urllib opener.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def u2ver(self):
        try:
            part = urllib2.__version__.split('.', 1)
            return float('.'.join(part))
        except Exception, e:
            log.exception(e)
            return 0

Response: Get the major or minor version of the urllib2 lib.


Instruction:
Can you create a Python 3 function that
converts a local file path to a absolute path file protocol URL.

Response:
def path_to_URL(path, escape=True):
    """Convert a local file path to a absolute path file protocol URL."""
    # We do not use urllib's builtin pathname2url() function since:
    #  - it has been commented with 'not recommended for general use'
    #  - it does not seem to work the same on Windows and non-Windows platforms
    #    (result starts with /// on Windows but does not on others)
    #  - urllib implementation prior to Python 2.5 used to quote ':' characters
    #    as '|' which would confuse pip on Windows.
    url = os.path.abspath(path)
    for sep in (os.sep, os.altsep):
        if sep and sep != "/":
            url = url.replace(sep, "/")
    if escape:
        # Must not escape ':' or '/' or Python will not recognize those URLs
        # correctly. Detected on Windows 7 SP1 x64 with Python 3.4.0, but doing
        # this always does not hurt since both are valid ASCII characters.
        no_protocol_URL = url_quote(url, safe=":/")
    else:
        no_protocol_URL = url
    return "file:///%s" % (no_protocol_URL,)


Instruction:
How would you explain what the following Python 3 function does
def requirement_spec(package_name, *args):
    if not args or args == (None,):
        return package_name
    version_specs = []
    for version_spec in args:
        if isinstance(version_spec, (list, tuple)):
            operator, version = version_spec
        else:
            assert isinstance(version_spec, str)
            operator = "=="
            version = version_spec
        version_specs.append("%s%s" % (operator, version))
    return "%s%s" % (package_name, ",".join(version_specs))

Response: Identifier used when specifying a requirement to pip or setuptools.


Instruction:
How would you explain what the following Python 3 function does
def script_folder(script_path):
    # There exist modules whose __file__ attribute does not correspond directly
    # to a disk file, e.g. modules imported from inside zip archives.
    if os.path.isfile(script_path):
        return _rel_path(os.path.dirname(script_path)) or "."

Response: Returns the folder where the given script is located.


Instruction:
Can you generate the documentation for the following Python 3 function
def path_iter(path):
    parts = []
    while path:
        path, item = os.path.split(path)
        if item:
            parts.append(item)
    return reversed(parts)

Response: Returns an iterator over all the file & folder names in a path.


Instruction:
Make a summary of the following Python 3 code
def document(self, wrapper):
        tag = wrapper[1].name
        ns = wrapper[1].namespace("ns0")
        return Element(tag, ns=ns)

Response:
Get the document root. For I { document / literal } this is the name of the the
        wrapper element qualified by the schema s target namespace.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def mkparam(self, method, pdef, object):
        if isinstance(object, (list, tuple)):
            return [self.mkparam(method, pdef, item) for item in object]
        return super(Document, self).mkparam(method, pdef, object)

Response:
Expand list parameters into individual parameters each with the type
        information.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def param_defs(self, method):
        pts = self.bodypart_types(method)
        if not method.soap.input.body.wrapped:
            return pts
        pt = pts[0][1].resolve()
        return [(c.name, c, a) for c, a in pt if not c.isattr()]

Response: Get parameter definitions for document literal.


Instruction:
Implement a function in Python 3 to
return a byte string version of s encoded as specified in encoding.

Response:
def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict"):
    """
    Returns a byte string version of 's', encoded as specified in 'encoding'.

    Accepts str & unicode objects, interpreting non-unicode strings as byte
    strings encoded using the given input encoding.

    """
    assert isinstance(s, basestring)
    if isinstance(s, unicode):
        return s.encode(encoding, errors)
    if s and encoding != input_encoding:
        return s.decode(input_encoding, errors).encode(encoding, errors)
    return s


Instruction:
Explain what the following Python 3 code does
def _date_from_match(match_object):
    year = int(match_object.group("year"))
    month = int(match_object.group("month"))
    day = int(match_object.group("day"))
    return datetime.date(year, month, day)

Response: Create a date object from a regular expression match.


Instruction:
Implement a function in Python 3 to
create a time object from a regular expression match.

Response:
def _time_from_match(match_object):
    """
    Create a time object from a regular expression match.

    Returns the time object and information whether the resulting time should
    be bumped up by one microsecond due to microsecond rounding.

    Subsecond information is rounded to microseconds due to a restriction in
    the python datetime.datetime/time implementation.

    The regular expression match is expected to be from _RE_DATETIME or
    _RE_TIME.

    @param match_object: The regular expression match.
    @type match_object: B{re}.I{MatchObject}
    @return: Time object + rounding flag.
    @rtype: tuple of B{datetime}.I{time} and bool

    """
    hour = int(match_object.group('hour'))
    minute = int(match_object.group('minute'))
    second = int(match_object.group('second'))
    subsecond = match_object.group('subsecond')

    round_up = False
    microsecond = 0
    if subsecond:
        round_up = len(subsecond) > 6 and int(subsecond[6]) >= 5
        subsecond = subsecond[:6]
        microsecond = int(subsecond + "0" * (6 - len(subsecond)))
    return datetime.time(hour, minute, second, microsecond), round_up


Instruction:
Write a Python 3 script to
create a timezone information object from a regular expression match.

Response:
def _tzinfo_from_match(match_object):
    """
    Create a timezone information object from a regular expression match.

    The regular expression match is expected to be from _RE_DATE, _RE_DATETIME
    or _RE_TIME.

    @param match_object: The regular expression match.
    @type match_object: B{re}.I{MatchObject}
    @return: A timezone information object.
    @rtype: B{datetime}.I{tzinfo}

    """
    tz_utc = match_object.group("tz_utc")
    if tz_utc:
        return UtcTimezone()

    tz_sign = match_object.group("tz_sign")
    if not tz_sign:
        return

    h = int(match_object.group("tz_hour") or 0)
    m = int(match_object.group("tz_minute") or 0)
    if h == 0 and m == 0:
        return UtcTimezone()

    # Python limitation - timezone offsets larger than one day (in absolute)
    # will cause operations depending on tzinfo.utcoffset() to fail, e.g.
    # comparing two timezone aware datetime.datetime/time objects.
    if h >= 24:
        raise ValueError("timezone indicator too large")

    tz_delta = datetime.timedelta(hours=h, minutes=m)
    if tz_sign == "-":
        tz_delta *= -1
    return FixedOffsetTimezone(tz_delta)


Instruction:
Write a Python 3 function that can
parse the string date.

Response:
def __parse(value):
        """
        Parse the string date.

        Supports the subset of ISO8601 used by xsd:date, but is lenient with
        what is accepted, handling most reasonable syntax.

        Any timezone is parsed but ignored because a) it is meaningless without
        a time and b) B{datetime}.I{date} does not support timezone
        information.

        @param value: A date string.
        @type value: str
        @return: A date object.
        @rtype: B{datetime}.I{date}

        """
        match_result = _RE_DATE.match(value)
        if match_result is None:
            raise ValueError("date data has invalid format '%s'" % (value,))
        return _date_from_match(match_result)


Instruction:
How would you implement a function in Python 3 that
parses the string datetime. and return a datetime object.

Response:
def __parse(value):
        """
        Parse the string datetime.

        Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
        with what is accepted, handling most reasonable syntax.

        Subsecond information is rounded to microseconds due to a restriction
        in the python datetime.datetime/time implementation.

        @param value: A datetime string.
        @type value: str
        @return: A datetime object.
        @rtype: B{datetime}.I{datetime}

        """
        match_result = _RE_DATETIME.match(value)
        if match_result is None:
           raise ValueError("date data has invalid format '%s'" % (value,))

        date = _date_from_match(match_result)
        time, round_up = _time_from_match(match_result)
        tzinfo = _tzinfo_from_match(match_result)

        value = datetime.datetime.combine(date, time)
        value = value.replace(tzinfo=tzinfo)
        if round_up:
            value += datetime.timedelta(microseconds=1)
        return value


Instruction:
Can you tell what is the following Python 3 function doing
def __parse(value):
        match_result = _RE_TIME.match(value)
        if match_result is None:
           raise ValueError("date data has invalid format '%s'" % (value,))

        time, round_up = _time_from_match(match_result)
        tzinfo = _tzinfo_from_match(match_result)
        if round_up:
            time = _bump_up_time_by_microsecond(time)
        return time.replace(tzinfo=tzinfo)

Response: Parse the string date.


Instruction:
Create a Python 3 function to
return the timezone name of the current instance.

Response:
def tzname(self, dt):
        """
        http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname

        """
        # total_seconds was introduced in Python 2.7
        if hasattr(self.__offset, "total_seconds"):
            total_seconds = self.__offset.total_seconds()
        else:
            total_seconds = (self.__offset.days * 24 * 60 * 60) + \
                            (self.__offset.seconds)

        hours = total_seconds // (60 * 60)
        total_seconds -= hours * 60 * 60

        minutes = total_seconds // 60
        total_seconds -= minutes * 60

        seconds = total_seconds // 1
        total_seconds -= seconds

        if seconds:
            return "%+03d:%02d:%02d" % (hours, minutes, seconds)
        return "%+03d:%02d" % (hours, minutes)


Instruction:
Given the following Python 3 function, write the documentation
def postprocess(self, content):
        node = content.node
        if len(node.children) and node.hasText():
            return node
        attributes = AttrList(node.attributes)
        if attributes.rlen() and \
            not len(node.children) and \
            node.hasText():
                p = Factory.property(node.name, node.getText())
                return merge(content.data, p)
        if len(content.data):
            return content.data
        lang = attributes.lang()
        if content.node.isnil():
            return None
        if not len(node.children) and content.text is None:
            if self.nillable(content):
                return None
            else:
                return Text('', lang=lang)
        if isinstance(content.text, basestring):
            return Text(content.text, lang=lang)
        else:
            return content.text

Response: Perform final processing of the content.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def append_children(self, content):
        for child in content.node:
            cont = Content(child)
            cval = self.append(cont)
            key = reserved.get(child.name, child.name)
            if key in content.data:
                v = getattr(content.data, key)
                if isinstance(v, list):
                    v.append(cval)
                else:
                    setattr(content.data, key, [v, cval])
                continue
            if self.multi_occurrence(cont):
                if cval is None:
                    setattr(content.data, key, [])
                else:
                    setattr(content.data, key, [cval,])
            else:
                setattr(content.data, key, cval)

Response: Append children into the content. data attribute.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _parse(string):
    if string:
        return suds.sax.parser.Parser().parse(string=string)

Response: Parses given XML document content.


Instruction:
Given the following Python 3 function, write the documentation
def create(self, name):
        timer = metrics.Timer()
        timer.start()
        type = self.resolver.find(name)
        if type is None:
            raise TypeNotFound(name)
        if type.enum():
            result = sudsobject.Factory.object(name)
            for e, a in type.children():
                setattr(result, e.name, e.name)
        else:
            try:
                result = self.builder.build(type)
            except Exception, e:
                log.error("create '%s' failed", name, exc_info=True)
                raise BuildError(name, e)
        timer.stop()
        metrics.log.debug("%s created: %s", name, timer)
        return result

Response: Create a WSDL type by name.


Instruction:
How would you explain what the following Python 3 function does
def __find(self, name):
        service = None
        if not self.__services:
            raise Exception, "No services defined"
        if isinstance(name, int):
            try:
                service = self.__services[name]
                name = service.name
            except IndexError:
                raise ServiceNotFound, "at [%d]" % (name,)
        else:
            for s in self.__services:
                if name == s.name:
                    service = s
                    break
        if service is None:
            raise ServiceNotFound, name
        return PortSelector(self.__client, service.ports, name)

Response: Find a service by name or index.


Instruction:
Make a summary of the following Python 3 code
def __ds(self):
        ds = self.__client.options.service
        if ds is not None:
            return self.__find(ds)

Response:
Get the I { default } service if defined in the I { options.
        } attribute.


Instruction:
Explain what the following Python 3 code does
def process_reply(self, reply, status=None, description=None):
        return self.__process_reply(reply, status, description)

Response: Process a SOAP reply and return the corresponding Python object representing the result.


Instruction:
Given the following Python 3 function, write the documentation
def send(self, soapenv):
        location = self.__location()
        log.debug("sending to (%s)\nmessage:\n%s", location, soapenv)
        plugins = PluginContainer(self.options.plugins)
        plugins.message.marshalled(envelope=soapenv.root())
        if self.options.prettyxml:
            soapenv = soapenv.str()
        else:
            soapenv = soapenv.plain()
        soapenv = soapenv.encode("utf-8")
        ctx = plugins.message.sending(envelope=soapenv)
        soapenv = ctx.envelope
        if self.options.nosend:
            return RequestContext(self.process_reply, soapenv)
        request = suds.transport.Request(location, soapenv)
        request.headers = self.__headers()
        try:
            timer = metrics.Timer()
            timer.start()
            reply = self.options.transport.send(request)
            timer.stop()
            metrics.log.debug("waited %s on server reply", timer)
        except suds.transport.TransportError, e:
            content = e.fp and e.fp.read() or ""
            return self.process_reply(content, e.httpcode, tostr(e))
        return self.process_reply(reply.message, None, None)

Response: Send a SOAP message to the server.


Instruction:
How would you code a function in Python 3 to
process a SOAP reply and return the corresponding Python object representing the reply.

Response:
def process_reply(self, reply, status, description):
        """
        Process a web service operation SOAP reply.

        Depending on how the ``retxml`` option is set, may return the SOAP
        reply XML or process it and return the Python object representing the
        returned value.

        @param reply: The SOAP reply envelope.
        @type reply: I{bytes}
        @param status: The HTTP status code (None indicates httplib.OK).
        @type status: int|I{None}
        @param description: Additional status description.
        @type description: str
        @return: The invoked web service operation return value.
        @rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}

        """
        if status is None:
            status = httplib.OK
        debug_message = "Reply HTTP status - %d" % (status,)
        if status in (httplib.ACCEPTED, httplib.NO_CONTENT):
            log.debug(debug_message)
            return
        #TODO: Consider whether and how to allow plugins to handle error,
        # httplib.ACCEPTED & httplib.NO_CONTENT replies as well as successful
        # ones.
        if status == httplib.OK:
            log.debug("%s\n%s", debug_message, reply)
        else:
            log.debug("%s - %s\n%s", debug_message, description, reply)

        plugins = PluginContainer(self.options.plugins)
        ctx = plugins.message.received(reply=reply)
        reply = ctx.reply

        # SOAP standard states that SOAP errors must be accompanied by HTTP
        # status code 500 - internal server error:
        #
        # From SOAP 1.1 specification:
        #   In case of a SOAP error while processing the request, the SOAP HTTP
        # server MUST issue an HTTP 500 "Internal Server Error" response and
        # include a SOAP message in the response containing a SOAP Fault
        # element (see section 4.4) indicating the SOAP processing error.
        #
        # From WS-I Basic profile:
        #   An INSTANCE MUST use a "500 Internal Server Error" HTTP status code
        # if the response message is a SOAP Fault.
        replyroot = None
        if status in (httplib.OK, httplib.INTERNAL_SERVER_ERROR):
            replyroot = _parse(reply)
            plugins.message.parsed(reply=replyroot)
            fault = self.__get_fault(replyroot)
            if fault:
                if status != httplib.INTERNAL_SERVER_ERROR:
                    log.warn("Web service reported a SOAP processing fault "
                        "using an unexpected HTTP status code %d. Reporting "
                        "as an internal server error.", status)
                if self.options.faults:
                    raise WebFault(fault, replyroot)
                return httplib.INTERNAL_SERVER_ERROR, fault
        if status != httplib.OK:
            if self.options.faults:
                #TODO: Use a more specific exception class here.
                raise Exception((status, description))
            return status, description

        if self.options.retxml:
            return reply

        result = replyroot and self.method.binding.output.get_reply(
            self.method, replyroot)
        ctx = plugins.message.unmarshalled(reply=result)
        result = ctx.reply
        if self.options.faults:
            return result
        return httplib.OK, result


Instruction:
Can you tell what is the following Python 3 function doing
def __get_fault(self, replyroot):
        envns = suds.bindings.binding.envns
        soapenv = replyroot and replyroot.getChild("Envelope", envns)
        soapbody = soapenv and soapenv.getChild("Body", envns)
        fault = soapbody and soapbody.getChild("Fault", envns)
        return fault is not None and UmxBasic().process(fault)

Response: Extract fault information from a SOAP reply.


Instruction:
Explain what the following Python 3 code does
def __headers(self):
        action = self.method.soap.action
        if isinstance(action, unicode):
            action = action.encode("utf-8")
        result = {
            "Content-Type": "text/xml; charset=utf-8",
            "SOAPAction": action}
        result.update(**self.options.headers)
        log.debug("headers = %s", result)
        return result

Response: Returns a dictionary of HTTP headers for a HTTP / HTTPS SOAP request.


Instruction:
Explain what the following Python 3 code does
def invoke(self, args, kwargs):
        simulation = kwargs.pop(self.__injkey)
        msg = simulation.get("msg")
        if msg is not None:
            assert msg.__class__ is suds.byte_str_class
            return self.send(_parse(msg))
        msg = self.method.binding.input.get_message(self.method, args, kwargs)
        log.debug("inject (simulated) send message:\n%s", msg)
        reply = simulation.get("reply")
        if reply is not None:
            assert reply.__class__ is suds.byte_str_class
            status = simulation.get("status")
            description = simulation.get("description")
            if description is None:
                description = "injected reply"
            return self.process_reply(reply, status, description)
        raise Exception("reply or msg injection parameter expected")

Response: Invoke a specified method.


Instruction:
Create a Python 3 function for
setting the URL of the used object.

Response:
def __set_URL(self, url):
        """
        URL is stored as a str internally and must not contain ASCII chars.

        Raised exception in case of detected non-ASCII URL characters may be
        either UnicodeEncodeError or UnicodeDecodeError, depending on the used
        Python version's str type and the exact value passed as URL input data.

        """
        if isinstance(url, str):
            url.encode("ascii")  # Check for non-ASCII characters.
            self.url = url
        elif sys.version_info < (3, 0):
            self.url = url.encode("ascii")
        else:
            self.url = url.decode("ascii")


Instruction:
Can you implement a function in Python 3 that
appends the content to the parent node.

Response:
def append(self, parent, content):
        """
        Select an appender and append the content to parent.
        @param parent: A parent node.
        @type parent: L{Element}
        @param content: The content to append.
        @type content: L{Content}
        """
        appender = self.default
        for matcher, candidate_appender in self.appenders:
            if matcher == content.value:
                appender = candidate_appender
                break
        appender.append(parent, content)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def root(self, parts):
        result = None
        name = parts[0]
        log.debug('searching schema for (%s)', name)
        qref = self.qualify(parts[0])
        query = BlindQuery(qref)
        result = query.execute(self.schema)
        if result is None:
            log.error('(%s) not-found', name)
            raise PathResolver.BadPath(name)
        log.debug('found (%s) as (%s)', name, Repr(result))
        return result

Response: Find the path root.


Instruction:
Explain what the following Python 3 code does
def branch(self, root, parts):
        result = root
        for part in parts[1:-1]:
            name = splitPrefix(part)[1]
            log.debug('searching parent (%s) for (%s)', Repr(result), name)
            result, ancestry = result.get_child(name)
            if result is None:
                log.error('(%s) not-found', name)
                raise PathResolver.BadPath(name)
            result = result.resolve(nobuiltin=True)
            log.debug('found (%s) as (%s)', name, Repr(result))
        return result

Response: Traverse the path until a leaf is reached.


Instruction:
Write a Python 3 function that can
get a child by name.

Response:
def getchild(self, name, parent):
        """Get a child by name."""
        log.debug('searching parent (%s) for (%s)', Repr(parent), name)
        if name.startswith('@'):
            return parent.get_attribute(name[1:])
        return parent.get_child(name)


Instruction:
How would you explain what the following Python 3 function does
def __path_prefix(self, folder):
        path_parts = path_iter(folder)
        _skip_expected(path_parts, self.__base_folder_parts)
        result = "/".join(path_parts)
        if result:
            result += "/"
        return result

Response: Returns the path prefix to be used when archiving any items from the given folder.


Instruction:
How would you implement a function in Python 3 that
converts a decimal. Decimal value to its XSD decimal type value.

Response:
def _decimal_to_xsd_format(value):
        """
        Converts a decimal.Decimal value to its XSD decimal type value.

        Result is a string containing the XSD decimal type's lexical value
        representation. The conversion is done without any precision loss.

        Note that Python's native decimal.Decimal string representation will
        not do here as the lexical representation desired here does not allow
        representing decimal values using float-like `<mantissa>E<exponent>'
        format, e.g. 12E+30 or 0.10006E-12.

        """
        value = XDecimal._decimal_canonical(value)
        negative, digits, exponent = value.as_tuple()

        # The following implementation assumes the following tuple decimal
        # encoding (part of the canonical decimal value encoding):
        #  - digits must contain at least one element
        #  - no leading integral 0 digits except a single one in 0 (if a non-0
        #    decimal value has leading integral 0 digits they must be encoded
        #    in its 'exponent' value and not included explicitly in its
        #    'digits' tuple)
        assert digits
        assert digits[0] != 0 or len(digits) == 1

        result = []
        if negative:
            result.append("-")

        # No fractional digits.
        if exponent >= 0:
            result.extend(str(x) for x in digits)
            result.extend("0" * exponent)
            return "".join(result)

        digit_count = len(digits)

        # Decimal point offset from the given digit start.
        point_offset = digit_count + exponent

        # Trim trailing fractional 0 digits.
        fractional_digit_count = min(digit_count, -exponent)
        while fractional_digit_count and digits[digit_count - 1] == 0:
            digit_count -= 1
            fractional_digit_count -= 1

        # No trailing fractional 0 digits and a decimal point coming not after
        # the given digits, meaning there is no need to add additional trailing
        # integral 0 digits.
        if point_offset <= 0:
            # No integral digits.
            result.append("0")
            if digit_count > 0:
                result.append(".")
                result.append("0" * -point_offset)
                result.extend(str(x) for x in digits[:digit_count])
        else:
            # Have integral and possibly some fractional digits.
            result.extend(str(x) for x in digits[:point_offset])
            if point_offset < digit_count:
                result.append(".")
                result.extend(str(x) for x in digits[point_offset:digit_count])
        return "".join(result)


Instruction:
Explain what the following Python 3 code does
def create(cls, schema, name):
        fn = cls.tags.get(name, XBuiltin)
        return fn(schema, name)

Response: Create an object based on the root tag name.


Instruction:
Explain what the following Python 3 code does
def _avoid_setuptools_zipped_egg_upgrade_issue(env, ez_setup):
    if env.sys_version_info[:2] != (2, 5):
        return  # only Python 2.5.x affected by this
    if not env.setuptools_zipped_egg:
        return  # setuptools not pre-installed as a zipped egg
    pv_new = parse_version(ez_setup.setuptools_version())
    if pv_new != parse_version(env.setuptools_version):
        return  # issue avoided since zipped egg archive names will not match
    fixed_version = utility.lowest_version_string_with_prefix("3.5.2")
    if pv_new >= parse_version(fixed_version):
        return  # issue fixed in setuptools
    # We could check for pip and use it for a cleaner setuptools uninstall if
    # available, but YAGNI since only Python 2.5.x environments are affected by
    # the zipped egg upgrade issue.
    os.remove(env.setuptools_zipped_egg)

Response: Avoid setuptools self - upgrade issues.


Instruction:
Can you implement a function in Python 3 that
returns whether a pre - installed setuptools distribution should be reused.

Response:
def _reuse_pre_installed_setuptools(env, installer):
    """
    Return whether a pre-installed setuptools distribution should be reused.

    """
    if not env.setuptools_version:
        return  # no prior setuptools ==> no reuse
    reuse_old = config.reuse_old_setuptools
    reuse_best = config.reuse_best_setuptools
    reuse_future = config.reuse_future_setuptools
    reuse_comment = None
    if reuse_old or reuse_best or reuse_future:
        pv_old = parse_version(env.setuptools_version)
        pv_new = parse_version(installer.setuptools_version())
        if pv_old < pv_new:
            if reuse_old:
                reuse_comment = "%s+ recommended" % (
                    installer.setuptools_version(),)
        elif pv_old > pv_new:
            if reuse_future:
                reuse_comment = "%s+ required" % (
                    installer.setuptools_version(),)
        elif reuse_best:
            reuse_comment = ""
    if reuse_comment is None:
        return  # reuse not allowed by configuration
    if reuse_comment:
        reuse_comment = " (%s)" % (reuse_comment,)
    print("Reusing pre-installed setuptools %s distribution%s." % (
        env.setuptools_version, reuse_comment))
    return True


Instruction:
How would you explain what the following Python 3 function does
def download_pip(env, requirements):
    if config.installation_cache_folder() is None:
        raise EnvironmentSetupError("Local installation cache folder not "
            "defined but required for downloading a pip installation.")
    # Installation cache folder needs to be explicitly created for setuptools
    # to be able to copy its downloaded installation files into it. Seen using
    # Python 2.4.4 & setuptools 1.4.
    _create_installation_cache_folder_if_needed()
    try:
        env.execute(["-m", "easy_install", "--zip-ok", "--multi-version",
            "--always-copy", "--exclude-scripts", "--install-dir",
            config.installation_cache_folder()] + requirements)
        zip_eggs_in_folder(config.installation_cache_folder())
    except (KeyboardInterrupt, SystemExit):
        raise
    except Exception:
        raise EnvironmentSetupError("pip download failed.")

Response: Download pip and its requirements using setuptools.


Instruction:
Implement a Python 3 function for
returning a list of options to make setuptools use installations from the given folder.

Response:
def setuptools_install_options(local_storage_folder):
    """
    Return options to make setuptools use installations from the given folder.

    No other installation source is allowed.

    """
    if local_storage_folder is None:
        return []
    # setuptools expects its find-links parameter to contain a list of link
    # sources (either local paths, file: URLs pointing to folders or URLs
    # pointing to a file containing HTML links) separated by spaces. That means
    # that, when specifying such items, whether local paths or URLs, they must
    # not contain spaces. The problem can be worked around by using a local
    # file URL, since URLs can contain space characters encoded as '%20' (for
    # more detailed information see below).
    #
    # Any URL referencing a folder needs to be specified with a trailing '/'
    # character in order for setuptools to correctly recognize it as a folder.
    #
    # All this has been tested using Python 2.4.3/2.4.4 & setuptools 1.4/1.4.2
    # as well as Python 3.4 & setuptools 3.3.
    #
    # Supporting paths with spaces - method 1:
    # ----------------------------------------
    # One way would be to prepare a link file and pass an URL referring to that
    # link file. The link file needs to contain a list of HTML link tags
    # (<a href="..."/>), one for every item stored inside the local storage
    # folder. If a link file references a folder whose name matches the desired
    # requirement name, it will be searched recursively (as described in method
    # 2 below).
    #
    # Note that in order for setuptools to recognize a local link file URL
    # correctly, the file needs to be named with the '.html' extension. That
    # will cause the underlying urllib2.open() operation to return the link
    # file's content type as 'text/html' which is required for setuptools to
    # recognize a valid link file.
    #
    # Supporting paths with spaces - method 2:
    # ----------------------------------------
    # Another possible way is to use an URL referring to the local storage
    # folder directly. This will cause setuptools to prepare and use a link
    # file internally - with its content read from a 'index.html' file located
    # in the given local storage folder, if it exists, or constructed so it
    # contains HTML links to all top-level local storage folder items, as
    # described for method 1 above.
    if " " in local_storage_folder:
        find_links_param = utility.path_to_URL(local_storage_folder)
        if find_links_param[-1] != "/":
            find_links_param += "/"
    else:
        find_links_param = local_storage_folder
    return ["-f", find_links_param, "--allow-hosts=None"]


Instruction:
Can you implement a function in Python 3 that
installs pip and its requirements using setuptools.

Response:
def install_pip(env, requirements):
    """Install pip and its requirements using setuptools."""
    try:
        installation_source_folder = config.installation_cache_folder()
        options = setuptools_install_options(installation_source_folder)
        if installation_source_folder is not None:
            zip_eggs_in_folder(installation_source_folder)
        env.execute(["-m", "easy_install"] + options + requirements)
    except (KeyboardInterrupt, SystemExit):
        raise
    except Exception:
        raise EnvironmentSetupError("pip installation failed.")


Instruction:
Create a Python 3 function to
prepare a pip requirements file if needed.

Response:
def prepare_pip_requirements_file_if_needed(requirements):
    """
    Make requirements be passed to pip via a requirements file if needed.

    We must be careful about how we pass shell operator characters (e.g. '<',
    '>', '|' or '^') included in our command-line arguments or they might cause
    problems if run through an intermediate shell interpreter. If our pip
    requirement specifications contain such characters, we pass them using a
    separate requirements file.

    This problem has been encountered on Windows 7 SP1 x64 using Python 2.4.3,
    2.4.4 & 2.5.4.

    """
    if utility.any_contains_any(requirements, "<>|()&^"):
        file_path, janitor = pip_requirements_file(requirements)
        requirements[:] = ["-r", file_path]
        return janitor


Instruction:
Here you have a function in Python 3, explain what it does
def download_pip_based_installations(env, pip_invocation, requirements,
        download_cache_folder):
    """Download requirements for pip based installation."""
    if config.installation_cache_folder() is None:
        raise EnvironmentSetupError("Local installation cache folder not "
            "defined but required for downloading pip based installations.")
    # Installation cache folder needs to be explicitly created for pip to be
    # able to copy its downloaded installation files into it. The same does not
    # hold for pip's download cache folder which gets created by pip on-demand.
    # Seen using Python 3.4.0 & pip 1.5.4.
    _create_installation_cache_folder_if_needed()
    try:
        pip_options = ["install", "-d", config.installation_cache_folder(),
            "--exists-action=i"]
        pip_options.extend(pip_download_cache_options(download_cache_folder))
        # Running pip based installations on Python 2.5.
        #   * Python 2.5 does not come with SSL support enabled by default and
        #     so pip can not use SSL certified downloads from PyPI.
        #   * To work around this either install the
        #     https://pypi.python.org/pypi/ssl package or run pip using the
        #     '--insecure' command-line options.
        #       * Installing the ssl package seems ridden with problems on
        #         Python 2.5 so this workaround has not been tested.
        if (2, 5) <= env.sys_version_info < (2, 6):
            # There are some potential cases where we do not need to use
            # "--insecure", e.g. if the target Python environment already has
            # the 'ssl' module installed. However, detecting whether this is so
            # does not seem to be worth the effort. The only way to detect
            # whether secure download is supported would be to scan the target
            # environment for this information, e.g. setuptools has this
            # information in its pip.backwardcompat.ssl variable - if it is
            # None, the necessary SSL support is not available. But then we
            # would have to be careful:
            #  - not to run the scan if we already know this information from
            #    some previous scan
            #  - to track all actions that could have invalidated our previous
            #    scan results, etc.
            # It just does not seem to be worth the hassle so for now - YAGNI.
            pip_options.append("--insecure")
        env.execute(pip_invocation + pip_options + requirements)
    except (KeyboardInterrupt, SystemExit):
        raise
    except Exception:
        raise EnvironmentSetupError("pip based download failed.")

Response: Download pip based installations.


Instruction:
Write a Python 3 script to
return a list of actions to perform when processing the given environment.

Response:
def enabled_actions_for_env(env):
    """Returns actions to perform when processing the given environment."""
    def enabled(config_value, required):
        if config_value is Config.TriBool.No:
            return False
        if config_value is Config.TriBool.Yes:
            return True
        assert config_value is Config.TriBool.IfNeeded
        return bool(required)

    # Some old Python versions do not support HTTPS downloads and therefore can
    # not download installation packages from PyPI. To run setuptools or pip
    # based installations on such Python versions, all the required
    # installation packages need to be downloaded locally first using a
    # compatible Python version (e.g. Python 2.4.4 for Python 2.4.3) and then
    # installed locally.
    download_supported = not ((2, 4, 3) <= env.sys_version_info < (2, 4, 4))

    local_install = config.installation_cache_folder() is not None

    actions = set()

    pip_required = False
    run_pip_based_installations = enabled(config.install_environments, True)
    if run_pip_based_installations:
        actions.add("run pip based installations")
        pip_required = True
    if download_supported and enabled(config.download_installations,
            local_install and run_pip_based_installations):
        actions.add("download pip based installations")
        pip_required = True

    setuptools_required = False
    run_pip_installation = enabled(config.install_environments, pip_required)
    if run_pip_installation:
        actions.add("run pip installation")
        setuptools_required = True
    if download_supported and enabled(config.download_installations,
            local_install and run_pip_installation):
        actions.add("download pip installation")
        setuptools_required = True

    if enabled(config.setup_setuptools, setuptools_required):
        actions.add("setup setuptools")

    return actions


Instruction:
Write a Python 3 function for
reading setuptools version from the underlying ez_setup script.

Response:
def __setuptools_version(self):
        """Read setuptools version from the underlying ez_setup script."""
        # Read the script directly as a file instead of importing it as a
        # Python module and reading the value from the loaded module's global
        # DEFAULT_VERSION variable. Not all ez_setup scripts are compatible
        # with all Python environments and so importing them would require
        # doing so using a separate process run in the target Python
        # environment instead of the current one.
        f = open(self.script_path(), "r")
        try:
            matcher = re.compile(r'\s*DEFAULT_VERSION\s*=\s*"([^"]*)"\s*$')
            for i, line in enumerate(f):
                if i > 50:
                    break
                match = matcher.match(line)
                if match:
                    return match.group(1)
        finally:
            f.close()
        self.__error("error parsing setuptools installation script '%s'" % (
            self.script_path(),))


Instruction:
Given the following Python 3 function, write the documentation
def rename(self, name):
        if name is None:
            raise Exception("name (%s) not-valid" % (name,))
        self.prefix, self.name = splitPrefix(name)

Response:
Rename the element.

        @param name: A new name for the element.
        @type name: basestring


Instruction:
Can you generate a brief explanation for the following Python 3 code
def clone(self, parent=None):
        root = Element(self.qname(), parent, self.namespace())
        for a in self.attributes:
            root.append(a.clone(self))
        for c in self.children:
            root.append(c.clone(self))
        for ns in self.nsprefixes.items():
            root.addPrefix(ns[0], ns[1])
        return root

Response: Deep clone of this element and children.


Instruction:
Explain what the following Python 3 code does
def get(self, name, ns=None, default=None):
        attr = self.getAttribute(name, ns)
        if attr is None or attr.value is None:
            return default
        return attr.getValue()

Response: Get the value of an attribute by name.


Instruction:
How would you explain what the following Python 3 function does
def namespace(self):
        if self.prefix is None:
            return self.defaultNamespace()
        return self.resolvePrefix(self.prefix)

Response:
Get the element s namespace by resolving the explicit
            namespace.


Instruction:
How would you explain what the following Python 3 function does
def defaultNamespace(self):
        p = self
        while p is not None:
            if p.expns is not None:
                return None, p.expns
            p = p.parent
        return Namespace.default

Response: Get the default namespace of the current node when not qualified.


Instruction:
How would you explain what the following Python 3 function does
def append(self, objects):
        if not isinstance(objects, (list, tuple)):
            objects = (objects,)
        for child in objects:
            if isinstance(child, Element):
                self.children.append(child)
                child.parent = self
                continue
            if isinstance(child, Attribute):
                self.attributes.append(child)
                child.parent = self
                continue
            raise Exception("append %s not-valid" %
                (child.__class__.__name__,))
        return self

Response: Append the specified child based on whether it is an element or an attribute.


Instruction:
How would you explain what the following Python 3 function does
def insert(self, objects, index=0):
        objects = (objects,)
        for child in objects:
            if not isinstance(child, Element):
                raise Exception("append %s not-valid" %
                    (child.__class__.__name__,))
            self.children.insert(index, child)
            child.parent = self
        return self

Response: Insert an object or collection of objects at the specified index.


Instruction:
Can you create a Python 3 function that
gets a child by name and namespace.

Response:
def getChild(self, name, ns=None, default=None):
        """
        Get a child by (optional) name and/or (optional) namespace.

        @param name: The name of a child element (may contain prefix).
        @type name: basestring
        @param ns: An optional namespace used to match the child.
        @type ns: (I{prefix}, I{name})
        @param default: Returned when child not-found.
        @type default: L{Element}
        @return: The requested child, or I{default} when not-found.
        @rtype: L{Element}

        """
        if ns is None:
            prefix, name = splitPrefix(name)
            if prefix is not None:
                ns = self.resolvePrefix(prefix)
        for c in self.children:
            if c.match(name, ns):
                return c
        return default


Instruction:
How would you explain what the following Python 3 function does
def childAtPath(self, path):
        result = None
        node = self
        for name in path.split("/"):
            if not name:
                continue
            ns = None
            prefix, name = splitPrefix(name)
            if prefix is not None:
                ns = node.resolvePrefix(prefix)
            result = node.getChild(name, ns)
            if result is None:
                return
            node = result
        return result

Response: Get a child at the given path.


Instruction:
Explain what the following Python 3 code does
def childrenAtPath(self, path):
        parts = [p for p in path.split("/") if p]
        if len(parts) == 1:
            return self.getChildren(path)
        return self.__childrenAtPath(parts)

Response: Get a list of children at I { path


Instruction:
Can you write a function in Python 3 where it
gets a list of children by name and namespace.

Response:
def getChildren(self, name=None, ns=None):
        """
        Get a list of children by (optional) name and/or (optional) namespace.

        @param name: The name of a child element (may contain a prefix).
        @type name: basestring
        @param ns: An optional namespace used to match the child.
        @type ns: (I{prefix}, I{name})
        @return: The list of matching children.
        @rtype: [L{Element},...]

        """
        if ns is None:
            if name is None:
                return self.children
            prefix, name = splitPrefix(name)
            if prefix is not None:
                ns = self.resolvePrefix(prefix)
        return [c for c in self.children if c.match(name, ns)]


Instruction:
Write a Python 3 function for
promoting the prefix declarations up the tree as far as possible.

Response:
def promotePrefixes(self):
        """
        Push prefix declarations up the tree as far as possible.

        Prefix mapping are pushed to its parent unless the parent has the
        prefix mapped to another URI or the parent has the prefix. This is
        propagated up the tree until the top is reached.

        @return: self
        @rtype: L{Element}

        """
        for c in self.children:
            c.promotePrefixes()
        if self.parent is None:
            return
        for p, u in self.nsprefixes.items():
            if p in self.parent.nsprefixes:
                pu = self.parent.nsprefixes[p]
                if pu == u:
                    del self.nsprefixes[p]
                continue
            if p != self.parent.prefix:
                self.parent.nsprefixes[p] = u
                del self.nsprefixes[p]
        return self


Instruction:
Given the following Python 3 function, write the documentation
def isempty(self, content=True):
        nochildren = not self.children
        notext = self.text is None
        nocontent = nochildren and notext
        if content:
            return nocontent
        noattrs = not len(self.attributes)
        return nocontent and noattrs

Response: Return True if the element has no children and no attributes.


Instruction:
Write a Python 3 script for
returning True if the element is I { nil } otherwise False.

Response:
def isnil(self):
        """
        Get whether the element is I{nil} as defined by having an
        I{xsi:nil="true"} attribute.

        @return: True if I{nil}, else False
        @rtype: boolean

        """
        nilattr = self.getAttribute("nil", ns=Namespace.xsins)
        return nilattr is not None and (nilattr.getValue().lower() == "true")


Instruction:
Create a Python 3 function for
setting this node to I { nil } as defined by having an I { xsi : nil } = I { flag } = I { flag } = I { nil } = I { flag } = I { nil } = I { flag } = I { nil } = I { flag } = I { nil } = I { flag } = I { nil } = I { flag } = I { nil } = I { nil } = I { nil } = I {

Response:
def setnil(self, flag=True):
        """
        Set this node to I{nil} as defined by having an I{xsi:nil}=I{flag}
        attribute.

        @param flag: A flag indicating how I{xsi:nil} will be set.
        @type flag: boolean
        @return: self
        @rtype: L{Element}

        """
        p, u = Namespace.xsins
        name = ":".join((p, "nil"))
        self.set(name, str(flag).lower())
        self.addPrefix(p, u)
        if flag:
            self.text = None
        return self


Instruction:
Write a Python 3 function for
applying the namespace to this node.

Response:
def applyns(self, ns):
        """
        Apply the namespace to this node.

        If the prefix is I{None} then this element's explicit namespace
        I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is
        simply mapped.

        @param ns: A namespace.
        @type ns: (I{prefix}, I{URI})

        """
        if ns is None:
            return
        if not isinstance(ns, (list, tuple)):
            raise Exception("namespace must be a list or a tuple")
        if ns[0] is None:
            self.expns = ns[1]
        else:
            self.prefix = ns[0]
            self.nsprefixes[ns[0]] = ns[1]


Instruction:
Can you tell what is the following Python 3 function doing
def str(self, indent=0):
        tab = "%*s" % (indent * 3, "")
        result = []
        result.append("%s<%s" % (tab, self.qname()))
        result.append(self.nsdeclarations())
        for a in self.attributes:
            result.append(" %s" % (unicode(a),))
        if self.isempty():
            result.append("/>")
            return "".join(result)
        result.append(">")
        if self.hasText():
            result.append(self.text.escape())
        for c in self.children:
            result.append("\n")
            result.append(c.str(indent + 1))
        if len(self.children):
            result.append("\n%s" % (tab,))
        result.append("</%s>" % (self.qname(),))
        return "".join(result)

Response: Get a string representation of this XML fragment.


Instruction:
Explain what the following Python 3 code does
def plain(self):
        result = ["<%s" % (self.qname(),), self.nsdeclarations()]
        for a in self.attributes:
            result.append(" %s" % (unicode(a),))
        if self.isempty():
            result.append("/>")
            return "".join(result)
        result.append(">")
        if self.hasText():
            result.append(self.text.escape())
        for c in self.children:
            result.append(c.plain())
        result.append("</%s>" % (self.qname(),))
        return "".join(result)

Response: Get a string representation of this XML fragment.


Instruction:
Write a Python 3 script for
getting a string representation for all namespace declarations as xmlns = None and xmlns : p = None.

Response:
def nsdeclarations(self):
        """
        Get a string representation for all namespace declarations as xmlns=""
        and xmlns:p="".

        @return: A separated list of declarations.
        @rtype: basestring

        """
        s = []
        myns = None, self.expns
        if self.parent is None:
            pns = Namespace.default
        else:
            pns = None, self.parent.expns
        if myns[1] != pns[1]:
            if self.expns is not None:
                s.append(' xmlns="%s"' % (self.expns,))
        for item in self.nsprefixes.items():
            p, u = item
            if self.parent is not None:
                ns = self.parent.resolvePrefix(p)
                if ns[1] == u:
                    continue
            s.append(' xmlns:%s="%s"' % (p, u))
        return "".join(s)


Instruction:
Write a Python 3 function for
opening a WSDL schema at the specified I { URL.

Response:
def open(self, url):
        """
        Open a WSDL schema at the specified I{URL}.

        First, the WSDL schema is looked up in the I{object cache}. If not
        found, a new one constructed using the I{fn} factory function and the
        result is cached for the next open().

        @param url: A WSDL URL.
        @type url: str.
        @return: The WSDL object.
        @rtype: I{Definitions}

        """
        cache = self.__cache()
        id = self.mangle(url, "wsdl")
        wsdl = cache.get(id)
        if wsdl is None:
            wsdl = self.fn(url, self.options)
            cache.put(id, wsdl)
        else:
            # Cached WSDL Definitions objects may have been created with
            # different options so we update them here with our current ones.
            wsdl.options = self.options
            for imp in wsdl.imports:
                imp.imported.options = self.options
        return wsdl


Instruction:
Write a Python 3 function for
getting the I { object cache } when I { cachingpolicy = B1.

Response:
def __cache(self):
        """
        Get the I{object cache}.

        @return: The I{cache} when I{cachingpolicy} = B{1}.
        @rtype: L{Cache}

        """
        if self.options.cachingpolicy == 1:
            return self.options.cache
        return suds.cache.NoCache()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def open(self, url):
        cache = self.__cache()
        id = self.mangle(url, "document")
        xml = cache.get(id)
        if xml is None:
            xml = self.__fetch(url)
            cache.put(id, xml)
        self.plugins.document.parsed(url=url, document=xml.root())
        return xml

Response: Open an XML document at the specified URL.


Instruction:
How would you explain what the following Python 3 function does
def __fetch(self, url):
        content = None
        store = self.options.documentStore
        if store is not None:
            content = store.open(url)
        if content is None:
            request = suds.transport.Request(url)
            fp = self.options.transport.open(request)
            try:
                content = fp.read()
            finally:
                fp.close()
        ctx = self.plugins.document.loaded(url=url, document=content)
        content = ctx.document
        sax = suds.sax.parser.Parser()
        return sax.parse(string=content)

Response: Fetch the content of a document from an external source.


Instruction:
Create a Python 3 function to
encode special characters found in string I { s.

Response:
def encode(self, s):
        """
        Encode special characters found in string I{s}.

        @param s: A string to encode.
        @type s: str
        @return: The encoded string.
        @rtype: str

        """
        if isinstance(s, basestring) and self.__needs_encoding(s):
            for x in self.encodings:
                s = re.sub(x[0], x[1], s)
        return s


Instruction:
Make a summary of the following Python 3 code
def __needs_encoding(self, s):
        if isinstance(s, basestring):
            for c in self.special:
                if c in s:
                    return True

Response: Check if string I { s contains special characters.


Instruction:
How would you explain what the following Python 3 function does
def virtualenv_requirements(version_info=sys.version_info):
    if version_info < (2, 5):
        # 'virtualenv' release 1.8 dropped Python 2.4.x compatibility.
        yield requirement_spec("virtualenv",
            ("<", lowest_version_string_with_prefix("1.8")))
    elif version_info < (2, 6):
        # 'virtualenv' release 1.10 dropped Python 2.5.x compatibility.
        yield requirement_spec("virtualenv",
            ("<", lowest_version_string_with_prefix("1.10")))
    else:
        yield requirement_spec("virtualenv")

Response: Generate a generator of all the virtualenv packages that are available on the current Python version.


Instruction:
Make a summary of the following Python 3 code
def __construct_python_version(self):
        major, minor, micro, release_level, serial = self.sys_version_info
        assert release_level in ("alfa", "beta", "candidate", "final")
        assert release_level != "final" or serial == 0
        parts = [str(major), ".", str(minor), ".", str(micro)]
        if release_level != "final":
            parts.append(release_level[0])
            parts.append(str(serial))
        self.python_version = "".join(parts)

Response: Construct a setuptools compatible Python version string.


Instruction:
Make a summary of the following Python 3 code
def __parse_scanned_version_info(self):
        string = self.sys_version_info_formatted
        try:
            major, minor, micro, release_level, serial = string.split(",")
            if (release_level in ("alfa", "beta", "candidate", "final") and
                    (release_level != "final" or serial == "0") and
                    major.isdigit() and  # --- --- --- --- --- --- --- --- ---
                    minor.isdigit() and  # Explicit isdigit() checks to detect
                    micro.isdigit() and  # leading/trailing whitespace.
                    serial.isdigit()):   # --- --- --- --- --- --- --- --- ---
                self.sys_version_info = (int(major), int(minor), int(micro),
                    release_level, int(serial))
                self.__construct_python_version()
                return
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            pass
        raise BadEnvironment("Unsupported Python version (%s)" % (string,))

Response: Parses the environment s formatted version info string and returns a tuple of integers.


Instruction:
Create a Python 3 function for
printing complex using the specified indent n and newline ( nl ).

Response:
def print_dictionary(self, d, h, n, nl=False):
        """Print complex using the specified indent (n) and newline (nl)."""
        if d in h:
            return "{}..."
        h.append(d)
        s = []
        if nl:
            s.append("\n")
            s.append(self.indent(n))
        s.append("{")
        for item in d.items():
            s.append("\n")
            s.append(self.indent(n+1))
            if isinstance(item[1], (list,tuple)):
                s.append(tostr(item[0]))
                s.append("[]")
            else:
                s.append(tostr(item[0]))
            s.append(" = ")
            s.append(self.process(item[1], h, n, True))
        s.append("\n")
        s.append(self.indent(n))
        s.append("}")
        h.pop()
        return "".join(s)


Instruction:
Write a Python 3 script for
printing a collection using the specified indent n and newline nl.

Response:
def print_collection(self, c, h, n):
        """Print collection using the specified indent (n) and newline (nl)."""
        if c in h:
            return "[]..."
        h.append(c)
        s = []
        for item in c:
            s.append("\n")
            s.append(self.indent(n))
            s.append(self.process(item, h, n - 2))
            s.append(",")
        h.pop()
        return "".join(s)


Instruction:
Here you have a function in Python 3, explain what it does
def node(self, content):
        ns = content.type.namespace()
        if content.type.form_qualified:
            node = Element(content.tag, ns=ns)
            if ns[0]:
                node.addPrefix(ns[0], ns[1])
        else:
            node = Element(content.tag)
        self.encode(node, content)
        log.debug("created - node:\n%s", node)
        return node

Response: Create an XML node.


Instruction:
Can you write a function in Python 3 where it
adds encoding information to the node.

Response:
def encode(self, node, content):
        """
        Add (SOAP) encoding information if needed.

        The encoding information is added only if the resolved type is derived
        by extension. Furthermore, the xsi:type value is qualified by namespace
        only if the content (tag) and referenced type are in different
        namespaces.

        """
        if content.type.any():
            return
        if not content.real.extension():
            return
        if content.type.resolve() == content.real:
            return
        ns = None
        name = content.real.name
        if self.xstq:
            ns = content.real.namespace("ns1")
        Typer.manual(node, name, ns)


Instruction:
Create a Python 3 function for
returning True if the content should be skipped.

Response:
def skip(self, content):
        """
        Get whether to skip this I{content}.

        Should be skipped when the content is optional and value is either None
        or an empty list.

        @param content: Content to skip.
        @type content: L{Object}
        @return: True if content is to be skipped.
        @rtype: bool

        """
        if self.optional(content):
            v = content.value
            if v is None:
                return True
            if isinstance(v, (list, tuple)) and not v:
                return True
        return False


Instruction:
Write a Python 3 function for
detecting egg distributions located in the given folder.

Response:
def _detect_eggs_in_folder(folder):
    """
    Detect egg distributions located in the given folder.

    Only direct folder content is considered and subfolders are not searched
    recursively.

    """
    eggs = {}
    for x in os.listdir(folder):
        zip = x.endswith(_zip_ext)
        if zip:
            root = x[:-len(_zip_ext)]
            egg = _Egg.NONE
        elif x.endswith(_egg_ext):
            root = x[:-len(_egg_ext)]
            if os.path.isdir(os.path.join(folder, x)):
                egg = _Egg.FOLDER
            else:
                egg = _Egg.FILE
        else:
            continue
        try:
            info = eggs[root]
        except KeyError:
            eggs[root] = _Egg(os.path.join(folder, root), egg, zip)
        else:
            if egg is not _Egg.NONE:
                info.set_egg(egg)
            if zip:
                info.set_zip()
    return eggs.values()


Instruction:
Implement a Python 3 function for
normalizing the contents of the egg distribution to be a single egg file.

Response:
def normalize(self):
        """
        Makes sure this egg distribution is stored only as an egg file.

        The egg file will be created from another existing distribution format
        if needed.

        """
        if self.has_egg_file():
            if self.has_zip():
                self.__remove_zip()
        else:
            if self.has_egg_folder():
                if not self.has_zip():
                    self.__zip_egg_folder()
                self.__remove_egg_folder()
            self.__rename_zip_to_egg()


Instruction:
Can you tell what is the following Python 3 function doing
def parse_args(method_name, param_defs, args, kwargs, external_param_processor,
    extra_parameter_errors):
    """
    Parse arguments for suds web service operation invocation functions.

    Suds prepares Python function objects for invoking web service operations.
    This function implements generic binding agnostic part of processing the
    arguments passed when calling those function objects.

    Argument parsing rules:
      * Each input parameter element should be represented by single regular
        Python function argument.
      * At most one input parameter belonging to a single choice parameter
        structure may have its value specified as something other than None.
      * Positional arguments are mapped to choice group input parameters the
        same as is done for a simple all/sequence group - each in turn.

    Expects to be passed the web service operation's parameter definitions
    (parameter name, type & optional ancestry information) in order and, based
    on that, extracts the values for those parameter from the arguments
    provided in the web service operation invocation call.

    Ancestry information describes parameters constructed based on suds
    library's automatic input parameter structure unwrapping. It is expected to
    include the parameter's XSD schema 'ancestry' context, i.e. a list of all
    the parent XSD schema tags containing the parameter's <element> tag. Such
    ancestry context provides detailed information about how the parameter's
    value is expected to be used, especially in relation to other input
    parameters, e.g. at most one parameter value may be specified for
    parameters directly belonging to the same choice input group.

    Rules on acceptable ancestry items:
      * Ancestry item's choice() method must return whether the item
        represents a <choice> XSD schema tag.
      * Passed ancestry items are used 'by address' internally and the same XSD
        schema tag is expected to be identified by the exact same ancestry item
        object during the whole argument processing.

    During processing, each parameter's definition and value, together with any
    additional pertinent information collected from the encountered parameter
    definition structure, is passed on to the provided external parameter
    processor function. There that information is expected to be used to
    construct the actual binding specific web service operation invocation
    request.

    Raises a TypeError exception in case any argument related errors are
    detected. The exceptions raised have been constructed to make them as
    similar as possible to their respective exceptions raised during regular
    Python function argument checking.

    Does not support multiple same-named input parameters.

    """
    arg_parser = _ArgParser(method_name, param_defs, external_param_processor)
    return arg_parser(args, kwargs, extra_parameter_errors)

Response: Parses the arguments passed to the suds web service operation invocation functions.


Instruction:
Can you generate the documentation for the following Python 3 function
def __all_parameters_processed(self):
        assert self.active()
        sentinel_frame = self.__stack[0]
        self.__pop_frames_above(sentinel_frame)
        assert len(self.__stack) == 1
        self.__pop_top_frame()
        assert not self.active()
        args_required = sentinel_frame.args_required()
        args_allowed = sentinel_frame.args_allowed()
        self.__check_for_extra_arguments(args_required, args_allowed)
        return args_required, args_allowed

Response: Finish the argument processing.


Instruction:
How would you implement a function in Python 3 that
checks if any extra arguments are detected.

Response:
def __check_for_extra_arguments(self, args_required, args_allowed):
        """
        Report an error in case any extra arguments are detected.

        Does nothing if reporting extra arguments as exceptions has not been
        enabled.

        May only be called after the argument processing has been completed.

        """
        assert not self.active()
        if not self.__extra_parameter_errors:
            return

        if self.__kwargs:
            param_name = self.__kwargs.keys()[0]
            if param_name in self.__params_with_arguments:
                msg = "got multiple values for parameter '%s'"
            else:
                msg = "got an unexpected keyword argument '%s'"
            self.__error(msg % (param_name,))

        if self.__args:
            def plural_suffix(count):
                if count == 1:
                    return ""
                return "s"
            def plural_was_were(count):
                if count == 1:
                    return "was"
                return "were"
            expected = args_required
            if args_required != args_allowed:
                expected = "%d to %d" % (args_required, args_allowed)
            given = self.__args_count
            msg_parts = ["takes %s positional argument" % (expected,),
                plural_suffix(expected), " but %d " % (given,),
                plural_was_were(given), " given"]
            self.__error("".join(msg_parts))


Instruction:
Implement a Python 3 function for
constructing a new frame representing the given ancestry item.

Response:
def __frame_factory(self, ancestry_item):
        """Construct a new frame representing the given ancestry item."""
        frame_class = Frame
        if ancestry_item is not None and ancestry_item.choice():
            frame_class = ChoiceFrame
        return frame_class(ancestry_item, self.__error,
            self.__extra_parameter_errors)


Instruction:
Write a Python 3 script to
extract a parameter value from the remaining arguments.

Response:
def __get_param_value(self, name):
        """
        Extract a parameter value from the remaining given arguments.

        Returns a 2-tuple consisting of the following:
          * Boolean indicating whether an argument has been specified for the
            requested input parameter.
          * Parameter value.

        """
        if self.__args:
            return True, self.__args.pop(0)
        try:
            value = self.__kwargs.pop(name)
        except KeyError:
            return False, None
        return True, value


Instruction:
Write a Python 3 function for
returning True if we are currently processing a choice parameter group.

Response:
def __in_choice_context(self):
        """
        Whether we are currently processing a choice parameter group.

        This includes processing a parameter defined directly or indirectly
        within such a group.

        May only be called during parameter processing or the result will be
        calculated based on the context left behind by the previous parameter
        processing if any.

        """
        for x in self.__stack:
            if x.__class__ is ChoiceFrame:
                return True
        return False


Instruction:
Write a Python 3 script for
initializing data for a new argument parsing run.

Response:
def __init_run(self, args, kwargs, extra_parameter_errors):
        """Initializes data for a new argument parsing run."""
        assert not self.active()
        self.__args = list(args)
        self.__kwargs = dict(kwargs)
        self.__extra_parameter_errors = extra_parameter_errors
        self.__args_count = len(args) + len(kwargs)
        self.__params_with_arguments = set()
        self.__stack = []
        self.__push_frame(None)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __match_ancestry(self, ancestry):
        stack = self.__stack
        if len(stack) == 1:
            return stack[0], ancestry
        previous = stack[0]
        for frame, n in zip(stack[1:], xrange(len(ancestry))):
            if frame.id() is not ancestry[n]:
                return previous, ancestry[n:]
            previous = frame
        return frame, ancestry[n + 1:]

Response: Find frames matching the given ancestry.


Instruction:
Can you generate the documentation for the following Python 3 function
def __pop_frames_above(self, frame):
        while self.__stack[-1] is not frame:
            self.__pop_top_frame()
        assert self.__stack

Response: Pops all the frames above the given frame.


Instruction:
Can you generate the documentation for the following Python 3 function
def __pop_top_frame(self):
        popped = self.__stack.pop()
        if self.__stack:
            self.__stack[-1].process_subframe(popped)

Response: Pops the top frame off the frame stack.


Instruction:
Can you generate the documentation for the following Python 3 function
def __process_parameter(self, param_name, param_type, ancestry=None):
        assert self.active()
        param_optional = param_type.optional()
        has_argument, value = self.__get_param_value(param_name)
        if has_argument:
            self.__params_with_arguments.add(param_name)
        self.__update_context(ancestry)
        self.__stack[-1].process_parameter(param_optional, value is not None)
        self.__external_param_processor(param_name, param_type,
            self.__in_choice_context(), value)

Response: Collect values for a given web service operation input parameter.


Instruction:
Write a Python 3 script to
push a new frame on top of the stack.

Response:
def __push_frame(self, ancestry_item):
        """Push a new frame on top of the frame stack."""
        frame = self.__frame_factory(ancestry_item)
        self.__stack.append(frame)


Instruction:
Create a Python 3 function for
opening a document at the specified URL.

Response:
def open(self, url):
        """
        Open a document at the specified URL.

        The document URL's needs not contain a protocol identifier, and if it
        does, that protocol identifier is ignored when looking up the store
        content.

        Missing documents referenced using the internal 'suds' protocol are
        reported by raising an exception. For other protocols, None is returned
        instead.

        @param url: A document URL.
        @type url: str
        @return: Document content or None if not found.
        @rtype: bytes

        """
        protocol, location = self.__split(url)
        content = self.__find(location)
        if protocol == 'suds' and content is None:
            raise Exception, 'location "%s" not in document store' % location
        return content


Instruction:
Write a Python 3 function for
returning the given Python source file s compiled content.

Response:
def read_python_code(filename):
    "Returns the given Python source file's compiled content."
    file = open(filename, "rt")
    try:
        source = file.read()
    finally:
        file.close()
    # Python 2.6 and below did not support passing strings to exec() &
    # compile() functions containing line separators other than '\n'. To
    # support them we need to manually make sure such line endings get
    # converted even on platforms where this is not handled by native text file
    # read operations.
    source = source.replace("\r\n", "\n").replace("\r", "\n")
    return compile(source, filename, "exec")


Instruction:
Can you create a Python 3 function that
returns a list of all the given packages and all their subpackages. Given packages are expected to be found relative to this script's location. Subpackages are detected by scanning the given packages' subfolder hierarchy for any folders containing the '__init__.py' module. As a consequence, namespace packages are not supported. This is our own specialized setuptools.find_packages() replacement so we can avoid the setuptools dependency.

Response:
def recursive_package_list(*packages):
    """
    Returns a list of all the given packages and all their subpackages.

    Given packages are expected to be found relative to this script's location.

    Subpackages are detected by scanning the given packages' subfolder
    hierarchy for any folders containing the '__init__.py' module. As a
    consequence, namespace packages are not supported.

    This is our own specialized setuptools.find_packages() replacement so we
    can avoid the setuptools dependency.

    """
    result = set()
    todo = []
    for package in packages:
        folder = os.path.join(script_folder, *package.split("."))
        if not os.path.isdir(folder):
            raise Exception("Folder not found for package '%s'." % (package,))
        todo.append((package, folder))
    while todo:
        package, folder = todo.pop()
        if package in result:
            continue
        result.add(package)
        for subitem in os.listdir(folder):
            subpackage = ".".join((package, subitem))
            subfolder = os.path.join(folder, subitem)
            if not os.path.isfile(os.path.join(subfolder, "__init__.py")):
                continue
            todo.append((subpackage, subfolder))
    return list(result)


Instruction:
Can you tell what is the following Python 3 function doing
def multi_occurrence(self):
        max = self.max
        if max is None:
            return False
        if max.isdigit():
            return int(max) > 1
        return max == "unbounded"

Response: Returns True if the node has at most one occurrence.


Instruction:
Can you write a function in Python 3 where it
finds a referenced type in self or children. Return None if not found.

Response:
def find(self, qref, classes=[], ignore=None):
        """
        Find a referenced type in self or children. Return None if not found.

        Qualified references for all schema objects checked in this search will
        be added to the set of ignored qualified references to avoid the find
        operation going into an infinite loop in case of recursively defined
        structures.

        @param qref: A qualified reference.
        @type qref: qref
        @param classes: A collection of classes used to qualify the match.
        @type classes: Collection(I{class},...), e.g. [I(class),...]
        @param ignore: A set of qualified references to ignore in this search.
        @type ignore: {qref,...}
        @return: The referenced type.
        @rtype: L{SchemaObject}
        @see: L{qualify()}

        """
        if not len(classes):
            classes = (self.__class__,)
        if ignore is None:
            ignore = set()
        if self.qname in ignore:
            return
        ignore.add(self.qname)
        if self.qname == qref and self.__class__ in classes:
            return self
        for c in self.rawchildren:
            p = c.find(qref, classes, ignore=ignore)
            if p is not None:
                return p


Instruction:
Explain what the following Python 3 code does
def next(self):
        frame = self.top()
        while True:
            result = frame.next()
            if result is None:
                self.pop()
                return self.next()
            if isinstance(result, Content):
                ancestry = [f.sx for f in self.stack]
                return result, ancestry
            self.push(result)
            return self.next()

Response: Get the next item.


Instruction:
Implement a function in Python 3 to
process the content using the optional type information.

Response:
def process(self, content):
        """
        Process (marshal) the tag with the specified value using the
        optional type information.
        @param content: The content to process.
        @type content: L{Object}
        """
        log.debug('processing:\n%s', content)
        self.reset()
        if content.tag is None:
            content.tag = content.value.__class__.__name__
        document = Document()
        self.append(document, content)
        return document.root()


Instruction:
How would you implement a function in Python 3 that
adds prefixes for each namespace referenced by parameter types.

Response:
def getprefixes(self):
        """Add prefixes for each namespace referenced by parameter types."""
        namespaces = []
        for l in (self.params, self.types):
            for t,r in l:
                ns = r.namespace()
                if ns[1] is None: continue
                if ns[1] in namespaces: continue
                if Namespace.xs(ns) or Namespace.xsd(ns):
                    continue
                namespaces.append(ns[1])
                if t == r: continue
                ns = t.namespace()
                if ns[1] is None: continue
                if ns[1] in namespaces: continue
                namespaces.append(ns[1])
        i = 0
        namespaces.sort()
        for u in namespaces:
            p = self.nextprefix()
            ns = (p, u)
            self.prefixes.append(ns)


Instruction:
Explain what the following Python 3 code does
def xlate(self, type):
        resolved = type.resolve()
        name = resolved.name
        if type.multi_occurrence():
            name += '[]'
        ns = resolved.namespace()
        if ns[1] == self.wsdl.tns[1]:
            return name
        prefix = self.getprefix(ns[1])
        return ':'.join((prefix, name))

Response: Get a ( namespace ) translated I{qualified name for specified type.


Instruction:
Here you have a function in Python 3, explain what it does
def description(self):
        s = []
        indent = (lambda n :  '\n%*s'%(n*3,' '))
        s.append('Service ( %s ) tns="%s"' % (self.service.name, self.wsdl.tns[1]))
        s.append(indent(1))
        s.append('Prefixes (%d)' % len(self.prefixes))
        for p in self.prefixes:
            s.append(indent(2))
            s.append('%s = "%s"' % p)
        s.append(indent(1))
        s.append('Ports (%d):' % len(self.ports))
        for p in self.ports:
            s.append(indent(2))
            s.append('(%s)' % p[0].name)
            s.append(indent(3))
            s.append('Methods (%d):' % len(p[1]))
            for m in p[1]:
                sig = []
                s.append(indent(4))
                sig.append(m[0])
                sig.append('(')
                sig.append(', '.join("%s %s" % (self.xlate(p[1]), p[0]) for p
                    in m[1]))
                sig.append(')')
                try:
                    s.append(''.join(sig))
                except Exception:
                    pass
            s.append(indent(3))
            s.append('Types (%d):' % len(self.types))
            for t in self.types:
                s.append(indent(4))
                s.append(self.xlate(t[0]))
        s.append('\n\n')
        return ''.join(s)

Response: Get a textual description of the service for which this object represents.


Instruction:
Write a Python 3 function for
appending the root element to the document root element.

Response:
def append(self, node):
        """
        Append (set) the document root.
        @param node: A root L{Element} or name used to build
            the document root element.
        @type node: (L{Element}|str|None)
        """
        if isinstance(node, basestring):
            self.__root = Element(node)
            return
        if isinstance(node, Element):
            self.__root = node
            return


Instruction:
Can you tell what is the following Python 3 function doing
def getChild(self, name, ns=None, default=None):
        if self.__root is None:
            return default
        if ns is None:
            prefix, name = splitPrefix(name)
            if prefix is None:
                ns = None
            else:
                ns = self.__root.resolvePrefix(prefix)
        if self.__root.match(name, ns):
            return self.__root
        else:
            return default

Response: Get a child by name and namespace.


Instruction:
Can you implement a function in Python 3 that
gets a child at the specified path.

Response:
def childAtPath(self, path):
        """
        Get a child at I{path} where I{path} is a (/) separated
        list of element names that are expected to be children.
        @param path: A (/) separated list of element names.
        @type path: basestring
        @return: The leaf node at the end of I{path}
        @rtype: L{Element}
        """
        if self.__root is None:
            return None
        if path[0] == '/':
            path = path[1:]
        path = path.split('/',1)
        if self.getChild(path[0]) is None:
            return None
        if len(path) > 1:
            return self.__root.childAtPath(path[1])
        else:
            return self.__root


Instruction:
Explain what the following Python 3 code does
def childrenAtPath(self, path):
        if self.__root is None:
            return []
        if path[0] == '/':
            path = path[1:]
        path = path.split('/',1)
        if self.getChild(path[0]) is None:
            return []
        if len(path) > 1:
            return self.__root.childrenAtPath(path[1])
        else:
            return [self.__root,]

Response: Get a list of children at the end of a path.


Instruction:
Create a Python 3 function to
get a list of children by name and namespace.

Response:
def getChildren(self, name=None, ns=None):
        """
        Get a list of children by (optional) name and/or (optional) namespace.
        @param name: The name of a child element (may contain prefix).
        @type name: basestring
        @param ns: An optional namespace used to match the child.
        @type ns: (I{prefix}, I{name})
        @return: The list of matching children.
        @rtype: [L{Element},...]
        """
        if name is None:
            matched = self.__root
        else:
            matched = self.getChild(name, ns)
        if matched is None:
            return []
        else:
            return [matched,]


Instruction:
Create a Python 3 function for
getting a string representation of this XML document.

Response:
def plain(self):
        """
        Get a string representation of this XML document.
        @return: A I{plain} string.
        @rtype: basestring
        """
        s = []
        s.append(self.DECL)
        root = self.root()
        if root is not None:
            s.append(root.plain())
        return ''.join(s)


Instruction:
Here you have a function in Python 3, explain what it does
def merge(self):
        if self.children:
            schema = self.children[0]
            for s in self.children[1:]:
                schema.merge(s)
            return schema

Response: Merge contained schemas into one.


Instruction:
Can you tell what is the following Python 3 function doing
def mktns(self):
        tns = self.root.get("targetNamespace")
        tns_prefix = None
        if tns is not None:
            tns_prefix = self.root.findPrefix(tns)
        return tns_prefix, tns

Response: Make the schema s target namespace.