Instruction:
Explain what the following Python 3 code does
def step(self):
        # type: () -> bool
        """
        Decreases the internal counter. Raises an error if the counter goes
        below 0

        :return: True if this step was the final one, else False
        :raise ValueError: The counter has gone below 0
        """
        with self.__lock:
            self.__value -= 1
            if self.__value == 0:
                # All done
                self.__event.set()
                return True
            elif self.__value < 0:
                # Gone too far
                raise ValueError("The counter has gone below 0")

        return False

Response: Decreases the internal counter and returns True if this step was the final one. Raises an error if the counter goes below 0


Instruction:
Implement a function in Python 3 to
display the available bundle matches and the bundle name.

Response:
def display_hook(prompt, session, context, matches, longest_match_len):
        # type: (str, ShellSession, BundleContext, List[str], int) -> None
        """
        Displays the available bundle matches and the bundle name

        :param prompt: Shell prompt string
        :param session: Current shell session (for display)
        :param context: BundleContext of the shell
        :param matches: List of words matching the substitution
        :param longest_match_len: Length of the largest match
        """
        # Prepare a line pattern for each match
        match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len)

        # Sort matching IDs
        matches = sorted(int(match) for match in matches)

        # Print the match and the associated name
        session.write_line()
        for bnd_id in matches:
            bnd = context.get_bundle(bnd_id)
            session.write_line(match_pattern, bnd_id, bnd.get_symbolic_name())

        # Print the prompt, then current line
        session.write(prompt)
        session.write_line_no_feed(readline.get_line_buffer())
        readline.redisplay()


Instruction:
Can you write a function in Python 3 where it
completes the current word - value - list of bundle IDs matching the current word - value

Response:
def complete(
        self, config, prompt, session, context, current_arguments, current
    ):
        # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
        """
        Returns the list of bundle IDs matching the current state

        :param config: Configuration of the current completion
        :param prompt: Shell prompt (for re-display)
        :param session: Shell session (to display in shell)
        :param context: Bundle context of the Shell bundle
        :param current_arguments: Current arguments (without the command itself)
        :param current: Current word
        :return: A list of matches
        """
        # Register a method to display helpful completion
        self.set_display_hook(self.display_hook, prompt, session, context)

        # Return a list of bundle IDs (strings) matching the current value
        # and not yet in arguments
        rl_matches = []
        for bnd in context.get_bundles():
            bnd_id = "{0} ".format(bnd.get_bundle_id())
            if bnd_id.startswith(current):
                rl_matches.append(bnd_id)

        return rl_matches


Instruction:
Can you write a function in Python 3 where it
displays the available services matches and the service details.

Response:
def display_hook(prompt, session, context, matches, longest_match_len):
        # type: (str, ShellSession, BundleContext, List[str], int) -> None
        """
        Displays the available services matches and the service details

        :param prompt: Shell prompt string
        :param session: Current shell session (for display)
        :param context: BundleContext of the shell
        :param matches: List of words matching the substitution
        :param longest_match_len: Length of the largest match
        """
        try:
            # Prepare a line pattern for each match
            match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len)

            # Sort matching IDs
            matches = sorted(int(match) for match in matches)

            # Print the match and the associated name
            session.write_line()
            for svc_id in matches:
                svc_ref = context.get_service_reference(
                    None, "({}={})".format(SERVICE_ID, svc_id)
                )
                session.write_line(match_pattern, svc_id, str(svc_ref))

            # Print the prompt, then current line
            session.write(prompt)
            session.write_line_no_feed(readline.get_line_buffer())
            readline.redisplay()
        except Exception as ex:
            session.write_line("\n{}\n\n", ex)


Instruction:
Can you create a Python 3 function that
completes the current value of the current key - value pair.

Response:
def complete(
        self, config, prompt, session, context, current_arguments, current
    ):
        # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
        """
        Returns the list of services IDs matching the current state

        :param config: Configuration of the current completion
        :param prompt: Shell prompt (for re-display)
        :param session: Shell session (to display in shell)
        :param context: Bundle context of the Shell bundle
        :param current_arguments: Current arguments (without the command itself)
        :param current: Current word
        :return: A list of matches
        """
        # Register a method to display helpful completion
        self.set_display_hook(self.display_hook, prompt, session, context)

        # Return a list of bundle IDs (strings) matching the current value
        # and not yet in arguments
        rl_matches = []
        for svc_ref in context.get_all_service_references(None, None):
            svc_id = "{0} ".format(svc_ref.get_property(SERVICE_ID))
            if svc_id.startswith(current):
                rl_matches.append(svc_id)

        return rl_matches


Instruction:
Write a Python 3 script for
returning True if this distribution provider supports export for given exported_configs service_intents and export_props.

Response:
def supports_export(self, exported_configs, service_intents, export_props):
        """
        Method called by rsa.export_service to ask if this
        ExportDistributionProvider supports export for given
        exported_configs (list), service_intents (list), and
        export_props (dict).

        If a ExportContainer instance is returned then it is used to export
        the service.  If None is returned, then this distribution provider will
        not be used to export the service.

        The default implementation returns self._get_or_create_container.
        """
        return self._get_or_create_container(
            exported_configs, service_intents, export_props
        )


Instruction:
How would you implement a function in Python 3 that
returns True if this distribution provider supports import for given exported_configs service_intents and endpoint_props.

Response:
def supports_import(
        self, exported_configs, service_intents, endpoint_props
    ):
        """
        Method called by rsa.export_service to ask if this
        ImportDistributionProvider supports import for given
        exported_configs (list), service_intents (list), and
        export_props (dict).

        If a ImportContainer instance is returned then it is used to import
        the service.  If None is returned, then this distribution provider will
        not be used to import the service.

        The default implementation returns self._get_or_create_container.
        """
        return self._get_or_create_container(
            exported_configs, service_intents, endpoint_props
        )


Instruction:
Create a Python 3 function for
checking if the component is valid.

Response:
def is_valid(self):
        # type: () -> bool
        """
        Checks if the component is valid

        :return: Always True if it doesn't raise an exception
        :raises AssertionError: Invalid properties
        """
        assert self._bundle_context
        assert self._container_props is not None
        assert self._get_distribution_provider()
        assert self.get_config_name()
        assert self.get_namespace()
        return True


Instruction:
Given the following Python 3 function, write the documentation
def _validate_component(self, bundle_context, container_props):
        # type: (BundleContext, Dict[str, Any]) -> None
        """
        Component validated

        :param bundle_context: Bundle context
        :param container_props: Instance properties
        :raises AssertionError: Invalid properties
        """
        self._bundle_context = bundle_context
        self._container_props = container_props
        self.is_valid()

Response:
Component validated

        :param bundle_context: Bundle context
        :param container_props: Instance properties
        :raises AssertionError: Invalid properties


Instruction:
How would you explain what the following Python 3 function does
def _add_export(self, ed_id, inst):
        # type: (str, Tuple[Any, EndpointDescription]) -> None
        """
        Keeps track of an exported service

        :param ed_id: ID of the endpoint description
        :param inst: A tuple: (service instance, endpoint description)
        """
        with self._exported_instances_lock:
            self._exported_services[ed_id] = inst

Response: Adds an exported service instance to the exported list.


Instruction:
Can you generate the documentation for the following Python 3 function
def _find_export(self, func):
        # type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]
        """
        Look for an export using the given lookup method

        The lookup method must accept a single parameter, which is a tuple
        containing a service instance and endpoint description.

        :param func: A function to look for the excepted export
        :return: The found tuple or None
        """
        with self._exported_instances_lock:
            for val in self._exported_services.values():
                if func(val):
                    return val

            return None

Response: Searches for an export using a given function


Instruction:
How would you implement a function in Python 3 that
registers a service export entry into the cache.

Response:
def _export_service(self, svc, ed):
        # type: (Any, EndpointDescription) -> None
        """
        Registers a service export

        :param svc: Service instance
        :param ed: Endpoint description
        """
        self._add_export(ed.get_id(), (svc, ed))


Instruction:
Implement a function in Python 3 to
prepare the properties of an endpoint

Response:
def prepare_endpoint_props(self, intfs, svc_ref, export_props):
        # type: (List[str], ServiceReference, Dict[str, Any]) -> Dict[str, Any]
        """
        Sets up the properties of an endpoint

        :param intfs: Specifications to export
        :param svc_ref: Reference of the exported service
        :param export_props: Export properties
        :return: The properties of the endpoint
        """
        pkg_vers = rsa.get_package_versions(intfs, export_props)
        exported_configs = get_string_plus_property_value(
            svc_ref.get_property(SERVICE_EXPORTED_CONFIGS)
        )
        if not exported_configs:
            exported_configs = [self.get_config_name()]
        service_intents = set()
        svc_intents = export_props.get(SERVICE_INTENTS, None)
        if svc_intents:
            service_intents.update(svc_intents)
        svc_exp_intents = export_props.get(SERVICE_EXPORTED_INTENTS, None)
        if svc_exp_intents:
            service_intents.update(svc_exp_intents)
        svc_exp_intents_extra = export_props.get(
            SERVICE_EXPORTED_INTENTS_EXTRA, None
        )
        if svc_exp_intents_extra:
            service_intents.update(svc_exp_intents_extra)

        rsa_props = rsa.get_rsa_props(
            intfs,
            exported_configs,
            self._get_supported_intents(),
            svc_ref.get_property(SERVICE_ID),
            export_props.get(ENDPOINT_FRAMEWORK_UUID),
            pkg_vers,
            list(service_intents),
        )
        ecf_props = rsa.get_ecf_props(
            self.get_id(),
            self.get_namespace(),
            rsa.get_next_rsid(),
            rsa.get_current_time_millis(),
        )
        extra_props = rsa.get_extra_props(export_props)
        merged = rsa.merge_dicts(rsa_props, ecf_props, extra_props)
        # remove service.bundleid
        merged.pop(SERVICE_BUNDLE_ID, None)
        # remove service.scope
        merged.pop(SERVICE_SCOPE, None)
        return merged


