Instruction:
Implement a function in Python 3 to
send an html message to one more email addresses.

Response:
def send_html_email(
    subject,  # single line with no line-breaks
    html_content,
    to_emails,
    from_email=DEFAULT_FROM_EMAIL,
    fail_silently=True
    ):
    """
    Send a message to one more email address(s).
    With html content as primary.
    """
    messenger = EmailMessage(subject, html_content, from_email, to_emails)
    messenger.content_subtype = "html"  # Main content is now text/html
    try:
        messenger.send()
    except Exception as e:
        if not fail_silently:
            raise


Instruction:
Make a summary of the following Python 3 code
def trim_form(parser, token):
    try:
        trim_form, orig_form, opcode, fields, as_, new_form = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('Invalid arguments for %r' % token.split_contents()[0])

    return FieldSetNode(opcode, fields.split(','), orig_form, new_form)

Response: Returns a form that only contains a subset of the original fields.


Instruction:
Write a Python 3 function for
turning a command - line argument into a list.

Response:
def unshell_list(s):
    """Turn a command-line argument into a list."""
    if not s:
        return None
    if sys.platform == 'win32':
        # When running coverage as coverage.exe, some of the behavior
        # of the shell is emulated: wildcards are expanded into a list of
        # filenames.  So you have to single-quote patterns on the command
        # line, but (not) helpfully, the single quotes are included in the
        # argument, so we have to strip them off here.
        s = s.strip("'")
    return s.split(',')


Instruction:
How would you explain what the following Python 3 function does
def parse_args(self, args=None, options=None):
        try:
            options, args = \
                super(CoverageOptionParser, self).parse_args(args, options)
        except self.OptionParserError:
            return False, None, None
        return True, options, args

Response: Call optparse. parse_args but return a triple


Instruction:
Can you generate the documentation for the following Python 3 function
def add_action(self, dash, dashdash, action_code):
        option = self.add_option(dash, dashdash, action='callback',
            callback=self._append_action
            )
        option.action_code = action_code

Response: Add a specialized option that is the action to execute.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _append_action(self, option, opt_unused, value_unused, parser):
        parser.values.actions.append(option.action_code)

Response: Callback for an option that adds to the actions list.


Instruction:
How would you explain what the following Python 3 function does
def command_line(self, argv):
        # Collect the command-line options.
        if not argv:
            self.help_fn(topic='minimum_help')
            return OK

        # The command syntax we parse depends on the first argument.  Classic
        # syntax always starts with an option.
        self.classic = argv[0].startswith('-')
        if self.classic:
            parser = ClassicOptionParser()
        else:
            parser = CMDS.get(argv[0])
            if not parser:
                self.help_fn("Unknown command: '%s'" % argv[0])
                return ERR
            argv = argv[1:]

        parser.help_fn = self.help_fn
        ok, options, args = parser.parse_args(argv)
        if not ok:
            return ERR

        # Handle help and version.
        if self.do_help(options, args, parser):
            return OK

        # Check for conflicts and problems in the options.
        if not self.args_ok(options, args):
            return ERR

        # Listify the list options.
        source = unshell_list(options.source)
        omit = unshell_list(options.omit)
        include = unshell_list(options.include)
        debug = unshell_list(options.debug)

        # Do something.
        self.coverage = self.covpkg.coverage(
            data_suffix = options.parallel_mode,
            cover_pylib = options.pylib,
            timid = options.timid,
            branch = options.branch,
            config_file = options.rcfile,
            source = source,
            omit = omit,
            include = include,
            debug = debug,
            )

        if 'debug' in options.actions:
            return self.do_debug(args)

        if 'erase' in options.actions or options.erase_first:
            self.coverage.erase()
        else:
            self.coverage.load()

        if 'execute' in options.actions:
            self.do_execute(options, args)

        if 'combine' in options.actions:
            self.coverage.combine()
            self.coverage.save()

        # Remaining actions are reporting, with some common options.
        report_args = dict(
            morfs = args,
            ignore_errors = options.ignore_errors,
            omit = omit,
            include = include,
            )

        if 'report' in options.actions:
            total = self.coverage.report(
                show_missing=options.show_missing, **report_args)
        if 'annotate' in options.actions:
            self.coverage.annotate(
                directory=options.directory, **report_args)
        if 'html' in options.actions:
            total = self.coverage.html_report(
                directory=options.directory, title=options.title,
                **report_args)
        if 'xml' in options.actions:
            outfile = options.outfile
            total = self.coverage.xml_report(outfile=outfile, **report_args)

        if options.fail_under is not None:
            if total >= options.fail_under:
                return OK
            else:
                return FAIL_UNDER
        else:
            return OK

Response: This function is called by the command - line interface to Coverage. It will parse the command - line arguments and then call the coverage command.


Instruction:
Can you generate the documentation for the following Python 3 function
def help(self, error=None, topic=None, parser=None):
        assert error or topic or parser
        if error:
            print(error)
            print("Use 'coverage help' for help.")
        elif parser:
            print(parser.format_help().strip())
        else:
            help_msg = HELP_TOPICS.get(topic, '').strip()
            if help_msg:
                print(help_msg % self.covpkg.__dict__)
            else:
                print("Don't know topic %r" % topic)

Response: Display an error message or the named topic.


Instruction:
How would you implement a function in Python 3 that
checks if all of the arguments are ok.

Response:
def args_ok(self, options, args):
        """Check for conflicts and problems in the options.

        Returns True if everything is ok, or False if not.

        """
        for i in ['erase', 'execute']:
            for j in ['annotate', 'html', 'report', 'combine']:
                if (i in options.actions) and (j in options.actions):
                    self.help_fn("You can't specify the '%s' and '%s' "
                              "options at the same time." % (i, j))
                    return False

        if not options.actions:
            self.help_fn(
                "You must specify at least one of -e, -x, -c, -r, -a, or -b."
                )
            return False
        args_allowed = (
            'execute' in options.actions or
            'annotate' in options.actions or
            'html' in options.actions or
            'debug' in options.actions or
            'report' in options.actions or
            'xml' in options.actions
            )
        if not args_allowed and args:
            self.help_fn("Unexpected arguments: %s" % " ".join(args))
            return False

        if 'execute' in options.actions and not args:
            self.help_fn("Nothing to do.")
            return False

        return True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def do_debug(self, args):

        if not args:
            self.help_fn("What information would you like: data, sys?")
            return ERR
        for info in args:
            if info == 'sys':
                print("-- sys ----------------------------------------")
                for line in info_formatter(self.coverage.sysinfo()):
                    print(" %s" % line)
            elif info == 'data':
                print("-- data ---------------------------------------")
                self.coverage.load()
                print("path: %s" % self.coverage.data.filename)
                print("has_arcs: %r" % self.coverage.data.has_arcs())
                summary = self.coverage.data.summary(fullpath=True)
                if summary:
                    filenames = sorted(summary.keys())
                    print("\n%d files:" % len(filenames))
                    for f in filenames:
                        print("%s: %d lines" % (f, summary[f]))
                else:
                    print("No data collected")
            else:
                self.help_fn("Don't know what you mean by %r" % info)
                return ERR
        return OK

Response: Implementation of coverage debug


Instruction:
How would you explain what the following Python 3 function does
def serialize_object(obj, threshold=64e-6):
    databuffers = []
    if isinstance(obj, (list, tuple)):
        clist = canSequence(obj)
        slist = map(serialize, clist)
        for s in slist:
            if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold:
                databuffers.append(s.getData())
                s.data = None
        return pickle.dumps(slist,-1), databuffers
    elif isinstance(obj, dict):
        sobj = {}
        for k in sorted(obj.iterkeys()):
            s = serialize(can(obj[k]))
            if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold:
                databuffers.append(s.getData())
                s.data = None
            sobj[k] = s
        return pickle.dumps(sobj,-1),databuffers
    else:
        s = serialize(can(obj))
        if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold:
            databuffers.append(s.getData())
            s.data = None
        return pickle.dumps(s,-1),databuffers

Response: Serialize an object into a list of sendable buffers.


Instruction:
How would you implement a function in Python 3 that
reconstructs an object serialized by serialize_object from data buffers.

Response:
def unserialize_object(bufs):
    """reconstruct an object serialized by serialize_object from data buffers."""
    bufs = list(bufs)
    sobj = pickle.loads(bufs.pop(0))
    if isinstance(sobj, (list, tuple)):
        for s in sobj:
            if s.data is None:
                s.data = bufs.pop(0)
        return uncanSequence(map(unserialize, sobj)), bufs
    elif isinstance(sobj, dict):
        newobj = {}
        for k in sorted(sobj.iterkeys()):
            s = sobj[k]
            if s.data is None:
                s.data = bufs.pop(0)
            newobj[k] = uncan(unserialize(s))
        return newobj, bufs
    else:
        if sobj.data is None:
            sobj.data = bufs.pop(0)
        return uncan(unserialize(sobj)), bufs


Instruction:
Make a summary of the following Python 3 code
def pack_apply_message(f, args, kwargs, threshold=64e-6):
    msg = [pickle.dumps(can(f),-1)]
    databuffers = [] # for large objects
    sargs, bufs = serialize_object(args,threshold)
    msg.append(sargs)
    databuffers.extend(bufs)
    skwargs, bufs = serialize_object(kwargs,threshold)
    msg.append(skwargs)
    databuffers.extend(bufs)
    msg.extend(databuffers)
    return msg