Instruction:
Implement a function in Python 3 to
export the given service to the given set of properties.

Response:
def export_service(self, svc_ref, export_props):
        # type: (ServiceReference, Dict[str, Any]) -> EndpointDescription
        """
        Exports the given service

        :param svc_ref: Reference to the service to export
        :param export_props: Export properties
        :return: The endpoint description
        """
        ed = EndpointDescription.fromprops(export_props)
        self._export_service(
            self._get_bundle_context().get_service(svc_ref), ed
        )
        return ed


Instruction:
Write a Python 3 function for
flushing buffered data to the target

Response:
def flush(self):
        """
        Sends buffered data to the target
        """
        # Flush buffer
        content = self._buffer.getvalue()
        self._buffer = StringIO()

        if content:
            # Send message
            self._client.send_message(self._target, content, mtype="chat")


Instruction:
Implement a Python 3 function for
returning a service instance from a Prototype Service Factory and a ServiceRegistration object

Response:
def _get_from_factory(self, factory, svc_registration):
        # type: (Any, ServiceRegistration) -> Any
        """
        Returns a service instance from a Prototype Service Factory

        :param factory: The prototype service factory
        :param svc_registration: The ServiceRegistration object
        :return: The requested service instance returned by the factory
        """
        svc_ref = svc_registration.get_reference()
        try:
            # Use the existing service
            service, counter = self.__factored[svc_ref]
            counter.inc()
        except KeyError:
            # Create the service
            service = factory.get_service(self.__bundle, svc_registration)
            counter = _UsageCounter()
            counter.inc()

            # Store the counter
            self.__factored[svc_ref] = (service, counter)

        return service


Instruction:
Write a Python 3 script for
returning a service instance from a Prototype Service Factory

Response:
def _get_from_prototype(self, factory, svc_registration):
        # type: (Any, ServiceRegistration) -> Any
        """
        Returns a service instance from a Prototype Service Factory

        :param factory: The service factory
        :param svc_registration: The ServiceRegistration object
        :return: The requested service instance returned by the factory
        """
        svc_ref = svc_registration.get_reference()
        service = factory.get_service(self.__bundle, svc_registration)

        try:
            # Check if the service already exists
            services, counter = self.__factored[svc_ref]
            services.append(service)
            counter.inc()
        except KeyError:
            counter = _UsageCounter()
            counter.inc()

            # Store the counter
            self.__factored[svc_ref] = ([service], counter)

        return service


Instruction:
Can you write a function in Python 3 where it
returns the service required by the bundle.

Response:
def get_service(self, factory, svc_registration):
        # type: (Any, ServiceRegistration) -> Any
        """
        Returns the service required by the bundle. The Service Factory is
        called only when necessary while the Prototype Service Factory is
        called each time

        :param factory: The service factory
        :param svc_registration: The ServiceRegistration object
        :return: The requested service instance (created if necessary)
        """
        svc_ref = svc_registration.get_reference()
        if svc_ref.is_prototype():
            return self._get_from_prototype(factory, svc_registration)

        return self._get_from_factory(factory, svc_registration)


Instruction:
Can you write a function in Python 3 where it
releases references to the given service reference :param factory: The service factory :param svc_registration: The ServiceRegistration object :param service: Service instance (for prototype factories) :return: True if all service references to this service factory have been released

Response:
def unget_service(self, factory, svc_registration, service=None):
        # type: (Any, ServiceRegistration, Any) -> bool
        """
        Releases references to the given service reference

        :param factory: The service factory
        :param svc_registration: The ServiceRegistration object
        :param service: Service instance (for prototype factories)
        :return: True if all service references to this service factory
                 have been released
        """
        svc_ref = svc_registration.get_reference()
        try:
            _, counter = self.__factored[svc_ref]
        except KeyError:
            logging.warning(
                "Trying to release an unknown service factory: %s", svc_ref
            )
        else:
            if svc_ref.is_prototype():
                # Notify the factory to clean up this instance
                factory.unget_service_instance(
                    self.__bundle, svc_registration, service
                )

            if not counter.dec():
                # All references have been released: clean up
                del self.__factored[svc_ref]

                # Call the factory
                factory.unget_service(self.__bundle, svc_registration)

                # No more reference to this service
                return True

        # Some references are still there
        return False


Instruction:
How would you code a function in Python 3 to
remove the reference to the given service from the bundle if it was using that factory.

Response:
def cleanup_service(self, factory, svc_registration):
        # type: (Any, ServiceRegistration) -> bool
        """
        If this bundle used that factory, releases the reference; else does
        nothing

        :param factory: The service factory
        :param svc_registration: The ServiceRegistration object
        :return: True if the bundle was using the factory, else False
        """
        svc_ref = svc_registration.get_reference()
        try:
            # "service" for factories, "services" for prototypes
            services, _ = self.__factored.pop(svc_ref)
        except KeyError:
            return False
        else:
            if svc_ref.is_prototype() and services:
                for service in services:
                    try:
                        factory.unget_service_instance(
                            self.__bundle, svc_registration, service
                        )
                    except Exception:
                        # Ignore instance-level exceptions, potential errors
                        # will reappear in unget_service()
                        pass

            # Call the factory
            factory.unget_service(self.__bundle, svc_registration)

            # No more association
            svc_ref.unused_by(self.__bundle)
            return True


Instruction:
Can you implement a function in Python 3 that
indicates that this reference is not being used anymore by the given bundle. This method should only be used by the framework. :param bundle: A bundle that used this reference

Response:
def unused_by(self, bundle):
        """
        Indicates that this reference is not being used anymore by the given
        bundle.
        This method should only be used by the framework.

        :param bundle: A bundle that used this reference
        """
        if bundle is None or bundle is self.__bundle:
            # Ignore
            return

        with self.__usage_lock:
            try:
                if not self.__using_bundles[bundle].dec():
                    # This bundle has cleaner all of its usages of this
                    # reference
                    del self.__using_bundles[bundle]
            except KeyError:
                # Ignore error
                pass


Instruction:
Can you generate the documentation for the following Python 3 function
def used_by(self, bundle):
        if bundle is None or bundle is self.__bundle:
            # Ignore
            return

        with self.__usage_lock:
            self.__using_bundles.setdefault(bundle, _UsageCounter()).inc()

Response: Indicates that this reference is being used by the given bundle.


Instruction:
How would you explain what the following Python 3 function does
def set_properties(self, properties):
        if not isinstance(properties, dict):
            raise TypeError("Waiting for dictionary")

        # Keys that must not be updated
        for forbidden_key in OBJECTCLASS, SERVICE_ID:
            try:
                del properties[forbidden_key]
            except KeyError:
                pass

        to_delete = []
        for key, value in properties.items():
            if self.__properties.get(key) == value:
                # No update
                to_delete.append(key)

        for key in to_delete:
            # Remove unchanged properties
            del properties[key]

        if not properties:
            # Nothing to do
            return

        # Ensure that the service has a valid service ranking
        try:
            properties[SERVICE_RANKING] = int(properties[SERVICE_RANKING])
        except (ValueError, TypeError):
            # Bad value: ignore update
            del properties[SERVICE_RANKING]
        except KeyError:
            # Service ranking not updated: ignore
            pass

        # pylint: disable=W0212
        with self.__reference._props_lock:
            # Update the properties
            previous = self.__properties.copy()
            self.__properties.update(properties)

            if self.__reference.needs_sort_update():
                # The sort key and the registry must be updated
                self.__update_callback(self.__reference)

            # Trigger a new computation in the framework
            event = ServiceEvent(
                ServiceEvent.MODIFIED, self.__reference, previous
            )

            self.__framework._dispatcher.fire_service_event(event)

Response: Updates the properties of the service with the given dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def clear(self):
        with self.__bnd_lock:
            self.__bnd_listeners = []

        with self.__svc_lock:
            self.__svc_listeners.clear()

        with self.__fw_lock:
            self.__fw_listeners = []

Response: Clears the event dispatcher and all associated listeners


Instruction:
How would you implement a function in Python 3 that
adds a bundle listener to the list of bundle listeners.

Response:
def add_bundle_listener(self, listener):
        """
        Adds a bundle listener

        :param listener: The bundle listener to register
        :return: True if the listener has been registered, False if it was
                 already known
        :raise BundleException: An invalid listener has been given
        """
        if listener is None or not hasattr(listener, "bundle_changed"):
            raise BundleException("Invalid bundle listener given")

        with self.__bnd_lock:
            if listener in self.__bnd_listeners:
                self._logger.warning(
                    "Already known bundle listener '%s'", listener
                )
                return False

            self.__bnd_listeners.append(listener)
            return True


Instruction:
Can you tell what is the following Python 3 function doing
def add_framework_listener(self, listener):
        if listener is None or not hasattr(listener, "framework_stopping"):
            raise BundleException("Invalid framework listener given")

        with self.__fw_lock:
            if listener in self.__fw_listeners:
                self._logger.warning(
                    "Already known framework listener '%s'", listener
                )
                return False

            self.__fw_listeners.append(listener)
            return True

Response: Adds a listener that will be called back right before the framework stops.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_service_listener(
        self, bundle_context, listener, specification=None, ldap_filter=None
    ):
        """
        Registers a service listener

        :param bundle_context: The bundle_context of the service listener
        :param listener: The service listener
        :param specification: The specification that must provide the service
                              (optional, None to accept all services)
        :param ldap_filter: Filter that must match the service properties
                            (optional, None to accept all services)
        :return: True if the listener has been registered, False if it was
                 already known
        :raise BundleException: An invalid listener has been given
        """
        if listener is None or not hasattr(listener, "service_changed"):
            raise BundleException("Invalid service listener given")

        with self.__svc_lock:
            if listener in self.__listeners_data:
                self._logger.warning(
                    "Already known service listener '%s'", listener
                )
                return False

            try:
                ldap_filter = ldapfilter.get_ldap_filter(ldap_filter)
            except ValueError as ex:
                raise BundleException("Invalid service filter: {0}".format(ex))

            stored = ListenerInfo(
                bundle_context, listener, specification, ldap_filter
            )
            self.__listeners_data[listener] = stored
            self.__svc_listeners.setdefault(specification, []).append(stored)
            return True

Response: Adds a service listener to the list of services that have been added to the service.


Instruction:
Explain what the following Python 3 code does
def remove_bundle_listener(self, listener):
        with self.__bnd_lock:
            if listener not in self.__bnd_listeners:
                return False

            self.__bnd_listeners.remove(listener)
            return True

Response: Removes a bundle listener


Instruction:
Implement a Python 3 function for
removing a framework stop listener

Response:
def remove_framework_listener(self, listener):
        """
        Unregisters a framework stop listener

        :param listener: The framework listener to unregister
        :return: True if the listener has been unregistered, else False
        """
        with self.__fw_lock:
            try:
                self.__fw_listeners.remove(listener)
                return True
            except ValueError:
                return False


Instruction:
Explain what the following Python 3 code does
def remove_service_listener(self, listener):
        with self.__svc_lock:
            try:
                data = self.__listeners_data.pop(listener)
                spec_listeners = self.__svc_listeners[data.specification]
                spec_listeners.remove(data)
                if not spec_listeners:
                    del self.__svc_listeners[data.specification]
                return True
            except KeyError:
                return False

Response: Removes a service listener from the list of available service listeners.


Instruction:
Explain what the following Python 3 code does
def fire_bundle_event(self, event):
        with self.__bnd_lock:
            # Copy the list of listeners
            listeners = self.__bnd_listeners[:]

        # Call'em all
        for listener in listeners:
            try:
                listener.bundle_changed(event)
            except:
                self._logger.exception("Error calling a bundle listener")

Response: Fires a bundle event in all the listeners of the bundle


Instruction:
Write a Python 3 script to
fire the framework stopping event for the current node

Response:
def fire_framework_stopping(self):
        """
        Calls all framework listeners, telling them that the framework is
        stopping
        """
        with self.__fw_lock:
            # Copy the list of listeners
            listeners = self.__fw_listeners[:]

        for listener in listeners:
            try:
                listener.framework_stopping()
            except:
                self._logger.exception(
                    "An error occurred calling one of the "
                    "framework stop listeners"
                )


Instruction:
Here you have a function in Python 3, explain what it does
def fire_service_event(self, event):
        # Get the service properties
        properties = event.get_service_reference().get_properties()
        svc_specs = properties[OBJECTCLASS]
        previous = None
        endmatch_event = None
        svc_modified = event.get_kind() == ServiceEvent.MODIFIED

        if svc_modified:
            # Modified service event : prepare the end match event
            previous = event.get_previous_properties()
            endmatch_event = ServiceEvent(
                ServiceEvent.MODIFIED_ENDMATCH,
                event.get_service_reference(),
                previous,
            )

        with self.__svc_lock:
            # Get the listeners for this specification
            listeners = set()
            for spec in svc_specs:
                try:
                    listeners.update(self.__svc_listeners[spec])
                except KeyError:
                    pass

            # Add those which listen to any specification
            try:
                listeners.update(self.__svc_listeners[None])
            except KeyError:
                pass

        # Filter listeners with EventListenerHooks
        listeners = self._filter_with_hooks(event, listeners)

        # Get the listeners for this specification
        for data in listeners:
            # Default event to send : the one we received
            sent_event = event

            # Test if the service properties matches the filter
            ldap_filter = data.ldap_filter
            if ldap_filter is not None and not ldap_filter.matches(properties):
                # Event doesn't match listener filter...
                if (
                    svc_modified
                    and previous is not None
                    and ldap_filter.matches(previous)
                ):
                    # ... but previous properties did match
                    sent_event = endmatch_event
                else:
                    # Didn't match before either, ignore it
                    continue

            # Call'em
            try:
                data.listener.service_changed(sent_event)
            except:
                self._logger.exception("Error calling a service listener")

Response: Fires a new event in the calling thread.


Instruction:
Can you implement a function in Python 3 that
filters listeners with hooks

Response:
def _filter_with_hooks(self, svc_event, listeners):
        """
        Filters listeners with EventListenerHooks

        :param svc_event: ServiceEvent being triggered
        :param listeners: Listeners to filter
        :return: A list of listeners with hook references
        """
        svc_ref = svc_event.get_service_reference()
        # Get EventListenerHooks service refs from registry
        hook_refs = self._registry.find_service_references(
            SERVICE_EVENT_LISTENER_HOOK
        )
        # only do something if there are some hook_refs
        if hook_refs:
            # Associate bundle context to hooks
            ctx_listeners = {}
            for listener in listeners:
                context = listener.bundle_context
                ctx_listeners.setdefault(context, []).append(listener)

            # Convert the dictionary to a shrinkable one,
            # with shrinkable lists of listeners
            shrinkable_ctx_listeners = ShrinkableMap(
                {
                    context: ShrinkableList(value)
                    for context, value in ctx_listeners.items()
                }
            )

            for hook_ref in hook_refs:
                if not svc_ref == hook_ref:
                    # Get the bundle of the hook service
                    hook_bundle = hook_ref.get_bundle()
                    # lookup service from registry
                    hook_svc = self._registry.get_service(hook_bundle, hook_ref)
                    if hook_svc is not None:
                        # call event method of the hook service,
                        # pass in svc_event and shrinkable_ctx_listeners
                        # (which can be modified by hook)
                        try:
                            hook_svc.event(svc_event, shrinkable_ctx_listeners)
                        except:
                            self._logger.exception(
                                "Error calling EventListenerHook"
                            )
                        finally:
                            # Clean up the service
                            self._registry.unget_service(hook_bundle, hook_ref)

            # Convert the shrinkable_ctx_listeners back to a list of listeners
            # before returning
            ret_listeners = set()
            for bnd_listeners in shrinkable_ctx_listeners.values():
                ret_listeners.update(bnd_listeners)

            return ret_listeners

        # No hook ref
        return listeners


Instruction:
Write a Python 3 function for
clearing the registry and services.

Response:
def clear(self):
        """
        Clears the registry
        """
        with self.__svc_lock:
            self.__svc_registry.clear()
            self.__svc_factories.clear()
            self.__svc_specs.clear()
            self.__bundle_svc.clear()
            self.__bundle_imports.clear()
            self.__factory_usage.clear()
            self.__pending_services.clear()


Instruction:
Here you have a function in Python 3, explain what it does
def register(
        self, bundle, classes, properties, svc_instance, factory, prototype
    ):
        """
        Registers a service.

        :param bundle: The bundle that registers the service
        :param classes: The classes implemented by the service
        :param properties: The properties associated to the service
        :param svc_instance: The instance of the service
        :param factory: If True, the given service is a service factory
        :param prototype: If True, the given service is a prototype service
                          factory (the factory argument is considered True)
        :return: The ServiceRegistration object
        """
        with self.__svc_lock:
            # Prepare properties
            service_id = self.__next_service_id
            self.__next_service_id += 1
            properties[OBJECTCLASS] = classes
            properties[SERVICE_ID] = service_id
            properties[SERVICE_BUNDLEID] = bundle.get_bundle_id()

            # Compute service scope
            if prototype:
                properties[SERVICE_SCOPE] = SCOPE_PROTOTYPE
            elif factory:
                properties[SERVICE_SCOPE] = SCOPE_BUNDLE
            else:
                properties[SERVICE_SCOPE] = SCOPE_SINGLETON

            # Force to have a valid service ranking
            try:
                properties[SERVICE_RANKING] = int(properties[SERVICE_RANKING])
            except (KeyError, ValueError, TypeError):
                properties[SERVICE_RANKING] = 0

            # Make the service reference
            svc_ref = ServiceReference(bundle, properties)

            # Make the service registration
            svc_registration = ServiceRegistration(
                self.__framework, svc_ref, properties, self.__sort_registry
            )

            # Store service information
            if prototype or factory:
                self.__svc_factories[svc_ref] = (svc_instance, svc_registration)

            # Also store factories, as they must appear like any other service
            self.__svc_registry[svc_ref] = svc_instance

            for spec in classes:
                spec_refs = self.__svc_specs.setdefault(spec, [])
                bisect.insort_left(spec_refs, svc_ref)

            # Reverse map, to ease bundle/service association
            bundle_services = self.__bundle_svc.setdefault(bundle, set())
            bundle_services.add(svc_ref)
            return svc_registration