Response:
pack up a function args and kwargs to be sent over the wire
    as a series of buffers


Instruction:
Can you tell what is the following Python 3 function doing
def unpack_apply_message(bufs, g=None, copy=True):
    bufs = list(bufs) # allow us to pop
    assert len(bufs) >= 3, "not enough buffers!"
    if not copy:
        for i in range(3):
            bufs[i] = bufs[i].bytes
    cf = pickle.loads(bufs.pop(0))
    sargs = list(pickle.loads(bufs.pop(0)))
    skwargs = dict(pickle.loads(bufs.pop(0)))
    # print sargs, skwargs
    f = uncan(cf, g)
    for sa in sargs:
        if sa.data is None:
            m = bufs.pop(0)
            if sa.getTypeDescriptor() in ('buffer', 'ndarray'):
                # always use a buffer, until memoryviews get sorted out
                sa.data = buffer(m)
                # disable memoryview support
                # if copy:
                #     sa.data = buffer(m)
                # else:
                #     sa.data = m.buffer
            else:
                if copy:
                    sa.data = m
                else:
                    sa.data = m.bytes

    args = uncanSequence(map(unserialize, sargs), g)
    kwargs = {}
    for k in sorted(skwargs.iterkeys()):
        sa = skwargs[k]
        if sa.data is None:
            m = bufs.pop(0)
            if sa.getTypeDescriptor() in ('buffer', 'ndarray'):
                # always use a buffer, until memoryviews get sorted out
                sa.data = buffer(m)
                # disable memoryview support
                # if copy:
                #     sa.data = buffer(m)
                # else:
                #     sa.data = m.buffer
            else:
                if copy:
                    sa.data = m
                else:
                    sa.data = m.bytes

        kwargs[k] = uncan(unserialize(sa), g)

    return f,args,kwargs

Response: unpacks f args kwargs from buffers packed by pack_apply_message


Instruction:
Can you generate the documentation for the following Python 3 function
def is_url(url):
    if '://' not in url:
        return False
    proto, addr = url.split('://', 1)
    if proto.lower() not in ['tcp','pgm','epgm','ipc','inproc']:
        return False
    return True

Response: boolean check for whether a string is a zmq url


Instruction:
Given the following Python 3 function, write the documentation
def validate_url(url):
    if not isinstance(url, basestring):
        raise TypeError("url must be a string, not %r"%type(url))
    url = url.lower()

    proto_addr = url.split('://')
    assert len(proto_addr) == 2, 'Invalid url: %r'%url
    proto, addr = proto_addr
    assert proto in ['tcp','pgm','epgm','ipc','inproc'], "Invalid protocol: %r"%proto

    # domain pattern adapted from http://www.regexlib.com/REDetails.aspx?regexp_id=391
    # author: Remi Sabourin
    pat = re.compile(r'^([\w\d]([\w\d\-]{0,61}[\w\d])?\.)*[\w\d]([\w\d\-]{0,61}[\w\d])?$')

    if proto == 'tcp':
        lis = addr.split(':')
        assert len(lis) == 2, 'Invalid url: %r'%url
        addr,s_port = lis
        try:
            port = int(s_port)
        except ValueError:
            raise AssertionError("Invalid port %r in url: %r"%(port, url))

        assert addr == '*' or pat.match(addr) is not None, 'Invalid url: %r'%url

    else:
        # only validate tcp urls currently
        pass

    return True

Response: validate a url for zeromq


Instruction:
Explain what the following Python 3 code does
def validate_url_container(container):
    if isinstance(container, basestring):
        url = container
        return validate_url(url)
    elif isinstance(container, dict):
        container = container.itervalues()

    for element in container:
        validate_url_container(element)

Response: validate a potentially nested collection of urls.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def split_url(url):
    proto_addr = url.split('://')
    assert len(proto_addr) == 2, 'Invalid url: %r'%url
    proto, addr = proto_addr
    lis = addr.split(':')
    assert len(lis) == 2, 'Invalid url: %r'%url
    addr,s_port = lis
    return proto,addr,s_port

Response: split a zmq url into proto addr s_port


Instruction:
Can you create a Python 3 function that
disambiguates an IP address into a multi - ip interface 0. 0 and '*' into connectable Surfaces based on the location.

Response:
def disambiguate_ip_address(ip, location=None):
    """turn multi-ip interfaces '0.0.0.0' and '*' into connectable
    ones, based on the location (default interpretation of location is localhost)."""
    if ip in ('0.0.0.0', '*'):
        try:
            external_ips = socket.gethostbyname_ex(socket.gethostname())[2]
        except (socket.gaierror, IndexError):
            # couldn't identify this machine, assume localhost
            external_ips = []
        if location is None or location in external_ips or not external_ips:
            # If location is unspecified or cannot be determined, assume local
            ip='127.0.0.1'
        elif location:
            return location
    return ip


Instruction:
Here you have a function in Python 3, explain what it does
def disambiguate_url(url, location=None):
    try:
        proto,ip,port = split_url(url)
    except AssertionError:
        # probably not tcp url; could be ipc, etc.
        return url

    ip = disambiguate_ip_address(ip,location)

    return "%s://%s:%s"%(proto,ip,port)

Response:
disambiguate a url into a multi - ip interface 0. 0 and '*' into connectable
 .


Instruction:
Explain what the following Python 3 code does
def _pull(keys):
    user_ns = globals()
    if isinstance(keys, (list,tuple, set)):
        for key in keys:
            if not user_ns.has_key(key):
                raise NameError("name '%s' is not defined"%key)
        return map(user_ns.get, keys)
    else:
        if not user_ns.has_key(keys):
            raise NameError("name '%s' is not defined"%keys)
        return user_ns.get(keys)

Response: helper method for implementing client. pull via client. apply


Instruction:
Write a Python 3 script for
selecting and return n random ports that are available.

Response:
def select_random_ports(n):
    """Selects and return n random ports that are available."""
    ports = []
    for i in xrange(n):
        sock = socket.socket()
        sock.bind(('', 0))
        while sock.getsockname()[1] in _random_ports:
            sock.close()
            sock = socket.socket()
            sock.bind(('', 0))
        ports.append(sock)
    for i, sock in enumerate(ports):
        port = sock.getsockname()[1]
        sock.close()
        ports[i] = port
        _random_ports.add(port)
    return ports


Instruction:
Write a Python 3 script for
relaying interupt and term signals to children.

Response:
def signal_children(children):
    """Relay interupt/term signals to children, for more solid process cleanup."""
    def terminate_children(sig, frame):
        log = Application.instance().log
        log.critical("Got signal %i, terminating children..."%sig)
        for child in children:
            child.terminate()

        sys.exit(sig != SIGINT)
        # sys.exit(sig)
    for sig in (SIGINT, SIGABRT, SIGTERM):
        signal(sig, terminate_children)


Instruction:
Make a summary of the following Python 3 code
def remote(view, block=None, **flags):

    def remote_function(f):
        return RemoteFunction(view, f, block=block, **flags)
    return remote_function

Response: Turn a function into a remote function.


Instruction:
How would you explain what the following Python 3 function does
def parallel(view, dist='b', block=None, ordered=True, **flags):

    def parallel_function(f):
        return ParallelFunction(view, f, dist=dist, block=block, ordered=ordered, **flags)
    return parallel_function

Response: Turn a function into a parallel remote function.


Instruction:
Write a Python 3 function that can
call a function on each element of a sequence remotely.

Response:
def map(self, *sequences):
        """call a function on each element of a sequence remotely.
        This should behave very much like the builtin map, but return an AsyncMapResult
        if self.block is False.
        """
        # set _map as a flag for use inside self.__call__
        self._map = True
        try:
            ret = self.__call__(*sequences)
        finally:
            del self._map
        return ret


Instruction:
Can you implement a function in Python 3 that
gets the last n items in readline history.

Response:
def get_readline_tail(self, n=10):
        """Get the last n items in readline history."""
        end = self.shell.readline.get_current_history_length() + 1
        start = max(end-n, 1)
        ghi = self.shell.readline.get_history_item
        return [ghi(x) for x in range(start, end)]


Instruction:
Here you have a function in Python 3, explain what it does
def set_autoindent(self,value=None):

        if value != 0 and not self.has_readline:
            if os.name == 'posix':
                warn("The auto-indent feature requires the readline library")
            self.autoindent = 0
            return
        if value is None:
            self.autoindent = not self.autoindent
        else:
            self.autoindent = value

Response: Set the autoindent flag checking for readline support.


Instruction:
Can you implement a function in Python 3 that
initializes logging in case it was requested at the command line.

Response:
def init_logstart(self):
        """Initialize logging in case it was requested at the command line.
        """
        if self.logappend:
            self.magic('logstart %s append' % self.logappend)
        elif self.logfile:
            self.magic('logstart %s' % self.logfile)
        elif self.logstart:
            self.magic('logstart')


Instruction:
Can you tell what is the following Python 3 function doing
def init_virtualenv(self):
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            return

        if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
            # Running properly in the virtualenv, don't need to do anything
            return

        warn("Attempting to work in a virtualenv. If you encounter problems, please "
             "install IPython inside the virtualenv.\n")
        if sys.platform == "win32":
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
        else:
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
                       'python%d.%d' % sys.version_info[:2], 'site-packages')

        import site
        sys.path.insert(0, virtual_env)
        site.addsitedir(virtual_env)

Response: Add a virtualenv to sys. path so the user can import modules from it.