Response: Registers a new service in the cache.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __sort_registry(self, svc_ref):
        # type: (ServiceReference) -> None
        """
        Sorts the registry, after the update of the sort key of given service
        reference

        :param svc_ref: A service reference with a modified sort key
        """
        with self.__svc_lock:
            if svc_ref not in self.__svc_registry:
                raise BundleException("Unknown service: {0}".format(svc_ref))

            # Remove current references
            for spec in svc_ref.get_property(OBJECTCLASS):
                # Use bisect to remove the reference (faster)
                spec_refs = self.__svc_specs[spec]
                idx = bisect.bisect_left(spec_refs, svc_ref)
                del spec_refs[idx]

            # ... use the new sort key
            svc_ref.update_sort_key()

            for spec in svc_ref.get_property(OBJECTCLASS):
                # ... and insert it again
                spec_refs = self.__svc_specs[spec]
                bisect.insort_left(spec_refs, svc_ref)

Response: Sorts the registry after the update of the sort key of the given service.


Instruction:
Write a Python 3 script for
hiding the services of the given bundle.

Response:
def hide_bundle_services(self, bundle):
        """
        Hides the services of the given bundle (removes them from lists, but
        lets them be unregistered)

        :param bundle: The bundle providing services
        :return: The references of the hidden services
        """
        with self.__svc_lock:
            try:
                svc_refs = self.__bundle_svc.pop(bundle)
            except KeyError:
                # Nothing to do
                return set()
            else:
                # Clean the registry
                specs = set()
                for svc_ref in svc_refs:
                    if svc_ref.is_factory():
                        continue

                    # Remove direct references
                    self.__pending_services[svc_ref] = self.__svc_registry.pop(
                        svc_ref
                    )
                    specs.update(svc_ref.get_property(OBJECTCLASS))

                    # Clean the specifications cache
                    for spec in svc_ref.get_property(OBJECTCLASS):
                        spec_services = self.__svc_specs[spec]
                        # Use bisect to remove the reference (faster)
                        idx = bisect.bisect_left(spec_services, svc_ref)
                        del spec_services[idx]
                        if not spec_services:
                            del self.__svc_specs[spec]

            return svc_refs


Instruction:
Can you write a function in Python 3 where it
finds all services references matching the given filter.

Response:
def find_service_references(
        self, clazz=None, ldap_filter=None, only_one=False
    ):
        """
        Finds all services references matching the given filter.

        :param clazz: Class implemented by the service
        :param ldap_filter: Service filter
        :param only_one: Return the first matching service reference only
        :return: A list of found references, or None
        :raise BundleException: An error occurred looking for service
                                references
        """
        with self.__svc_lock:
            if clazz is None and ldap_filter is None:
                # Return a sorted copy of the keys list
                # Do not return None, as the whole content was required
                return sorted(self.__svc_registry.keys())

            if hasattr(clazz, "__name__"):
                # Escape the type name
                clazz = ldapfilter.escape_LDAP(clazz.__name__)
            elif is_string(clazz):
                # Escape the class name
                clazz = ldapfilter.escape_LDAP(clazz)

            if clazz is None:
                # Directly use the given filter
                refs_set = sorted(self.__svc_registry.keys())
            else:
                try:
                    # Only for references with the given specification
                    refs_set = iter(self.__svc_specs[clazz])
                except KeyError:
                    # No matching specification
                    return None

            # Parse the filter
            try:
                new_filter = ldapfilter.get_ldap_filter(ldap_filter)
            except ValueError as ex:
                raise BundleException(ex)

            if new_filter is not None:
                # Prepare a generator, as we might not need a complete
                # walk-through
                refs_set = (
                    ref
                    for ref in refs_set
                    if new_filter.matches(ref.get_properties())
                )

            if only_one:
                # Return the first element in the list/generator
                try:
                    return [next(refs_set)]
                except StopIteration:
                    # No match
                    return None

            # Get all the matching references
            return list(refs_set) or None


Instruction:
How would you code a function in Python 3 to
return this bundle s ServiceReference list for all services it is using or returns None if this bundle is not using any services.

Response:
def get_bundle_imported_services(self, bundle):
        """
        Returns this bundle's ServiceReference list for all services it is
        using or returns None if this bundle is not using any services.
        A bundle is considered to be using a service if its use count for that
        service is greater than zero.

        The list is valid at the time of the call to this method, however, as
        the Framework is a very dynamic environment, services can be modified
        or unregistered at any time.

        :param bundle: The bundle to look into
        :return: The references of the services used by this bundle
        """
        with self.__svc_lock:
            return sorted(self.__bundle_imports.get(bundle, []))


Instruction:
Write a Python 3 function that can
return the list of services registered by the given bundle. Returns None if the bundle didn t register any services.

Response:
def get_bundle_registered_services(self, bundle):
        # type: (Any) -> List[ServiceReference]
        """
        Retrieves the services registered by the given bundle. Returns None
        if the bundle didn't register any service.

        :param bundle: The bundle to look into
        :return: The references to the services registered by the bundle
        """
        with self.__svc_lock:
            return sorted(self.__bundle_svc.get(bundle, []))


Instruction:
Make a summary of the following Python 3 code
def get_service(self, bundle, reference):
        # type: (Any, ServiceReference) -> Any
        """
        Retrieves the service corresponding to the given reference

        :param bundle: The bundle requiring the service
        :param reference: A service reference
        :return: The requested service
        :raise BundleException: The service could not be found
        """
        with self.__svc_lock:
            if reference.is_factory():
                return self.__get_service_from_factory(bundle, reference)

            # Be sure to have the instance
            try:
                service = self.__svc_registry[reference]

                # Indicate the dependency
                imports = self.__bundle_imports.setdefault(bundle, {})
                imports.setdefault(reference, _UsageCounter()).inc()
                reference.used_by(bundle)
                return service
            except KeyError:
                # Not found
                raise BundleException(
                    "Service not found (reference: {0})".format(reference)
                )

Response: Returns the service corresponding to the given service.


Instruction:
Explain what the following Python 3 code does
def __get_service_from_factory(self, bundle, reference):
        # type: (Any, ServiceReference) -> Any
        """
        Returns a service instance from a service factory or a prototype
        service factory

        :param bundle: The bundle requiring the service
        :param reference: A reference pointing to a factory
        :return: The requested service
        :raise BundleException: The service could not be found
        """
        try:
            factory, svc_reg = self.__svc_factories[reference]

            # Indicate the dependency
            imports = self.__bundle_imports.setdefault(bundle, {})
            if reference not in imports:
                # New reference usage: store a single usage
                # The Factory counter will handle the rest
                usage_counter = _UsageCounter()
                usage_counter.inc()
                imports[reference] = usage_counter
                reference.used_by(bundle)

            # Check the per-bundle usage counter
            factory_counter = self.__factory_usage.setdefault(
                bundle, _FactoryCounter(bundle)
            )
            return factory_counter.get_service(factory, svc_reg)
        except KeyError:
            # Not found
            raise BundleException(
                "Service not found (reference: {0})".format(reference)
            )

Response: Returns a service instance from a service factory or a prototype service factory


Instruction:
Make a summary of the following Python 3 code
def unget_used_services(self, bundle):
        # Pop used references
        try:
            imported_refs = list(self.__bundle_imports.pop(bundle))
        except KeyError:
            # Nothing to do
            return

        for svc_ref in imported_refs:
            # Remove usage marker
            svc_ref.unused_by(bundle)

            if svc_ref.is_prototype():
                # Get factory information and clean up the service from the
                # factory counter
                factory_counter = self.__factory_usage.pop(bundle)
                factory, svc_reg = self.__svc_factories[svc_ref]
                factory_counter.cleanup_service(factory, svc_reg)
            elif svc_ref.is_factory():
                # Factory service, release it the standard way
                self.__unget_service_from_factory(bundle, svc_ref)

        # Clean up local structures
        try:
            del self.__factory_usage[bundle]
        except KeyError:
            pass

        try:
            self.__bundle_imports.pop(bundle).clear()
        except KeyError:
            pass

Response: Removes all service usages of the given bundle.


Instruction:
Implement a function in Python 3 to
remove the usage of a service by a bundle.

Response:
def unget_service(self, bundle, reference, service=None):
        # type: (Any, ServiceReference, Any) -> bool
        """
        Removes the usage of a service by a bundle

        :param bundle: The bundle that used the service
        :param reference: A service reference
        :param service: Service instance (for Prototype Service Factories)
        :return: True if the bundle usage has been removed
        """
        with self.__svc_lock:
            if reference.is_prototype():
                return self.__unget_service_from_factory(
                    bundle, reference, service
                )
            elif reference.is_factory():
                return self.__unget_service_from_factory(bundle, reference)

            try:
                # Remove the service reference from the bundle
                imports = self.__bundle_imports[bundle]
                if not imports[reference].dec():
                    # No more reference to it
                    del imports[reference]
            except KeyError:
                # Unknown reference
                return False
            else:
                # Clean up
                if not imports:
                    del self.__bundle_imports[bundle]

                # Update the service reference
                reference.unused_by(bundle)
                return True


Instruction:
Here you have a function in Python 3, explain what it does
def __unget_service_from_factory(self, bundle, reference, service=None):
        # type: (Any, ServiceReference, Any) -> bool
        """
        Removes the usage of a a service factory or a prototype
        service factory by a bundle

        :param bundle: The bundle that used the service
        :param reference: A service reference
        :param service: Service instance (for prototype factories)
        :return: True if the bundle usage has been removed
        """
        try:
            factory, svc_reg = self.__svc_factories[reference]
        except KeyError:
            # Unknown service reference
            return False

        # Check the per-bundle usage counter
        try:
            counter = self.__factory_usage[bundle]
        except KeyError:
            # Unknown reference to a factory
            return False
        else:
            if counter.unget_service(factory, svc_reg, service):
                try:
                    # No more dependency
                    reference.unused_by(bundle)

                    # All references have been taken away: clean up
                    if not self.__factory_usage[bundle].is_used():
                        del self.__factory_usage[bundle]

                    # Remove the service reference from the bundle
                    imports = self.__bundle_imports[bundle]
                    del imports[reference]
                except KeyError:
                    # Unknown reference
                    return False
                else:
                    # Clean up
                    if not imports:
                        del self.__bundle_imports[bundle]

        return True

Response: Removes the usage of a service from a service factory or prototype factory by a bundle.


Instruction:
Implement a function in Python 3 to
convert the given value according to the given type of the value.

Response:
def _convert_value(vtype, value):
        """
        Converts the given value string according to the given type

        :param vtype: Type of the value
        :param value: String form of the value
        :return: The converted value
        :raise ValueError: Conversion failed
        """
        # Normalize value
        value = value.strip()

        if vtype == TYPE_STRING:
            # Nothing to do
            return value
        elif vtype in TYPES_INT:
            return int(value)
        elif vtype in TYPES_FLOAT:
            return float(value)
        elif vtype in TYPES_BOOLEAN:
            # Compare lower-case value
            return value.lower() not in ("false", "0")
        elif vtype in TYPES_CHAR:
            return value[0]

        # No luck
        raise ValueError("Unknown value type: {0}".format(vtype))


Instruction:
Can you write a function in Python 3 where it
adds the given container to the given property node.

Response:
def _add_container(props_node, tag, container):
        """
        Walks through the given container and fills the node

        :param props_node: A property node
        :param tag: Name of the container tag
        :param container: The container
        """
        values_node = ElementTree.SubElement(props_node, tag)
        for value in container:
            value_node = ElementTree.SubElement(values_node, TAG_VALUE)
            value_node.text = str(value)


Instruction:
Can you implement a function in Python 3 that
returns the type associated to the given name or value.

Response:
def _get_type(name, value):
        """
        Returns the type associated to the given name or value

        :param name: Property name
        :param value: Property value
        :return: A value type name
        """
        # Types forced for known keys
        if name in TYPED_BOOL:
            return TYPE_BOOLEAN

        elif name in TYPED_LONG:
            return TYPE_LONG

        elif name in TYPED_STRING:
            return TYPE_STRING

        # We need to analyze the content of value
        if isinstance(value, (tuple, list, set)):
            # Get the type from container content
            try:
                # Extract value
                value = next(iter(value))

            except StopIteration:
                # Empty list, can't check
                return TYPE_STRING

        # Single value
        if isinstance(value, int):
            # Integer
            return TYPE_LONG

        elif isinstance(value, float):
            # Float
            return TYPE_DOUBLE

        elif isinstance(value, type(ElementTree.Element(None))):
            # XML
            return XML_VALUE

        # Default: String
        return TYPE_STRING


Instruction:
How would you explain what the following Python 3 function does
def connect(
        self, host, port=5222, reattempt=False, use_tls=True, use_ssl=False
    ):
        # pylint: disable=W0221
        """
        Connects to the server.

        By default, uses an un-encrypted connection, as it won't connect to an
        OpenFire server otherwise

        :param host: Server host name
        :param port: Server port (default: 5222)
        :param reattempt: If True, tries to connect to the server until it
                         succeeds
        :param use_tls: Use STARTTLS
        :param use_ssl: Server connection is encrypted
        :return: True if connection succeeded
        """
        if not self._expected_server_name:
            # We seem to connect the server anonymously, so SleekXMPP
            # couldn't find the server host name from the JID
            # => give it the given server host name as the expected one
            self._expected_server_name = host

        # Try to connect
        if super(BasicBot, self).connect(
            (host, port), reattempt, use_tls, use_ssl
        ):
            # On success, start the processing thread
            self.process(threaded=True)
            return True

        return False

Response: Connect to the server.


Instruction:
Make a summary of the following Python 3 code
def on_session_start(self, data):
        # pylint: disable=W0613
        """
        XMPP session started
        """
        # Send initial presence
        self.send_presence(ppriority=self._initial_priority)

        # Request roster
        self.get_roster()

Response: Called when the XMPP session is started.


Instruction:
Can you generate the documentation for the following Python 3 function
def on_invite(self, data):
        if not self._nick:
            self._nick = self.boundjid.user

        # Join the room
        self.plugin["xep_0045"].joinMUC(data["from"], self._nick)

Response: Invite from the MUC.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def iter_services(self, feature=None):
        # Get the list of root services
        items = self["xep_0030"].get_items(
            jid=self.boundjid.domain,
            ifrom=self.boundjid.full,
            block=True,
            timeout=10,
        )

        for item in items["disco_items"]["items"]:
            # Each item is a 3-tuple. The service JID is the first entry
            if not feature:
                # No filter
                yield item[0]
            else:
                # Get service details
                info = self["xep_0030"].get_info(
                    jid=item[0],
                    ifrom=self.boundjid.full,
                    block=True,
                    timeout=10,
                )
                if feature in info["disco_info"]["features"]:
                    # The service provides the required feature
                    yield item[0]

Response: Iterate over the root - level services on the server which provides the requested feature.


Instruction:
Make a summary of the following Python 3 code
def _find_assignment(arg_token):
    idx = arg_token.find("=")
    while idx != -1:
        if idx != 0 and arg_token[idx - 1] != "\\":
            # No escape character
            return idx

        idx = arg_token.find("=", idx + 1)

    # No assignment found
    return -1

Response: Find the first non - escaped assignment in the given argument token.


Instruction:
How would you implement a function in Python 3 that
converts the given list of arguments into a list of kwargs and a

Response:
def _make_args(args_list, session, fw_props):
    """
    Converts the given list of arguments into a list (args) and a
    dictionary (kwargs).
    All arguments with an assignment are put into kwargs, others in args.

    :param args_list: The list of arguments to be treated
    :param session: The current shell session
    :return: The (arg_token, kwargs) tuple.
    """
    args = []
    kwargs = {}

    for arg_token in args_list:
        idx = _find_assignment(arg_token)
        if idx != -1:
            # Assignment
            key = arg_token[:idx]
            value = arg_token[idx + 1 :]
            kwargs[key] = value
        else:
            # Direct argument
            args.append(arg_token)

    # Prepare the dictionary of variables
    variables = collections.defaultdict(str)
    variables.update(fw_props)
    variables.update(session.variables)

    # Replace variables
    args = [_ArgTemplate(arg).safe_substitute(variables) for arg in args]
    kwargs = {
        key: _ArgTemplate(value).safe_substitute(variables)
        for key, value in kwargs.items()
    }
    return args, kwargs


Instruction:
Can you tell what is the following Python 3 function doing
def _split_ns_command(cmd_token):
    namespace = None
    cmd_split = cmd_token.split(".", 1)
    if len(cmd_split) == 1:
        # No name space given
        command = cmd_split[0]
    else:
        # Got a name space and a command
        namespace = cmd_split[0]
        command = cmd_split[1]

    if not namespace:
        # No name space given: given an empty one
        namespace = ""

    # Use lower case values only
    return namespace.lower(), command.lower()

Response: Splits the command name of the given command token into a namespace and command tuple.


Instruction:
Here you have a function in Python 3, explain what it does
def register_command(self, namespace, command, method):
        if method is None:
            self._logger.error("No method given for %s.%s", namespace, command)
            return False

        # Store everything in lower case
        namespace = (namespace or "").strip().lower()
        command = (command or "").strip().lower()

        if not namespace:
            namespace = DEFAULT_NAMESPACE

        if not command:
            self._logger.error("No command name given")
            return False

        if namespace not in self._commands:
            space = self._commands[namespace] = {}
        else:
            space = self._commands[namespace]

        if command in space:
            self._logger.error(
                "Command already registered: %s.%s", namespace, command
            )
            return False

        space[command] = method
        return True

Response: Registers the given command to the shell.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_command_completers(self, namespace, command):
        # type: (str, str) -> CompletionInfo
        """
        Returns the completer method associated to the given command, or None

        :param namespace: The command name space.
        :param command: The shell name of the command
        :return: A CompletionConfiguration object
        :raise KeyError: Unknown command or name space
        """
        # Find the method (can raise a KeyError)
        method = self._commands[namespace][command]

        # Return the completer, if any
        return getattr(method, ATTR_COMPLETERS, None)

Response: Returns the completer method associated to the given command.


Instruction:
Make a summary of the following Python 3 code
def unregister(self, namespace, command=None):
        if not namespace:
            namespace = DEFAULT_NAMESPACE

        namespace = namespace.strip().lower()
        if namespace not in self._commands:
            self._logger.warning("Unknown name space: %s", namespace)
            return False

        if command is not None:
            # Remove the command
            command = command.strip().lower()
            if command not in self._commands[namespace]:
                self._logger.warning(
                    "Unknown command: %s.%s", namespace, command
                )
                return False

            del self._commands[namespace][command]

            # Remove the name space if necessary
            if not self._commands[namespace]:
                del self._commands[namespace]
        else:
            # Remove the whole name space
            del self._commands[namespace]

        return True

Response: Unregisters the given command from the given name space.