Instruction:
Explain what the following Python 3 code does
def save_sys_module_state(self):
        self._orig_sys_module_state = {}
        self._orig_sys_module_state['stdin'] = sys.stdin
        self._orig_sys_module_state['stdout'] = sys.stdout
        self._orig_sys_module_state['stderr'] = sys.stderr
        self._orig_sys_module_state['excepthook'] = sys.excepthook
        self._orig_sys_modules_main_name = self.user_module.__name__
        self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)

Response: Save the state of sys. modules.


Instruction:
Can you tell what is the following Python 3 function doing
def restore_sys_module_state(self):
        try:
            for k, v in self._orig_sys_module_state.iteritems():
                setattr(sys, k, v)
        except AttributeError:
            pass
        # Reset what what done in self.init_sys_modules
        if self._orig_sys_modules_main_mod is not None:
            sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod

Response: Restore the state of the sys module.


Instruction:
Make a summary of the following Python 3 code
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):

        # At some point in the future, this should validate the hook before it
        # accepts it.  Probably at least check that the hook takes the number
        # of args it's supposed to.

        f = types.MethodType(hook,self)

        # check if the hook is for strdispatcher first
        if str_key is not None:
            sdp = self.strdispatchers.get(name, StrDispatch())
            sdp.add_s(str_key, f, priority )
            self.strdispatchers[name] = sdp
            return
        if re_key is not None:
            sdp = self.strdispatchers.get(name, StrDispatch())
            sdp.add_re(re.compile(re_key), f, priority )
            self.strdispatchers[name] = sdp
            return

        dp = getattr(self.hooks, name, None)
        if name not in IPython.core.hooks.__all__:
            print "Warning! Hook '%s' is not one of %s" % \
                  (name, IPython.core.hooks.__all__ )
        if not dp:
            dp = IPython.core.hooks.CommandChainDispatcher()

        try:
            dp.add(f,priority)
        except AttributeError:
            # it was not commandchain, plain old func - replace
            dp = f

        setattr(self.hooks,name, dp)

Response: Set an internal IPython hook.


Instruction:
Given the following Python 3 function, write the documentation
def register_post_execute(self, func):
        if not callable(func):
            raise ValueError('argument %s must be callable' % func)
        self._post_execute[func] = True

Response: Register a function for calling after code execution.


Instruction:
Create a Python 3 function for
returning a new main module object for user code execution.

Response:
def new_main_mod(self,ns=None):
        """Return a new 'main' module object for user code execution.
        """
        main_mod = self._user_main_module
        init_fakemod_dict(main_mod,ns)
        return main_mod


Instruction:
Explain what the following Python 3 code does
def cache_main_mod(self,ns,fname):
        self._main_ns_cache[os.path.abspath(fname)] = ns.copy()

Response: Cache a main module s namespace.


Instruction:
Write a Python 3 function that can
call the pydb/pdb debugger. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false.

Response:
def debugger(self,force=False):
        """Call the pydb/pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
          flag and does not actually invoke the debugger if the flag is false.
          The 'force' option forces the debugger to activate even if the flag
          is false.
        """

        if not (force or self.call_pdb):
            return

        if not hasattr(sys,'last_traceback'):
            error('No traceback has been produced, nothing to debug.')
            return

        # use pydb if available
        if debugger.has_pydb:
            from pydb import pm
        else:
            # fallback to our internal debugger
            pm = lambda : self.InteractiveTB.debugger(force=True)

        with self.readline_no_record:
            pm()


Instruction:
Here you have a function in Python 3, explain what it does
def prepare_user_module(self, user_module=None, user_ns=None):
        if user_module is None and user_ns is not None:
            user_ns.setdefault("__name__", "__main__")
            class DummyMod(object):
                "A dummy module used for IPython's interactive namespace."
                pass
            user_module = DummyMod()
            user_module.__dict__ = user_ns

        if user_module is None:
            user_module = types.ModuleType("__main__",
                doc="Automatically created module for IPython interactive environment")

        # We must ensure that __builtin__ (without the final 's') is always
        # available and pointing to the __builtin__ *module*.  For more details:
        # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
        user_module.__dict__.setdefault('__builtin__', builtin_mod)
        user_module.__dict__.setdefault('__builtins__', builtin_mod)

        if user_ns is None:
            user_ns = user_module.__dict__

        return user_module, user_ns

Response: Prepare the user module and namespace in which user code will be run.


Instruction:
How would you code a function in Python 3 to
initialize all user - visible user - visible user - namespace variables to their minimum defaults.

Response:
def init_user_ns(self):
        """Initialize all user-visible namespaces to their minimum defaults.

        Certain history lists are also initialized here, as they effectively
        act as user namespaces.

        Notes
        -----
        All data structures here are only filled in, they are NOT reset by this
        method.  If they were not empty before, data will simply be added to
        therm.
        """
        # This function works in two parts: first we put a few things in
        # user_ns, and we sync that contents into user_ns_hidden so that these
        # initial variables aren't shown by %who.  After the sync, we add the
        # rest of what we *do* want the user to see with %who even on a new
        # session (probably nothing, so theye really only see their own stuff)

        # The user dict must *always* have a __builtin__ reference to the
        # Python standard __builtin__ namespace,  which must be imported.
        # This is so that certain operations in prompt evaluation can be
        # reliably executed with builtins.  Note that we can NOT use
        # __builtins__ (note the 's'),  because that can either be a dict or a
        # module, and can even mutate at runtime, depending on the context
        # (Python makes no guarantees on it).  In contrast, __builtin__ is
        # always a module object, though it must be explicitly imported.

        # For more details:
        # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
        ns = dict()

        # Put 'help' in the user namespace
        try:
            from site import _Helper
            ns['help'] = _Helper()
        except ImportError:
            warn('help() not available - check site.py')

        # make global variables for user access to the histories
        ns['_ih'] = self.history_manager.input_hist_parsed
        ns['_oh'] = self.history_manager.output_hist
        ns['_dh'] = self.history_manager.dir_hist

        ns['_sh'] = shadowns

        # user aliases to input and output histories.  These shouldn't show up
        # in %who, as they can have very large reprs.
        ns['In']  = self.history_manager.input_hist_parsed
        ns['Out'] = self.history_manager.output_hist

        # Store myself as the public api!!!
        ns['get_ipython'] = self.get_ipython

        ns['exit'] = self.exiter
        ns['quit'] = self.exiter

        # Sync what we've added so far to user_ns_hidden so these aren't seen
        # by %who
        self.user_ns_hidden.update(ns)

        # Anything put into ns now would show up in %who.  Think twice before
        # putting anything here, as we really want %who to show the user their
        # stuff, not our variables.

        # Finally, update the real user's namespace
        self.user_ns.update(ns)


Instruction:
How would you code a function in Python 3 to
get a list of all the namespace dictionaries in which IPython might store a user - created object.

Response:
def all_ns_refs(self):
        """Get a list of references to all the namespace dictionaries in which
        IPython might store a user-created object.

        Note that this does not include the displayhook, which also caches
        objects from the output."""
        return [self.user_ns, self.user_global_ns,
                self._user_main_module.__dict__] + self._main_ns_cache.values()


Instruction:
Given the following Python 3 function, write the documentation
def reset(self, new_session=True):
        # Clear histories
        self.history_manager.reset(new_session)
        # Reset counter used to index all histories
        if new_session:
            self.execution_count = 1

        # Flush cached output items
        if self.displayhook.do_full_cache:
            self.displayhook.flush()

        # The main execution namespaces must be cleared very carefully,
        # skipping the deletion of the builtin-related keys, because doing so
        # would cause errors in many object's __del__ methods.
        if self.user_ns is not self.user_global_ns:
            self.user_ns.clear()
        ns = self.user_global_ns
        drop_keys = set(ns.keys())
        drop_keys.discard('__builtin__')
        drop_keys.discard('__builtins__')
        drop_keys.discard('__name__')
        for k in drop_keys:
            del ns[k]

        self.user_ns_hidden.clear()

        # Restore the user namespaces to minimal usability
        self.init_user_ns()

        # Restore the default and user aliases
        self.alias_manager.clear_aliases()
        self.alias_manager.init_aliases()

        # Flush the private list of module references kept for script
        # execution protection
        self.clear_main_mod_cache()

        # Clear out the namespace from the last %run
        self.new_main_mod()

Response: Reset all internal namespaces and aliases and aliases to their default values.


Instruction:
Explain what the following Python 3 code does
def del_var(self, varname, by_name=False):
        if varname in ('__builtin__', '__builtins__'):
            raise ValueError("Refusing to delete %s" % varname)

        ns_refs = self.all_ns_refs

        if by_name:                    # Delete by name
            for ns in ns_refs:
                try:
                    del ns[varname]
                except KeyError:
                    pass
        else:                         # Delete by object
            try:
                obj = self.user_ns[varname]
            except KeyError:
                raise NameError("name '%s' is not defined" % varname)
            # Also check in output history
            ns_refs.append(self.history_manager.output_hist)
            for ns in ns_refs:
                to_delete = [n for n, o in ns.iteritems() if o is obj]
                for name in to_delete:
                    del ns[name]

            # displayhook keeps extra references, but not in a dictionary
            for name in ('_', '__', '___'):
                if getattr(self.displayhook, name) is obj:
                    setattr(self.displayhook, name, None)

Response: Delete a variable from the various namespaces so that we don t keep any hidden references to it.


Instruction:
Create a Python 3 function to
clear selective variables from internal namespaces based on a regular expression pattern.