Instruction:
Explain what the following Python 3 code does
def __find_command_ns(self, command):
        # Look for the spaces where the command name appears
        namespaces = []
        for namespace, commands in self._commands.items():
            if command in commands:
                namespaces.append(namespace)

        # Sort name spaces
        namespaces.sort()

        # Default name space must always come first
        try:
            namespaces.remove(DEFAULT_NAMESPACE)
            namespaces.insert(0, DEFAULT_NAMESPACE)
        except ValueError:
            # Default name space wasn't present
            pass

        return namespaces

Response: Returns the name spaces where the given command name appears.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_namespaces(self):
        namespaces = list(self._commands.keys())
        namespaces.remove(DEFAULT_NAMESPACE)
        namespaces.sort()
        return namespaces

Response: Returns the list of known name spaces without the default one


Instruction:
Write a Python 3 script to
retrieve the commands of the given name space.

Response:
def get_commands(self, namespace):
        """
        Retrieves the commands of the given name space. If *namespace* is None
        or empty, it retrieves the commands of the default name space

        :param namespace: The commands name space
        :return: A list of commands names
        """
        if not namespace:
            # Default name space:
            namespace = DEFAULT_NAMESPACE

        try:
            namespace.strip().lower()
            commands = list(self._commands[namespace].keys())
            commands.sort()
            return commands
        except KeyError:
            # Unknown name space
            return []


Instruction:
Explain what the following Python 3 code does
def get_ns_commands(self, cmd_name):
        namespace, command = _split_ns_command(cmd_name)
        if not namespace:
            # Name space not given, look for the commands
            spaces = self.__find_command_ns(command)
            if not spaces:
                # Unknown command
                raise ValueError("Unknown command {0}".format(command))
            else:
                # Return a sorted list of tuples
                return sorted((namespace, command) for namespace in spaces)

        # Single match
        return [(namespace, command)]

Response: Returns the possible name spaces and commands associated to the given command name.


Instruction:
Here you have a function in Python 3, explain what it does
def get_ns_command(self, cmd_name):
        namespace, command = _split_ns_command(cmd_name)
        if not namespace:
            # Name space not given, look for the command
            spaces = self.__find_command_ns(command)
            if not spaces:
                # Unknown command
                raise ValueError("Unknown command {0}".format(command))
            elif len(spaces) > 1:
                # Multiple possibilities
                if spaces[0] == DEFAULT_NAMESPACE:
                    # Default name space has priority
                    namespace = DEFAULT_NAMESPACE

                else:
                    # Ambiguous name
                    raise ValueError(
                        "Multiple name spaces for command '{0}': {1}".format(
                            command, ", ".join(sorted(spaces))
                        )
                    )
            else:
                # Use the found name space
                namespace = spaces[0]

        # Command found
        return namespace, command

Response: Returns the name space and command associated to the given command name.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def execute(self, cmdline, session=None):
        if session is None:
            # Default session
            session = beans.ShellSession(
                beans.IOHandler(sys.stdin, sys.stdout), {}
            )

        assert isinstance(session, beans.ShellSession)

        # Split the command line
        if not cmdline:
            return False

        # Convert the line into a string
        cmdline = to_str(cmdline)

        try:
            line_split = shlex.split(cmdline, True, True)
        except ValueError as ex:
            session.write_line("Error reading line: {0}", ex)
            return False

        if not line_split:
            return False

        try:
            # Extract command information
            namespace, command = self.get_ns_command(line_split[0])
        except ValueError as ex:
            # Unknown command
            session.write_line(str(ex))
            return False

        # Get the content of the name space
        space = self._commands.get(namespace, None)
        if not space:
            session.write_line("Unknown name space {0}", namespace)
            return False

        # Get the method object
        method = space.get(command, None)
        if method is None:
            session.write_line("Unknown command: {0}.{1}", namespace, command)
            return False

        # Make arguments and keyword arguments
        args, kwargs = _make_args(
            line_split[1:], session, self._framework.get_properties()
        )
        try:
            # Execute it
            result = method(session, *args, **kwargs)

            # Store the result as $?
            if result is not None:
                session.set(beans.RESULT_VAR_NAME, result)

            # 0, None are considered as success, so don't use not nor bool
            return result is not False
        except TypeError as ex:
            # Invalid arguments...
            self._logger.error(
                "Error calling %s.%s: %s", namespace, command, ex
            )
            session.write_line("Invalid method call: {0}", ex)
            self.__print_namespace_help(session, namespace, command)
            return False
        except Exception as ex:
            # Error
            self._logger.exception(
                "Error calling %s.%s: %s", namespace, command, ex
            )
            session.write_line("{0}: {1}", type(ex).__name__, str(ex))
            return False
        finally:
            # Try to flush in any case
            try:
                session.flush()
            except IOError:
                pass

Response: Executes the given command line and stores the result in the current shell session.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __extract_help(method):
        if method is None:
            return "(No associated method)"

        # Get the arguments
        arg_spec = get_method_arguments(method)

        # Ignore the session argument
        start_arg = 1

        # Compute the number of arguments with default value
        if arg_spec.defaults is not None:
            nb_optional = len(arg_spec.defaults)

            # Let the mandatory arguments as they are
            args = [
                "<{0}>".format(arg)
                for arg in arg_spec.args[start_arg:-nb_optional]
            ]

            # Add the other arguments
            for name, value in zip(
                arg_spec.args[-nb_optional:], arg_spec.defaults[-nb_optional:]
            ):
                if value is not None:
                    args.append("[<{0}>={1}]".format(name, value))
                else:
                    args.append("[<{0}>]".format(name))
        else:
            # All arguments are mandatory
            args = ["<{0}>".format(arg) for arg in arg_spec.args[start_arg:]]

        # Extra arguments
        if arg_spec.keywords:
            args.append("[<property=value> ...]")

        if arg_spec.varargs:
            args.append("[<{0} ...>]".format(arg_spec.varargs))

        # Get the documentation string
        doc = inspect.getdoc(method) or "(Documentation missing)"
        return " ".join(args), " ".join(doc.split())

Response: Extracts the help string for the given method


Instruction:
Can you tell what is the following Python 3 function doing
def __print_command_help(self, session, namespace, cmd_name):
        # Extract documentation
        args, doc = self.__extract_help(self._commands[namespace][cmd_name])

        # Print the command name, and its arguments
        if args:
            session.write_line("- {0} {1}", cmd_name, args)
        else:
            session.write_line("- {0}", cmd_name)

        # Print the documentation line
        session.write_line("\t\t{0}", doc)

Response: Prints the documentation of the given command


Instruction:
Given the following Python 3 function, write the documentation
def __print_namespace_help(self, session, namespace, cmd_name=None):
        session.write_line("=== Name space '{0}' ===", namespace)

        # Get all commands in this name space
        if cmd_name is None:
            names = [command for command in self._commands[namespace]]
            names.sort()
        else:
            names = [cmd_name]

        first_cmd = True
        for command in names:
            if not first_cmd:
                # Print an empty line
                session.write_line("\n")

            self.__print_command_help(session, namespace, command)
            first_cmd = False

Response: Prints the documentation of all the commands in the given name space and all the commands in the given name space.


Instruction:
Can you generate the documentation for the following Python 3 function
def print_help(self, session, command=None):
        if command:
            # Single command mode
            if command in self._commands:
                # Argument is a name space
                self.__print_namespace_help(session, command)
                was_namespace = True
            else:
                was_namespace = False

            # Also print the name of matching commands
            try:
                # Extract command name space and name
                possibilities = self.get_ns_commands(command)
            except ValueError as ex:
                # Unknown command
                if not was_namespace:
                    # ... and no name space were matching either -> error
                    session.write_line(str(ex))
                    return False
            else:
                # Print the help of the found command
                if was_namespace:
                    # Give some space
                    session.write_line("\n\n")

                for namespace, cmd_name in possibilities:
                    self.__print_namespace_help(session, namespace, cmd_name)
        else:
            # Get all name spaces
            namespaces = list(self._commands.keys())
            namespaces.remove(DEFAULT_NAMESPACE)
            namespaces.sort()
            namespaces.insert(0, DEFAULT_NAMESPACE)

            first_ns = True
            for namespace in namespaces:
                if not first_ns:
                    # Add empty lines
                    session.write_line("\n\n")

                # Print the help of all commands
                self.__print_namespace_help(session, namespace)
                first_ns = False

        return None

Response: Prints the available methods and their documentation or the documentation of the given command.


Instruction:
Can you implement a function in Python 3 that
sets the given variables or prints the current ones.

Response:
def var_set(session, **kwargs):
        """
        Sets the given variables or prints the current ones. "set answer=42"
        """
        if not kwargs:
            for name, value in session.variables.items():
                session.write_line("{0}={1}".format(name, value))
        else:
            for name, value in kwargs.items():
                name = name.strip()
                session.set(name, value)
                session.write_line("{0}={1}", name, value)


Instruction:
Can you generate the documentation for the following Python 3 function
def var_unset(session, name):
        name = name.strip()
        try:
            session.unset(name)
        except KeyError:
            session.write_line("Unknown variable: {0}", name)
            return False
        else:
            session.write_line("Variable {0} unset.", name)

        return None

Response: Unsets the given variable in the given session.


Instruction:
Create a Python 3 function to
run the given script file