Response:
def reset_selective(self, regex=None):
        """Clear selective variables from internal namespaces based on a
        specified regular expression.

        Parameters
        ----------
        regex : string or compiled pattern, optional
            A regular expression pattern that will be used in searching
            variable names in the users namespaces.
        """
        if regex is not None:
            try:
                m = re.compile(regex)
            except TypeError:
                raise TypeError('regex must be a string or compiled pattern')
            # Search for keys in each namespace that match the given regex
            # If a match is found, delete the key/value pair.
            for ns in self.all_ns_refs:
                for var in ns:
                    if m.search(var):
                        del ns[var]


Instruction:
Given the following Python 3 function, write the documentation
def push(self, variables, interactive=True):
        vdict = None

        # We need a dict of name/value pairs to do namespace updates.
        if isinstance(variables, dict):
            vdict = variables
        elif isinstance(variables, (basestring, list, tuple)):
            if isinstance(variables, basestring):
                vlist = variables.split()
            else:
                vlist = variables
            vdict = {}
            cf = sys._getframe(1)
            for name in vlist:
                try:
                    vdict[name] = eval(name, cf.f_globals, cf.f_locals)
                except:
                    print ('Could not get variable %s from %s' %
                           (name,cf.f_code.co_name))
        else:
            raise ValueError('variables must be a dict/str/list/tuple')

        # Propagate variables to user namespace
        self.user_ns.update(vdict)

        # And configure interactive visibility
        user_ns_hidden = self.user_ns_hidden
        if interactive:
            user_ns_hidden.difference_update(vdict)
        else:
            user_ns_hidden.update(vdict)

Response: Injects a group of variables into the IPython user namespace.


Instruction:
Create a Python 3 function for
removing a dict of variables from the user namespace if they are the same as the values in the dictionary.

Response:
def drop_by_id(self, variables):
        """Remove a dict of variables from the user namespace, if they are the
        same as the values in the dictionary.

        This is intended for use by extensions: variables that they've added can
        be taken back out if they are unloaded, without removing any that the
        user has overwritten.

        Parameters
        ----------
        variables : dict
          A dictionary mapping object names (as strings) to the objects.
        """
        for name, obj in variables.iteritems():
            if name in self.user_ns and self.user_ns[name] is obj:
                del self.user_ns[name]
                self.user_ns_hidden.discard(name)


Instruction:
Create a Python 3 function to
find an object in the available namespaces.