Response:
def run_file(self, session, filename):
        """
        Runs the given "script" file
        """
        try:
            with open(filename, "r") as filep:
                for lineno, line in enumerate(filep):
                    line = line.strip()
                    if not line or line.startswith("#"):
                        # Ignore comments and empty lines
                        continue

                    # Print out the executed line
                    session.write_line("[{0:02d}] >> {1}", lineno, line)

                    # Execute the line
                    if not self.execute(line, session):
                        session.write_line(
                            "Command at line {0} failed. Abandon.", lineno + 1
                        )
                        return False

                session.write_line("Script execution succeeded")
        except IOError as ex:
            session.write_line("Error reading file {0}: {1}", filename, ex)
            return False

        return None


Instruction:
How would you explain what the following Python 3 function does
def add_properties(self, properties):
        if isinstance(properties, dict):
            self._properties.update(properties)

Response: Updates the framework properties dictionary with the new properties.


Instruction:
Can you tell what is the following Python 3 function doing
def add_environment(self, environ):
        if isinstance(environ, dict):
            self._environment.update(environ)

Response: Updates the environment dictionary with the given one.


Instruction:
Implement a function in Python 3 to
add new paths to the Python path.

Response:
def add_paths(self, paths):
        """
        Adds entries to the Python path.

        The given paths are normalized before being added to the left of the
        list

        :param paths: New paths to add
        """
        if paths:
            # Use new paths in priority
            self._paths = list(paths) + self._paths


Instruction:
How would you code a function in Python 3 to
add a list of components to instantiate

Response:
def add_components(self, components):
        """
        Adds a list of components to instantiate

        :param components: The description of components
        :raise KeyError: Missing component configuration
        """
        if components:
            for component in components:
                self._components[component["name"]] = (
                    component["factory"],
                    component.get("properties", {}),
                )


Instruction:
Write a Python 3 function that can
normalize the environment variables paths and filters the lists of bundles to install and start.

Response:
def normalize(self):
        """
        Normalizes environment variables, paths and filters the lists of
        bundles to install and start.

        After this call, the environment variables of this process will have
        been updated.
        """
        # Add environment variables
        os.environ.update(self._environment)

        # Normalize paths and avoid duplicates
        self._paths = remove_duplicates(
            os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
            for path in self._paths
            if os.path.exists(path)
        )

        # Normalize the lists of bundles
        self._bundles = remove_duplicates(self._bundles)


Instruction:
Make a summary of the following Python 3 code
def find_default(self, filename):
        for path in self.DEFAULT_PATH:
            # Normalize path
            path = os.path.expanduser(os.path.expandvars(path))
            fullname = os.path.realpath(os.path.join(path, filename))

            if os.path.exists(fullname) and os.path.isfile(fullname):
                yield fullname

Response: A generator which looks in common folders for the default configuration file.


Instruction:
Here you have a function in Python 3, explain what it does
def load(self, filename=None):
        if not filename:
            for name in self.find_default(".pelix.conf"):
                self.load(name)
        else:
            with open(filename, "r") as filep:
                self.__parse(json.load(filep))

Response: Loads the given file and adds its content to the current state.


Instruction:
Explain what the following Python 3 code does
def __parse(self, configuration):
        for entry in (
            "properties",
            "environment",
            "paths",
            "bundles",
            "components",
        ):
            # Check if current values must be reset
            reset_key = "reset_{0}".format(entry)

            # Compute the name of the method
            call_name = "add" if not configuration.get(reset_key) else "set"
            method = getattr(self.__state, "{0}_{1}".format(call_name, entry))

            # Update configuration
            method(configuration.get(entry))

Response: Parses the given configuration dictionary into a dictionary of values.


Instruction:
Can you tell what is the following Python 3 function doing
def normalize(self):
        # Normalize configuration
        self.__state.normalize()

        # Update sys.path, avoiding duplicates
        whole_path = list(self.__state.paths)
        whole_path.extend(sys.path)

        # Ensure the working directory as first search path
        sys.path = ["."]
        for path in whole_path:
            if path not in sys.path:
                sys.path.append(path)

Response: Normalizes the environment variables and the Python path.


Instruction:
Make a summary of the following Python 3 code
def unescape_string_literal(literal, encoding):
    r'''Unescape a string or unicode literal.

    Examples:

    >>> u = u'\u4e16\u754c\u4f60\u597d' # 世界你好
    >>> print unescape_string_literal(repr(u), 'utf-8')
    u'世界你好'

    >>> print unescape_string_literal(repr(u.encode('utf-8')), 'utf-8')
    '世界你好'

    >>> print unescape_string_literal(repr(u.encode('big5')), 'utf-8')
    '\xa5@\xac\xc9\xa7A\xa6n'
    '''

    if encoding is None:
        encoding = getfilesystemencoding()

    if literal[0] in 'uU':

        return literalize_string(
            literal[2:-1].decode('unicode-escape').encode(encoding),
            is_unicode=True
        )

    else:

        content = literal[1:-1].decode('string-escape')

        # keep it escaped if the encoding doesn't work on it
        try:
            content.decode(encoding)
        except UnicodeDecodeError:
            return literal

    return literalize_string(content)

Response: r Unescape a string or unicode literal.


Instruction:
Given the following Python 3 function, write the documentation
def unescape(b, encoding):
    '''Unescape all string and unicode literals in bytes.'''
    return string_literal_re.sub(
        lambda m: unescape_string_literal(m.group(), encoding),
        b
    )

Response: Unescape all string and unicode literals in bytes.


Instruction:
Here you have a function in Python 3, explain what it does
def make_unistream(stream):
    '''Make a stream which unescapes string literals before writes out.'''

    unistream = lambda: 'I am an unistream!'

    # make unistream look like the stream
    for attr_name in dir(stream):
        if not attr_name.startswith('_'):
            setattr(unistream, attr_name, getattr(stream, attr_name))

    # modify the write method to unescape the output
    unistream.write = lambda b: stream.write(
        # TODO: the to_bytes makes the behavior different, should we care?
        unescape(to_bytes(b, unistream.encoding), unistream.encoding)
    )

    return unistream

Response: Make a stream which unescapes string literals before writes out.


Instruction:
Create a Python 3 function for
formatting the given stack frame to show its position in the code and its context.

Response:
def format_frame_info(frame):
    """
    Formats the given stack frame to show its position in the code and
    part of its context

    :param frame: A stack frame
    """
    # Same as in traceback.extract_stack
    line_no = frame.f_lineno
    code = frame.f_code
    filename = code.co_filename
    method_name = code.co_name
    linecache.checkcache(filename)

    try:
        # Try to get the type of the calling object
        instance = frame.f_locals["self"]
        method_name = "{0}::{1}".format(type(instance).__name__, method_name)
    except KeyError:
        # Not called from a bound method
        pass

    # File & line
    output_lines = [
        '  File "{0}", line {1}, in {2}'.format(filename, line_no, method_name)
    ]

    # Arguments
    if frame.f_locals:
        # Pypy keeps f_locals as an empty dictionary
        arg_info = inspect.getargvalues(frame)
        for name in arg_info.args:
            try:
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )
            except TypeError:
                # Happens in dict/list-comprehensions in Python 2.x
                name = name[0]
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )

        if arg_info.varargs:
            output_lines.append(
                "    - *{0:s} = {1}".format(
                    arg_info.varargs, frame.f_locals[arg_info.varargs]
                )
            )

        if arg_info.keywords:
            output_lines.append(
                "    - **{0:s} = {1}".format(
                    arg_info.keywords, frame.f_locals[arg_info.keywords]
                )
            )

    # Line block
    lines = _extract_lines(filename, frame.f_globals, line_no, 3)
    if lines:
        output_lines.append("")
        prefix = "      "
        output_lines.append(
            "{0}{1}".format(prefix, "\n{0}".format(prefix).join(lines))
        )
    return "\n".join(output_lines)


Instruction:
Explain what the following Python 3 code does
def _extract_lines(filename, f_globals, line_no, around):
    current_line = linecache.getline(filename, line_no, f_globals)
    if not current_line:
        # No data on this line
        return ""

    lines = []
    # Add some lines before
    for pre_line_no in range(line_no - around, line_no):
        pre_line = linecache.getline(filename, pre_line_no, f_globals)
        lines.append("{0}".format(pre_line.rstrip()))

    # The line itself
    lines.append("{0}".format(current_line.rstrip()))

    # Add some lines after
    for pre_line_no in range(line_no + 1, line_no + around + 1):
        pre_line = linecache.getline(filename, pre_line_no, f_globals)
        lines.append("{0}".format(pre_line.rstrip()))

    # Smart left strip
    minimal_tab = None
    for line in lines:
        if line.strip():
            tab = len(line) - len(line.lstrip())
            if minimal_tab is None or tab < minimal_tab:
                minimal_tab = tab

    if minimal_tab > 0:
        lines = [line[minimal_tab:] for line in lines]

    # Add some place for a marker
    marked_line = ">> {0}".format(lines[around])
    lines = ["   {0}".format(line) for line in lines]
    lines[around] = marked_line
    lines.append("")
    return lines

Response: Extracts a block of lines from the given file.


Instruction:
Write a Python 3 script for
returning the list of methods for this command handler.

Response:
def get_methods(self):
        """
        Retrieves the list of tuples (command, method) for this command handler
        """
        return [
            ("levels", self.print_levels),
            ("make", self.make_report),
            ("clear", self.clear_report),
            ("show", self.show_report),
            ("write", self.write_report),
        ]