Response:
def _ofind(self, oname, namespaces=None):
        """Find an object in the available namespaces.

        self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic

        Has special code to detect magic functions.
        """
        oname = oname.strip()
        #print '1- oname: <%r>' % oname  # dbg
        if not oname.startswith(ESC_MAGIC) and \
            not oname.startswith(ESC_MAGIC2) and \
            not py3compat.isidentifier(oname, dotted=True):
            return dict(found=False)

        alias_ns = None
        if namespaces is None:
            # Namespaces to search in:
            # Put them in a list. The order is important so that we
            # find things in the same order that Python finds them.
            namespaces = [ ('Interactive', self.user_ns),
                           ('Interactive (global)', self.user_global_ns),
                           ('Python builtin', builtin_mod.__dict__),
                           ('Alias', self.alias_manager.alias_table),
                           ]
            alias_ns = self.alias_manager.alias_table

        # initialize results to 'null'
        found = False; obj = None;  ospace = None;  ds = None;
        ismagic = False; isalias = False; parent = None

        # We need to special-case 'print', which as of python2.6 registers as a
        # function but should only be treated as one if print_function was
        # loaded with a future import.  In this case, just bail.
        if (oname == 'print' and not py3compat.PY3 and not \
            (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
            return {'found':found, 'obj':obj, 'namespace':ospace,
                    'ismagic':ismagic, 'isalias':isalias, 'parent':parent}

        # Look for the given name by splitting it in parts.  If the head is
        # found, then we look for all the remaining parts as members, and only
        # declare success if we can find them all.
        oname_parts = oname.split('.')
        oname_head, oname_rest = oname_parts[0],oname_parts[1:]
        for nsname,ns in namespaces:
            try:
                obj = ns[oname_head]
            except KeyError:
                continue
            else:
                #print 'oname_rest:', oname_rest  # dbg
                for part in oname_rest:
                    try:
                        parent = obj
                        obj = getattr(obj,part)
                    except:
                        # Blanket except b/c some badly implemented objects
                        # allow __getattr__ to raise exceptions other than
                        # AttributeError, which then crashes IPython.
                        break
                else:
                    # If we finish the for loop (no break), we got all members
                    found = True
                    ospace = nsname
                    if ns == alias_ns:
                        isalias = True
                    break  # namespace loop

        # Try to see if it's magic
        if not found:
            obj = None
            if oname.startswith(ESC_MAGIC2):
                oname = oname.lstrip(ESC_MAGIC2)
                obj = self.find_cell_magic(oname)
            elif oname.startswith(ESC_MAGIC):
                oname = oname.lstrip(ESC_MAGIC)
                obj = self.find_line_magic(oname)
            else:
                # search without prefix, so run? will find %run?
                obj = self.find_line_magic(oname)
                if obj is None:
                    obj = self.find_cell_magic(oname)
            if obj is not None:
                found = True
                ospace = 'IPython internal'
                ismagic = True

        # Last try: special-case some literals like '', [], {}, etc:
        if not found and oname_head in ["''",'""','[]','{}','()']:
            obj = eval(oname_head)
            found = True
            ospace = 'Interactive'

        return {'found':found, 'obj':obj, 'namespace':ospace,
                'ismagic':ismagic, 'isalias':isalias, 'parent':parent}


Instruction:
Create a Python 3 function for
seconding part of object finding, to look for property details.

Response:
def _ofind_property(self, oname, info):
        """Second part of object finding, to look for property details."""
        if info.found:
            # Get the docstring of the class property if it exists.
            path = oname.split('.')
            root = '.'.join(path[:-1])
            if info.parent is not None:
                try:
                    target = getattr(info.parent, '__class__')
                    # The object belongs to a class instance.
                    try:
                        target = getattr(target, path[-1])
                        # The class defines the object.
                        if isinstance(target, property):
                            oname = root + '.__class__.' + path[-1]
                            info = Struct(self._ofind(oname))
                    except AttributeError: pass
                except AttributeError: pass

        # We return either the new info or the unmodified input if the object
        # hadn't been found
        return info


Instruction:
Explain what the following Python 3 code does
def _object_find(self, oname, namespaces=None):
        inf = Struct(self._ofind(oname, namespaces))
        return Struct(self._ofind_property(oname, inf))

Response: Find an object and return a struct with info about it.


Instruction:
Implement a function in Python 3 to
set up the command history and starts regular autosaves.

Response:
def init_history(self):
        """Sets up the command history, and starts regular autosaves."""
        self.history_manager = HistoryManager(shell=self, config=self.config)
        self.configurables.append(self.history_manager)


Instruction:
Write a Python 3 function for
setting a custom exception handler for the specified exception classes.

Response:
def set_custom_exc(self, exc_tuple, handler):
        """set_custom_exc(exc_tuple,handler)

        Set a custom exception handler, which will be called if any of the
        exceptions in exc_tuple occur in the mainloop (specifically, in the
        run_code() method).

        Parameters
        ----------

        exc_tuple : tuple of exception classes
            A *tuple* of exception classes, for which to call the defined
            handler.  It is very important that you use a tuple, and NOT A
            LIST here, because of the way Python's except statement works.  If
            you only want to trap a single exception, use a singleton tuple::

                exc_tuple == (MyCustomException,)

        handler : callable
            handler must have the following signature::

                def my_handler(self, etype, value, tb, tb_offset=None):
                    ...
                    return structured_traceback

            Your handler must return a structured traceback (a list of strings),
            or None.

            This will be made into an instance method (via types.MethodType)
            of IPython itself, and it will be called if any of the exceptions
            listed in the exc_tuple are caught. If the handler is None, an
            internal basic one is used, which just prints basic info.

            To protect IPython from crashes, if your handler ever raises an
            exception or returns an invalid result, it will be immediately
            disabled.

        WARNING: by putting in your own exception handler into IPython's main
        execution loop, you run a very good chance of nasty crashes.  This
        facility should only be used if you really know what you are doing."""

        assert type(exc_tuple)==type(()) , \
               "The custom exceptions must be given AS A TUPLE."

        def dummy_handler(self,etype,value,tb,tb_offset=None):
            print '*** Simple custom exception handler ***'
            print 'Exception type :',etype
            print 'Exception value:',value
            print 'Traceback      :',tb
            #print 'Source code    :','\n'.join(self.buffer)

        def validate_stb(stb):
            """validate structured traceback return type

            return type of CustomTB *should* be a list of strings, but allow
            single strings or None, which are harmless.

            This function will *always* return a list of strings,
            and will raise a TypeError if stb is inappropriate.
            """
            msg = "CustomTB must return list of strings, not %r" % stb
            if stb is None:
                return []
            elif isinstance(stb, basestring):
                return [stb]
            elif not isinstance(stb, list):
                raise TypeError(msg)
            # it's a list
            for line in stb:
                # check every element
                if not isinstance(line, basestring):
                    raise TypeError(msg)
            return stb

        if handler is None:
            wrapped = dummy_handler
        else:
            def wrapped(self,etype,value,tb,tb_offset=None):
                """wrap CustomTB handler, to protect IPython from user code

                This makes it harder (but not impossible) for custom exception
                handlers to crash IPython.
                """
                try:
                    stb = handler(self,etype,value,tb,tb_offset=tb_offset)
                    return validate_stb(stb)
                except:
                    # clear custom handler immediately
                    self.set_custom_exc((), None)
                    print >> io.stderr, "Custom TB Handler failed, unregistering"
                    # show the exception in handler first
                    stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
                    print >> io.stdout, self.InteractiveTB.stb2text(stb)
                    print >> io.stdout, "The original exception:"
                    stb = self.InteractiveTB.structured_traceback(
                                            (etype,value,tb), tb_offset=tb_offset
                    )
                return stb

        self.CustomTB = types.MethodType(wrapped,self)
        self.custom_exceptions = exc_tuple


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_exc_info(self, exc_tuple=None):
        if exc_tuple is None:
            etype, value, tb = sys.exc_info()
        else:
            etype, value, tb = exc_tuple

        if etype is None:
            if hasattr(sys, 'last_type'):
                etype, value, tb = sys.last_type, sys.last_value, \
                                   sys.last_traceback

        if etype is None:
            raise ValueError("No exception to find")

        # Now store the exception info in sys.last_type etc.
        # WARNING: these variables are somewhat deprecated and not
        # necessarily safe to use in a threaded environment, but tools
        # like pdb depend on their existence, so let's set them.  If we
        # find problems in the field, we'll need to revisit their use.
        sys.last_type = etype
        sys.last_value = value
        sys.last_traceback = tb

        return etype, value, tb

Response: get exc_info from a given tuple sys. exc_info sys. last_type sys. last_value sys. last_traceback


Instruction:
How would you implement a function in Python 3 that
displays the traceback of the exception that just occurred.

Response:
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
                      exception_only=False):
        """Display the exception that just occurred.

        If nothing is known about the exception, this is the method which
        should be used throughout the code for presenting user tracebacks,
        rather than directly invoking the InteractiveTB object.

        A specific showsyntaxerror() also exists, but this method can take
        care of calling it if needed, so unless you are explicitly catching a
        SyntaxError exception, don't try to analyze the stack manually and
        simply call this method."""

        try:
            try:
                etype, value, tb = self._get_exc_info(exc_tuple)
            except ValueError:
                self.write_err('No traceback available to show.\n')
                return

            if etype is SyntaxError:
                # Though this won't be called by syntax errors in the input
                # line, there may be SyntaxError cases with imported code.
                self.showsyntaxerror(filename)
            elif etype is UsageError:
                self.write_err("UsageError: %s" % value)
            else:
                if exception_only:
                    stb = ['An exception has occurred, use %tb to see '
                           'the full traceback.\n']
                    stb.extend(self.InteractiveTB.get_exception_only(etype,
                                                                     value))
                else:
                    try:
                        # Exception classes can customise their traceback - we
                        # use this in IPython.parallel for exceptions occurring
                        # in the engines. This should return a list of strings.
                        stb = value._render_traceback_()
                    except Exception:
                        stb = self.InteractiveTB.structured_traceback(etype,
                                            value, tb, tb_offset=tb_offset)

                    self._showtraceback(etype, value, stb)
                    if self.call_pdb:
                        # drop into debugger
                        self.debugger(force=True)
                    return

                # Actually show the traceback
                self._showtraceback(etype, value, stb)

        except KeyboardInterrupt:
            self.write_err("\nKeyboardInterrupt\n")


Instruction:
Can you write a function in Python 3 where it
displays the syntax error that just occurred.

Response:
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).
        """
        etype, value, last_traceback = self._get_exc_info()

        if filename and etype is SyntaxError:
            try:
                value.filename = filename
            except:
                # Not the format we expect; leave it alone
                pass

        stb = self.SyntaxTB.structured_traceback(etype, value, [])
        self._showtraceback(etype, value, stb)


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

        if self.readline_use:
            import IPython.utils.rlineimpl as readline

        self.rl_next_input = None
        self.rl_do_indent = False

        if not self.readline_use or not readline.have_readline:
            self.has_readline = False
            self.readline = None
            # Set a number of methods that depend on readline to be no-op
            self.readline_no_record = no_op_context
            self.set_readline_completer = no_op
            self.set_custom_completer = no_op
            if self.readline_use:
                warn('Readline services not available or not loaded.')
        else:
            self.has_readline = True
            self.readline = readline
            sys.modules['readline'] = readline

            # Platform-specific configuration
            if os.name == 'nt':
                # FIXME - check with Frederick to see if we can harmonize
                # naming conventions with pyreadline to avoid this
                # platform-dependent check
                self.readline_startup_hook = readline.set_pre_input_hook
            else:
                self.readline_startup_hook = readline.set_startup_hook

            # Load user's initrc file (readline config)
            # Or if libedit is used, load editrc.
            inputrc_name = os.environ.get('INPUTRC')
            if inputrc_name is None:
                inputrc_name = '.inputrc'
                if readline.uses_libedit:
                    inputrc_name = '.editrc'
                inputrc_name = os.path.join(self.home_dir, inputrc_name)
            if os.path.isfile(inputrc_name):
                try:
                    readline.read_init_file(inputrc_name)
                except:
                    warn('Problems reading readline initialization file <%s>'
                         % inputrc_name)

            # Configure readline according to user's prefs
            # This is only done if GNU readline is being used.  If libedit
            # is being used (as on Leopard) the readline config is
            # not run as the syntax for libedit is different.
            if not readline.uses_libedit:
                for rlcommand in self.readline_parse_and_bind:
                    #print "loading rl:",rlcommand  # dbg
                    readline.parse_and_bind(rlcommand)

            # Remove some chars from the delimiters list.  If we encounter
            # unicode chars, discard them.
            delims = readline.get_completer_delims()
            if not py3compat.PY3:
                delims = delims.encode("ascii", "ignore")
            for d in self.readline_remove_delims:
                delims = delims.replace(d, "")
            delims = delims.replace(ESC_MAGIC, '')
            readline.set_completer_delims(delims)
            # otherwise we end up with a monster history after a while:
            readline.set_history_length(self.history_length)

            self.refill_readline_hist()
            self.readline_no_record = ReadlineNoRecord(self)

        # Configure auto-indent for all platforms
        self.set_autoindent(self.autoindent)

Response: Initialize the readline module.


Instruction:
How would you code a function in Python 3 to
hook to be used at the start of each line. Currently it handles auto - indent only.

Response:
def pre_readline(self):
        """readline hook to be used at the start of each line.

        Currently it handles auto-indent only."""

        if self.rl_do_indent:
            self.readline.insert_text(self._indent_current_str())
        if self.rl_next_input is not None:
            self.readline.insert_text(self.rl_next_input)
            self.rl_next_input = None


Instruction:
Write a Python 3 script for
initializing the completion machinery.

Response:
def init_completer(self):
        """Initialize the completion machinery.

        This creates completion machinery that can be used by client code,
        either interactively in-process (typically triggered by the readline
        library), programatically (such as in test suites) or out-of-prcess
        (typically over the network by remote frontends).
        """
        from IPython.core.completer import IPCompleter
        from IPython.core.completerlib import (module_completer,
                magic_run_completer, cd_completer, reset_completer)

        self.Completer = IPCompleter(shell=self,
                                     namespace=self.user_ns,
                                     global_namespace=self.user_global_ns,
                                     alias_table=self.alias_manager.alias_table,
                                     use_readline=self.has_readline,
                                     config=self.config,
                                     )
        self.configurables.append(self.Completer)

        # Add custom completers to the basic ones built into IPCompleter
        sdisp = self.strdispatchers.get('complete_command', StrDispatch())
        self.strdispatchers['complete_command'] = sdisp
        self.Completer.custom_completers = sdisp

        self.set_hook('complete_command', module_completer, str_key = 'import')
        self.set_hook('complete_command', module_completer, str_key = 'from')
        self.set_hook('complete_command', magic_run_completer, str_key = '%run')
        self.set_hook('complete_command', cd_completer, str_key = '%cd')
        self.set_hook('complete_command', reset_completer, str_key = '%reset')

        # Only configure readline if we truly are using readline.  IPython can
        # do tab-completion over the network, in GUIs, etc, where readline
        # itself may be absent
        if self.has_readline:
            self.set_readline_completer()


Instruction:
Explain what the following Python 3 code does
def complete(self, text, line=None, cursor_pos=None):

        # Inject names into __builtin__ so we can complete on the added names.
        with self.builtin_trap:
            return self.Completer.complete(text, line, cursor_pos)

Response: Return the completed text and a list of possible completions.


Instruction:
Can you tell what is the following Python 3 function doing
def set_custom_completer(self, completer, pos=0):

        newcomp = types.MethodType(completer,self.Completer)
        self.Completer.matchers.insert(pos,newcomp)

Response: Adds a new custom completer function.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_completer_frame(self, frame=None):
        if frame:
            self.Completer.namespace = frame.f_locals
            self.Completer.global_namespace = frame.f_globals
        else:
            self.Completer.namespace = self.user_ns
            self.Completer.global_namespace = self.user_global_ns

Response: Set the frame of the completer.


Instruction:
Write a Python 3 function that can
execute the given line magic.

Response:
def run_line_magic(self, magic_name, line):
        """Execute the given line magic.

        Parameters
        ----------
        magic_name : str
          Name of the desired magic function, without '%' prefix.

        line : str
          The rest of the input line as a single string.
        """
        fn = self.find_line_magic(magic_name)
        if fn is None:
            cm = self.find_cell_magic(magic_name)
            etpl = "Line magic function `%%%s` not found%s."
            extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
                                    'did you mean that instead?)' % magic_name )
            error(etpl % (magic_name, extra))
        else:
            # Note: this is the distance in the stack to the user's frame.
            # This will need to be updated if the internal calling logic gets
            # refactored, or else we'll be expanding the wrong variables.
            stack_depth = 2
            magic_arg_s = self.var_expand(line, stack_depth)
            # Put magic args in a list so we can call with f(*a) syntax
            args = [magic_arg_s]
            # Grab local namespace if we need it:
            if getattr(fn, "needs_local_scope", False):
                args.append(sys._getframe(stack_depth).f_locals)
            with self.builtin_trap:
                result = fn(*args)
            return result


Instruction:
How would you code a function in Python 3 to
execute the given cell magic.

Response:
def run_cell_magic(self, magic_name, line, cell):
        """Execute the given cell magic.

        Parameters
        ----------
        magic_name : str
          Name of the desired magic function, without '%' prefix.

        line : str
          The rest of the first input line as a single string.

        cell : str
          The body of the cell as a (possibly multiline) string.
        """
        fn = self.find_cell_magic(magic_name)
        if fn is None:
            lm = self.find_line_magic(magic_name)
            etpl = "Cell magic function `%%%%%s` not found%s."
            extra = '' if lm is None else (' (But line magic `%%%s` exists, '
                                    'did you mean that instead?)' % magic_name )
            error(etpl % (magic_name, extra))
        else:
            # Note: this is the distance in the stack to the user's frame.
            # This will need to be updated if the internal calling logic gets
            # refactored, or else we'll be expanding the wrong variables.
            stack_depth = 2
            magic_arg_s = self.var_expand(line, stack_depth)
            with self.builtin_trap:
                result = fn(line, cell)
            return result


Instruction:
Given the following Python 3 function, write the documentation
def find_magic(self, magic_name, magic_kind='line'):
        return self.magics_manager.magics[magic_kind].get(magic_name)

Response: Find and return a magic of the given type by name.


Instruction:
Can you generate the documentation for the following Python 3 function
def magic(self, arg_s):
        # TODO: should we issue a loud deprecation warning here?
        magic_name, _, magic_arg_s = arg_s.partition(' ')
        magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
        return self.run_line_magic(magic_name, magic_arg_s)

Response: Deprecated. Use run_line_magic to call a magic function by name.


Instruction:
Write a Python 3 script to
define a new macro in the user namespace.

Response:
def define_macro(self, name, themacro):
        """Define a new macro

        Parameters
        ----------
        name : str
            The name of the macro.
        themacro : str or Macro
            The action to do upon invoking the macro.  If a string, a new
            Macro object is created by passing the string to it.
        """

        from IPython.core import macro

        if isinstance(themacro, basestring):
            themacro = macro.Macro(themacro)
        if not isinstance(themacro, macro.Macro):
            raise ValueError('A macro must be a string or a Macro instance.')
        self.user_ns[name] = themacro


Instruction:
Write a Python 3 script for
calling the given cmd in a subprocess using os. system ArcGIS

Response:
def system_raw(self, cmd):
        """Call the given cmd in a subprocess using os.system

        Parameters
        ----------
        cmd : str
          Command to execute.
        """
        cmd = self.var_expand(cmd, depth=1)
        # protect os.system from UNC paths on Windows, which it can't handle:
        if sys.platform == 'win32':
            from IPython.utils._process_win32 import AvoidUNCPath
            with AvoidUNCPath() as path:
                if path is not None:
                    cmd = '"pushd %s &&"%s' % (path, cmd)
                cmd = py3compat.unicode_to_str(cmd)
                ec = os.system(cmd)
        else:
            cmd = py3compat.unicode_to_str(cmd)
            ec = os.system(cmd)

        # We explicitly do NOT return the subprocess status code, because
        # a non-None value would trigger :func:`sys.displayhook` calls.
        # Instead, we store the exit_code in user_ns.
        self.user_ns['_exit_code'] = ec


Instruction:
Write a Python 3 function that can
get output from a subprocess.

Response:
def getoutput(self, cmd, split=True, depth=0):
        """Get output (possibly including stderr) from a subprocess.

        Parameters
        ----------
        cmd : str
          Command to execute (can not end in '&', as background processes are
          not supported.
        split : bool, optional
          If True, split the output into an IPython SList.  Otherwise, an
          IPython LSString is returned.  These are objects similar to normal
          lists and strings, with a few convenience attributes for easier
          manipulation of line-based output.  You can use '?' on them for
          details.
        depth : int, optional
          How many frames above the caller are the local variables which should
          be expanded in the command string? The default (0) assumes that the
          expansion variables are in the stack frame calling this function.
        """
        if cmd.rstrip().endswith('&'):
            # this is *far* from a rigorous test
            raise OSError("Background processes not supported.")
        out = getoutput(self.var_expand(cmd, depth=depth+1))
        if split:
            out = SList(out.splitlines())
        else:
            out = LSString(out)
        return out


Instruction:
Can you create a Python 3 function that
prints to the screen the rewritten form of the user s command.

Response:
def auto_rewrite_input(self, cmd):
        """Print to the screen the rewritten form of the user's command.

        This shows visual feedback by rewriting input lines that cause
        automatic calling to kick in, like::

          /f x

        into::

          ------> f(x)

        after the user's input prompt.  This helps the user understand that the
        input line was transformed automatically by IPython.
        """
        if not self.show_rewritten_input:
            return

        rw = self.prompt_manager.render('rewrite') + cmd

        try:
            # plain ascii works better w/ pyreadline, on some machines, so
            # we use it and only print uncolored rewrite if we have unicode
            rw = str(rw)
            print >> io.stdout, rw
        except UnicodeEncodeError:
            print "------> " + cmd


Instruction:
Can you tell what is the following Python 3 function doing
def user_variables(self, names):
        out = {}
        user_ns = self.user_ns
        for varname in names:
            try:
                value = repr(user_ns[varname])
            except:
                value = self._simple_error()
            out[varname] = value
        return out

Response: Get a list of variable names from the user s namespace.


Instruction:
Implement a Python 3 function for
evaluating a dict of Python expressions in the user s namespace.

Response:
def user_expressions(self, expressions):
        """Evaluate a dict of expressions in the user's namespace.

        Parameters
        ----------
        expressions : dict
          A dict with string keys and string values.  The expression values
          should be valid Python expressions, each of which will be evaluated
          in the user namespace.

        Returns
        -------
        A dict, keyed like the input expressions dict, with the repr() of each
        value.
        """
        out = {}
        user_ns = self.user_ns
        global_ns = self.user_global_ns
        for key, expr in expressions.iteritems():
            try:
                value = repr(eval(expr, global_ns, user_ns))
            except:
                value = self._simple_error()
            out[key] = value
        return out


Instruction:
Here you have a function in Python 3, explain what it does
def ex(self, cmd):
        with self.builtin_trap:
            exec cmd in self.user_global_ns, self.user_ns

Response: Execute a normal python statement in user namespace.


Instruction:
Can you create a Python 3 function that
evaluates python expression expr in user namespace.

Response:
def ev(self, expr):
        """Evaluate python expression expr in user namespace.

        Returns the result of evaluation
        """
        with self.builtin_trap:
            return eval(expr, self.user_global_ns, self.user_ns)


Instruction:
Here you have a function in Python 3, explain what it does
def safe_execfile_ipy(self, fname):
        fname = os.path.abspath(os.path.expanduser(fname))

        # Make sure we can open the file
        try:
            with open(fname) as thefile:
                pass
        except:
            warn('Could not open file <%s> for safe execution.' % fname)
            return

        # Find things also in current directory.  This is needed to mimic the
        # behavior of running a script from the system command line, where
        # Python inserts the script's directory into sys.path
        dname = os.path.dirname(fname)

        with prepended_to_syspath(dname):
            try:
                with open(fname) as thefile:
                    # self.run_cell currently captures all exceptions
                    # raised in user code.  It would be nice if there were
                    # versions of runlines, execfile that did raise, so
                    # we could catch the errors.
                    self.run_cell(thefile.read(), store_history=False)
            except:
                self.showtraceback()
                warn('Unknown failure executing file: <%s>' % fname)

Response: Like safe_execfile but for. ipython files with IPython syntax.


Instruction:
How would you explain what the following Python 3 function does
def _run_cached_cell_magic(self, magic_name, line):
        cell = self._current_cell_magic_body
        self._current_cell_magic_body = None
        return self.run_cell_magic(magic_name, line, cell)

Response: Special method to call a cell magic with the data stored in self. _current_cell_magic_body


Instruction:
Create a Python 3 function to
run a complete IPython cell.

Response:
def run_cell(self, raw_cell, store_history=False, silent=False):
        """Run a complete IPython cell.

        Parameters
        ----------
        raw_cell : str
          The code (including IPython code such as %magic functions) to run.
        store_history : bool
          If True, the raw and translated cell will be stored in IPython's
          history. For user code calling back into IPython's machinery, this
          should be set to False.
        silent : bool
          If True, avoid side-effets, such as implicit displayhooks, history,
          and logging.  silent=True forces store_history=False.
        """
        if (not raw_cell) or raw_cell.isspace():
            return

        if silent:
            store_history = False

        self.input_splitter.push(raw_cell)

        # Check for cell magics, which leave state behind.  This interface is
        # ugly, we need to do something cleaner later...  Now the logic is
        # simply that the input_splitter remembers if there was a cell magic,
        # and in that case we grab the cell body.
        if self.input_splitter.cell_magic_parts:
            self._current_cell_magic_body = \
                               ''.join(self.input_splitter.cell_magic_parts)
        cell = self.input_splitter.source_reset()

        with self.builtin_trap:
            prefilter_failed = False
            if len(cell.splitlines()) == 1:
                try:
                    # use prefilter_lines to handle trailing newlines
                    # restore trailing newline for ast.parse
                    cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
                except AliasError as e:
                    error(e)
                    prefilter_failed = True
                except Exception:
                    # don't allow prefilter errors to crash IPython
                    self.showtraceback()
                    prefilter_failed = True

            # Store raw and processed history
            if store_history:
                self.history_manager.store_inputs(self.execution_count,
                                                  cell, raw_cell)
            if not silent:
                self.logger.log(cell, raw_cell)

            if not prefilter_failed:
                # don't run if prefilter failed
                cell_name = self.compile.cache(cell, self.execution_count)

                with self.display_trap:
                    try:
                        code_ast = self.compile.ast_parse(cell,
                                                          filename=cell_name)
                    except IndentationError:
                        self.showindentationerror()
                        if store_history:
                            self.execution_count += 1
                        return None
                    except (OverflowError, SyntaxError, ValueError, TypeError,
                            MemoryError):
                        self.showsyntaxerror()
                        if store_history:
                            self.execution_count += 1
                        return None

                    interactivity = "none" if silent else self.ast_node_interactivity
                    self.run_ast_nodes(code_ast.body, cell_name,
                                       interactivity=interactivity)

                    # Execute any registered post-execution functions.
                    # unless we are silent
                    post_exec = [] if silent else self._post_execute.iteritems()

                    for func, status in post_exec:
                        if self.disable_failing_post_execute and not status:
                            continue
                        try:
                            func()
                        except KeyboardInterrupt:
                            print >> io.stderr, "\nKeyboardInterrupt"
                        except Exception:
                            # register as failing:
                            self._post_execute[func] = False
                            self.showtraceback()
                            print >> io.stderr, '\n'.join([
                                "post-execution function %r produced an error." % func,
                                "If this problem persists, you can disable failing post-exec functions with:",
                                "",
                                "    get_ipython().disable_failing_post_execute = True"
                            ])

        if store_history:
            # Write output to the database. Does nothing unless
            # history output logging is enabled.
            self.history_manager.store_output(self.execution_count)
            # Each cell is a *single* input, regardless of how many lines it has
            self.execution_count += 1


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
        if not nodelist:
            return

        if interactivity == 'last_expr':
            if isinstance(nodelist[-1], ast.Expr):
                interactivity = "last"
            else:
                interactivity = "none"

        if interactivity == 'none':
            to_run_exec, to_run_interactive = nodelist, []
        elif interactivity == 'last':
            to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
        elif interactivity == 'all':
            to_run_exec, to_run_interactive = [], nodelist
        else:
            raise ValueError("Interactivity was %r" % interactivity)

        exec_count = self.execution_count

        try:
            for i, node in enumerate(to_run_exec):
                mod = ast.Module([node])
                code = self.compile(mod, cell_name, "exec")
                if self.run_code(code):
                    return True

            for i, node in enumerate(to_run_interactive):
                mod = ast.Interactive([node])
                code = self.compile(mod, cell_name, "single")
                if self.run_code(code):
                    return True

            # Flush softspace
            if softspace(sys.stdout, 0):
                print

        except:
            # It's possible to have exceptions raised here, typically by
            # compilation of odd code (such as a naked 'return' outside a
            # function) that did parse but isn't valid. Typically the exception
            # is a SyntaxError, but it's safest just to catch anything and show
            # the user a traceback.

            # We do only one try/except outside the loop to minimize the impact
            # on runtime, and also because if any node in the node list is
            # broken, we should stop execution completely.
            self.showtraceback()

        return False

Response: Runs a sequence of AST nodes.


Instruction:
Here you have a function in Python 3, explain what it does
def run_code(self, code_obj):

        # Set our own excepthook in case the user code tries to call it
        # directly, so that the IPython crash handler doesn't get triggered
        old_excepthook,sys.excepthook = sys.excepthook, self.excepthook

        # we save the original sys.excepthook in the instance, in case config
        # code (such as magics) needs access to it.
        self.sys_excepthook = old_excepthook
        outflag = 1  # happens in more places, so it's easier as default
        try:
            try:
                self.hooks.pre_run_code_hook()
                #rprint('Running code', repr(code_obj)) # dbg
                exec code_obj in self.user_global_ns, self.user_ns
            finally:
                # Reset our crash handler in place
                sys.excepthook = old_excepthook
        except SystemExit:
            self.showtraceback(exception_only=True)
            warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
        except self.custom_exceptions:
            etype,value,tb = sys.exc_info()
            self.CustomTB(etype,value,tb)
        except:
            self.showtraceback()
        else:
            outflag = 0
        return outflag

Response: Execute a compiled code object and return the exit status.


Instruction:
Given the following Python 3 function, write the documentation
def enable_pylab(self, gui=None, import_all=True):
        from IPython.core.pylabtools import mpl_runner
        # We want to prevent the loading of pylab to pollute the user's
        # namespace as shown by the %who* magics, so we execute the activation
        # code in an empty namespace, and we update *both* user_ns and
        # user_ns_hidden with this information.
        ns = {}
        try:
            gui = pylab_activate(ns, gui, import_all, self)
        except KeyError:
            error("Backend %r not supported" % gui)
            return
        self.user_ns.update(ns)
        self.user_ns_hidden.update(ns)
        # Now we must activate the gui pylab wants to use, and fix %run to take
        # plot updates into account
        self.enable_gui(gui)
        self.magics_manager.registry['ExecutionMagics'].default_runner = \
        mpl_runner(self.safe_execfile)

Response: Activate pylab support at runtime.


Instruction:
How would you explain what the following Python 3 function does
def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
        ns = self.user_ns.copy()
        ns.update(sys._getframe(depth+1).f_locals)
        ns.pop('self', None)
        try:
            cmd = formatter.format(cmd, **ns)
        except Exception:
            # if formatter couldn't format, just let it go untransformed
            pass
        return cmd

Response: Expand python variables in a string.


Instruction:
Given the following Python 3 function, write the documentation
def mktempfile(self, data=None, prefix='ipython_edit_'):

        filename = tempfile.mktemp('.py', prefix)
        self.tempfiles.append(filename)

        if data:
            tmp_file = open(filename,'w')
            tmp_file.write(data)
            tmp_file.close()
        return filename

Response: Make a new tempfile and return its filename.


Instruction:
Can you generate the documentation for the following Python 3 function
def extract_input_lines(self, range_str, raw=False):
        lines = self.history_manager.get_range_by_str(range_str, raw=raw)
        return "\n".join(x for _, _, x in lines)

Response: Return as a string a set of input history slices.


Instruction:
Here you have a function in Python 3, explain what it does
def find_user_code(self, target, raw=True, py_only=False):
        code = self.extract_input_lines(target, raw=raw)  # Grab history
        if code:
            return code
        utarget = unquote_filename(target)
        try:
            if utarget.startswith(('http://', 'https://')):
                return openpy.read_py_url(utarget, skip_encoding_cookie=True)
        except UnicodeDecodeError:
            if not py_only :
                response = urllib.urlopen(target)
                return response.read().decode('latin1')
            raise ValueError(("'%s' seem to be unreadable.") % utarget)

        potential_target = [target]
        try :
            potential_target.insert(0,get_py_filename(target))
        except IOError:
            pass

        for tgt in potential_target :
            if os.path.isfile(tgt):                        # Read file
                try :
                    return openpy.read_py_file(tgt, skip_encoding_cookie=True)
                except UnicodeDecodeError :
                    if not py_only :
                        with io_open(tgt,'r', encoding='latin1') as f :
                            return f.read()
                    raise ValueError(("'%s' seem to be unreadable.") % target)

        try:                                              # User namespace
            codeobj = eval(target, self.user_ns)
        except Exception:
            raise ValueError(("'%s' was not found in history, as a file, url, "
                                "nor in the user namespace.") % target)
        if isinstance(codeobj, basestring):
            return codeobj
        elif isinstance(codeobj, Macro):
            return codeobj.value

        raise TypeError("%s is neither a string nor a macro." % target,
                        codeobj)

Response: Get a code string from history file filename or raw history.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def atexit_operations(self):
        # Close the history session (this stores the end time and line count)
        # this must be *before* the tempfile cleanup, in case of temporary
        # history db
        self.history_manager.end_session()

        # Cleanup all tempfiles left around
        for tfile in self.tempfiles:
            try:
                os.unlink(tfile)
            except OSError:
                pass

        # Clear all user namespaces to release all references cleanly.
        self.reset(new_session=False)

        # Run user hooks
        self.hooks.shutdown_hook()

Response: This will be executed at the time of exit.


Instruction:
Can you generate the documentation for the following Python 3 function
def broadcast(client, sender, msg_name, dest_name=None, block=None):
    dest_name = msg_name if dest_name is None else dest_name
    client[sender].execute('com.publish(%s)'%msg_name, block=None)
    targets = client.ids
    targets.remove(sender)
    return client[targets].execute('%s=com.consume()'%dest_name, block=None)

Response: broadcast a message from one engine to all others.


Instruction:
Can you write a function in Python 3 where it
sends a message from one to one - or - more engines.

Response:
def send(client, sender, targets, msg_name, dest_name=None, block=None):
    """send a message from one to one-or-more engines."""
    dest_name = msg_name if dest_name is None else dest_name
    def _send(targets, m_name):
        msg = globals()[m_name]
        return com.send(targets, msg)

    client[sender].apply_async(_send, targets, msg_name)

    return client[targets].execute('%s=com.recv()'%dest_name, block=None)


Instruction:
Can you implement a function in Python 3 that
makes function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- skip_condition : bool or callable Flag to determine whether to skip the decorated test. msg : str, optional Message to give on raising a SkipTest exception. Default is None. Returns ------- decorator : function Decorator which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata.

Response:
def skipif(skip_condition, msg=None):
    """
    Make function raise SkipTest exception if a given condition is true.

    If the condition is a callable, it is used at runtime to dynamically
    make the decision. This is useful for tests that may require costly
    imports, to delay the cost until the test suite is actually executed.

    Parameters
    ----------
    skip_condition : bool or callable
        Flag to determine whether to skip the decorated test.
    msg : str, optional
        Message to give on raising a SkipTest exception. Default is None.

    Returns
    -------
    decorator : function
        Decorator which, when applied to a function, causes SkipTest
        to be raised when `skip_condition` is True, and the function
        to be called normally otherwise.

    Notes
    -----
    The decorator itself is decorated with the ``nose.tools.make_decorator``
    function in order to transmit function name, and various other metadata.

    """

    def skip_decorator(f):
        # Local import to avoid a hard nose dependency and only incur the
        # import time overhead at actual test-time.
        import nose

        # Allow for both boolean or callable skip conditions.
        if callable(skip_condition):
            skip_val = lambda : skip_condition()
        else:
            skip_val = lambda : skip_condition

        def get_msg(func,msg=None):
            """Skip message with information about function being skipped."""
            if msg is None:
                out = 'Test skipped due to test condition'
            else:
                out = '\n'+msg

            return "Skipping test: %s%s" % (func.__name__,out)

        # We need to define *two* skippers because Python doesn't allow both
        # return with value and yield inside the same function.
        def skipper_func(*args, **kwargs):
            """Skipper for normal test functions."""
            if skip_val():
                raise nose.SkipTest(get_msg(f,msg))
            else:
                return f(*args, **kwargs)

        def skipper_gen(*args, **kwargs):
            """Skipper for test generators."""
            if skip_val():
                raise nose.SkipTest(get_msg(f,msg))
            else:
                for x in f(*args, **kwargs):
                    yield x

        # Choose the right skipper to use when building the actual decorator.
        if nose.util.isgenerator(f):
            skipper = skipper_gen
        else:
            skipper = skipper_func

        return nose.tools.make_decorator(f)(skipper)

    return skip_decorator


Instruction:
How would you explain what the following Python 3 function does
def knownfailureif(fail_condition, msg=None):
    if msg is None:
        msg = 'Test skipped due to known failure'

    # Allow for both boolean or callable known failure conditions.
    if callable(fail_condition):
        fail_val = lambda : fail_condition()
    else:
        fail_val = lambda : fail_condition

    def knownfail_decorator(f):
        # Local import to avoid a hard nose dependency and only incur the
        # import time overhead at actual test-time.
        import nose
        def knownfailer(*args, **kwargs):
            if fail_val():
                raise KnownFailureTest, msg
            else:
                return f(*args, **kwargs)
        return nose.tools.make_decorator(f)(knownfailer)

    return knownfail_decorator

Response: Decorator that makes a function raise KnownFailureTest exception if given condition is true.


Instruction:
Can you generate the documentation for the following Python 3 function
def deprecated(conditional=True):
    def deprecate_decorator(f):
        # Local import to avoid a hard nose dependency and only incur the
        # import time overhead at actual test-time.
        import nose

        def _deprecated_imp(*args, **kwargs):
            # Poor man's replacement for the with statement
            ctx = WarningManager(record=True)
            l = ctx.__enter__()
            warnings.simplefilter('always')
            try:
                f(*args, **kwargs)
                if not len(l) > 0:
                    raise AssertionError("No warning raised when calling %s"
                            % f.__name__)
                if not l[0].category is DeprecationWarning:
                    raise AssertionError("First warning for %s is not a " \
                            "DeprecationWarning( is %s)" % (f.__name__, l[0]))
            finally:
                ctx.__exit__()

        if callable(conditional):
            cond = conditional()
        else:
            cond = conditional
        if cond:
            return nose.tools.make_decorator(f)(_deprecated_imp)
        else:
            return f
    return deprecate_decorator

Response: A function decorator that marks a test as deprecated.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def list_profiles_in(path):
    files = os.listdir(path)
    profiles = []
    for f in files:
        full_path = os.path.join(path, f)
        if os.path.isdir(full_path) and f.startswith('profile_'):
            profiles.append(f.split('_',1)[-1])
    return profiles

Response: list profiles in a given root directory


Instruction:
Write a Python 3 script to
list profiles that are bundled with IPython.

Response:
def list_bundled_profiles():
    """list profiles that are bundled with IPython."""
    path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
    files = os.listdir(path)
    profiles = []
    for profile in files:
        full_path = os.path.join(path, profile)
        if os.path.isdir(full_path) and profile != "__pycache__":
            profiles.append(profile)
    return profiles


Instruction:
How would you implement a function in Python 3 that
ensures that the directory at path is created.

Response:
def _bypass_ensure_directory(path, mode=0o777):
    """Sandbox-bypassing version of ensure_directory()"""
    if not WRITE_SUPPORT:
        raise IOError('"os.mkdir" not supported on this platform.')
    dirname, filename = split(path)
    if dirname and filename and not isdir(dirname):
        _bypass_ensure_directory(dirname)
        mkdir(dirname, mode)


Instruction:
Write a Python 3 script for
finding a distribution matching requirement req.

Response:
def find(self, req):
        """Find a distribution matching requirement `req`

        If there is an active distribution for the requested project, this
        returns it as long as it meets the version requirement specified by
        `req`.  But, if there is an active distribution for the project and it
        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
        If there is no active distribution for the requested project, ``None``
        is returned.
        """
        dist = self.by_key.get(req.key)
        if dist is not None and dist not in req:
            # XXX add more info
            raise VersionConflict(dist, req)
        else:
            return dist


Instruction:
Explain what the following Python 3 code does
def resolve(self, requirements, env=None, installer=None,
            replace_conflicting=False):
        """List all distributions needed to (recursively) meet `requirements`

        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
        if supplied, should be an ``Environment`` instance.  If
        not supplied, it defaults to all distributions available within any
        entry or distribution in the working set.  `installer`, if supplied,
        will be invoked with each requirement that cannot be met by an
        already-installed distribution; it should return a ``Distribution`` or
        ``None``.

        Unless `replace_conflicting=True`, raises a VersionConflict exception if
        any requirements are found on the path that have the correct name but
        the wrong version.  Otherwise, if an `installer` is supplied it will be
        invoked to obtain the correct version of the requirement and activate
        it.
        """

        # set up the stack
        requirements = list(requirements)[::-1]
        # set of processed requirements
        processed = {}
        # key -> dist
        best = {}
        to_activate = []

        # Mapping of requirement to set of distributions that required it;
        # useful for reporting info about conflicts.
        required_by = collections.defaultdict(set)

        while requirements:
            # process dependencies breadth-first
            req = requirements.pop(0)
            if req in processed:
                # Ignore cyclic or redundant dependencies
                continue
            dist = best.get(req.key)
            if dist is None:
                # Find the best distribution and add it to the map
                dist = self.by_key.get(req.key)
                if dist is None or (dist not in req and replace_conflicting):
                    ws = self
                    if env is None:
                        if dist is None:
                            env = Environment(self.entries)
                        else:
                            # Use an empty environment and workingset to avoid
                            # any further conflicts with the conflicting
                            # distribution
                            env = Environment([])
                            ws = WorkingSet([])
                    dist = best[req.key] = env.best_match(req, ws, installer)
                    if dist is None:
                        #msg = ("The '%s' distribution was not found on this "
                        #       "system, and is required by this application.")
                        #raise DistributionNotFound(msg % req)

                        # unfortunately, zc.buildout uses a str(err)
                        # to get the name of the distribution here..
                        raise DistributionNotFound(req)
                to_activate.append(dist)
            if dist not in req:
                # Oops, the "best" so far conflicts with a dependency
                tmpl = "%s is installed but %s is required by %s"
                args = dist, req, list(required_by.get(req, []))
                raise VersionConflict(tmpl % args)

            # push the new requirements onto the stack
            new_requirements = dist.requires(req.extras)[::-1]
            requirements.extend(new_requirements)

            # Register the new requirements needed by req
            for new_requirement in new_requirements:
                required_by[new_requirement].add(req.project_name)

            processed[req] = True

        # return list of distros to activate
        return to_activate

Response: Resolves all of the requirements in the working set.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_invalid_marker(cls, text):
        try:
            cls.evaluate_marker(text)
        except SyntaxError:
            return cls.normalize_exception(sys.exc_info()[1])
        return False

Response:
Validate text as a PEP 426 environment marker ; return an exception
            if invalid or False otherwise.