Instruction:
Make a summary of the following Python 3 code
def get_level_methods(self, level):
        try:
            # Real name of the level
            return set(self.__levels[level])
        except KeyError:
            # Alias
            result = set()
            for sub_level in self.__aliases[level]:
                result.update(self.get_level_methods(sub_level))
            return result

Response: Returns the set of methods to call for the given level of report


Instruction:
Write a Python 3 function for
printing the available levels to the given session.

Response:
def print_levels(self, session):
        """
        Lists available levels
        """
        lines = []
        for level in sorted(self.get_levels()):
            methods = sorted(
                method.__name__ for method in self.get_level_methods(level)
            )
            lines.append("- {0}:".format(level))
            lines.append("\t{0}".format(", ".join(methods)))
        session.write_line("\n".join(lines))


Instruction:
How would you implement a function in Python 3 that
returns a dictionary containing details about the operating system and the operating system itself.

Response:
def os_details():
        """
        Returns a dictionary containing details about the operating system
        """
        # Compute architecture and linkage
        bits, linkage = platform.architecture()
        results = {
            # Machine details
            "platform.arch.bits": bits,
            "platform.arch.linkage": linkage,
            "platform.machine": platform.machine(),
            "platform.process": platform.processor(),
            "sys.byteorder": sys.byteorder,
            # OS details
            "os.name": os.name,
            "host.name": socket.gethostname(),
            "sys.platform": sys.platform,
            "platform.system": platform.system(),
            "platform.release": platform.release(),
            "platform.version": platform.version(),
            "encoding.filesystem": sys.getfilesystemencoding(),
        }

        # Paths and line separators
        for name in "sep", "altsep", "pathsep", "linesep":
            results["os.{0}".format(name)] = getattr(os, name, None)

        try:
            # Available since Python 3.4
            results["os.cpu_count"] = os.cpu_count()
        except AttributeError:
            results["os.cpu_count"] = None

        try:
            # Only for Unix
            # pylint: disable=E1101
            results["sys.dlopenflags"] = sys.getdlopenflags()
        except AttributeError:
            results["sys.dlopenflags"] = None

        return results


Instruction:
Implement a function in Python 3 to
return details about the current process

Response:
def process_details():
        """
        Returns details about the current process
        """
        results = {"argv": sys.argv, "working.directory": os.getcwd()}

        # Process ID and execution IDs (UID, GID, Login, ...)
        for key, method in {
            "pid": "getpid",
            "ppid": "getppid",
            "login": "getlogin",
            "uid": "getuid",
            "euid": "geteuid",
            "gid": "getgid",
            "egid": "getegid",
            "groups": "getgroups",
        }.items():
            try:
                results[key] = getattr(os, method)()
            except (AttributeError, OSError):
                results[key] = None
        return results


Instruction:
Can you write a function in Python 3 where it
returns details about the network links in the current language.

Response:
def network_details():
        """
        Returns details about the network links
        """
        # Get IPv4 details
        ipv4_addresses = [
            info[4][0]
            for info in socket.getaddrinfo(
                socket.gethostname(), None, socket.AF_INET
            )
        ]

        # Add localhost
        ipv4_addresses.extend(
            info[4][0]
            for info in socket.getaddrinfo("localhost", None, socket.AF_INET)
        )

        # Filter addresses
        ipv4_addresses = sorted(set(ipv4_addresses))

        try:
            # Get IPv6 details
            ipv6_addresses = [
                info[4][0]
                for info in socket.getaddrinfo(
                    socket.gethostname(), None, socket.AF_INET6
                )
            ]

            # Add localhost
            ipv6_addresses.extend(
                info[4][0]
                for info in socket.getaddrinfo(
                    "localhost", None, socket.AF_INET6
                )
            )

            # Filter addresses
            ipv6_addresses = sorted(set(ipv6_addresses))
        except (socket.gaierror, AttributeError):
            # AttributeError: AF_INET6 is missing in some versions of Python
            ipv6_addresses = None

        return {
            "IPv4": ipv4_addresses,
            "IPv6": ipv6_addresses,
            "host.name": socket.gethostname(),
            "host.fqdn": socket.getfqdn(),
        }


Instruction:
Can you tell what is the following Python 3 function doing
def python_details():
        build_no, build_date = platform.python_build()
        results = {
            # Version of interpreter
            "build.number": build_no,
            "build.date": build_date,
            "compiler": platform.python_compiler(),
            "branch": platform.python_branch(),
            "revision": platform.python_revision(),
            "implementation": platform.python_implementation(),
            "version": ".".join(str(v) for v in sys.version_info),
            # API version
            "api.version": sys.api_version,
            # Installation details
            "prefix": sys.prefix,
            "base_prefix": getattr(sys, "base_prefix", None),
            "exec_prefix": sys.exec_prefix,
            "base_exec_prefix": getattr(sys, "base_exec_prefix", None),
            # Execution details
            "executable": sys.executable,
            "encoding.default": sys.getdefaultencoding(),
            # Other details, ...
            "recursion_limit": sys.getrecursionlimit(),
        }

        # Threads implementation details
        thread_info = getattr(sys, "thread_info", (None, None, None))
        results["thread_info.name"] = thread_info[0]
        results["thread_info.lock"] = thread_info[1]
        results["thread_info.version"] = thread_info[2]

        # ABI flags (POSIX only)
        results["abiflags"] = getattr(sys, "abiflags", None)

        # -X options (CPython only)
        results["x_options"] = getattr(sys, "_xoptions", None)
        return results

Response: Returns a dictionary containing details about the Python interpreter and the Python interpreter itself.


Instruction:
Can you generate the documentation for the following Python 3 function
def python_modules():
        imported = {}
        results = {"builtins": sys.builtin_module_names, "imported": imported}
        for module_name, module_ in sys.modules.items():
            if module_name not in sys.builtin_module_names:
                try:
                    imported[module_name] = inspect.getfile(module_)
                except TypeError:
                    imported[
                        module_name
                    ] = "<no file information :: {0}>".format(repr(module_))

        return results

Response: Returns the list of Python modules and their file information.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pelix_bundles(self):
        framework = self.__context.get_framework()
        return {
            bundle.get_bundle_id(): {
                "name": bundle.get_symbolic_name(),
                "version": bundle.get_version(),
                "state": bundle.get_state(),
                "location": bundle.get_location(),
            }
            for bundle in framework.get_bundles()
        }

Response: Return a list of installed bundles


Instruction:
Create a Python 3 function for
returning a list of the services that are in the system

Response:
def pelix_services(self):
        """
        List of registered services
        """
        return {
            svc_ref.get_property(pelix.constants.SERVICE_ID): {
                "specifications": svc_ref.get_property(
                    pelix.constants.OBJECTCLASS
                ),
                "ranking": svc_ref.get_property(
                    pelix.constants.SERVICE_RANKING
                ),
                "properties": svc_ref.get_properties(),
                "bundle.id": svc_ref.get_bundle().get_bundle_id(),
                "bundle.name": svc_ref.get_bundle().get_symbolic_name(),
            }
            for svc_ref in self.__context.get_all_service_references(None)
        }


Instruction:
Given the following Python 3 function, write the documentation
def ipopo_factories(self):
        try:
            with use_ipopo(self.__context) as ipopo:
                return {
                    name: ipopo.get_factory_details(name)
                    for name in ipopo.get_factories()
                }
        except BundleException:
            # iPOPO is not available:
            return None

Response: Return a dictionary of iPOPO factory details for all the iPOPO related objects.


Instruction:
Explain what the following Python 3 code does
def ipopo_instances(self):
        try:
            with use_ipopo(self.__context) as ipopo:
                return {
                    instance[0]: ipopo.get_instance_details(instance[0])
                    for instance in ipopo.get_instances()
                }
        except BundleException:
            # iPOPO is not available:
            return None

Response: Returns a list of iPOPO instances


Instruction:
Implement a Python 3 function for
listing the active threads and their current code line line.

Response:
def threads_list():
        """
        Lists the active threads and their current code line
        """
        results = {}

        # pylint: disable=W0212
        try:
            # Extract frames
            frames = sys._current_frames()

            # Get the thread ID -> Thread mapping
            names = threading._active.copy()
        except AttributeError:
            # Extraction not available
            return results

        # Sort by thread ID
        thread_ids = sorted(frames.keys())
        for thread_id in thread_ids:
            # Get the corresponding stack
            stack = frames[thread_id]

            # Try to get the thread name
            try:
                name = names[thread_id].name
            except KeyError:
                name = "<unknown>"

            trace_lines = []
            frame = stack
            while frame is not None:
                # Store the line information
                trace_lines.append(format_frame_info(frame))

                # Previous frame...
                frame = frame.f_back

            # Construct the thread description
            results[thread_id] = {
                "name": name,
                "stacktrace": "\n".join(reversed(trace_lines)),
            }

        return results


Instruction:
Write a Python 3 function that can
create a report for the requested levels.

Response:
def make_report(self, session, *levels):
        """
        Prepares the report at the requested level(s)
        """
        if not levels:
            levels = ["full"]

        try:
            # List the methods to call, avoiding double-calls
            methods = set()
            for level in levels:
                methods.update(self.get_level_methods(level))
        except KeyError as ex:
            # Unknown level
            session.write_line("Unknown report level: {0}", ex)
            self.__report = None
        else:
            # Call each method
            self.__report = {method.__name__: method() for method in methods}
            # Describe the report
            self.__report["report"] = {
                "report.levels": levels,
                "time.stamp": time.time(),
                "time.local": str(datetime.datetime.now()),
                "time.utc": str(datetime.datetime.utcnow()),
            }

        return self.__report