def set_custom_exc(self, exc_tuple, handler):

assert type(exc_tuple)==type(()) ,"<STR_LIT>"<EOL>def dummy_handler(self,etype,value,tb,tb_offset=None):<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>',etype)<EOL>print('<STR_LIT>',value)<EOL>print('<STR_LIT>',tb)<EOL><DEDENT>def validate_stb(stb):<EOL><INDENT>"""<STR_LIT>"""<EOL>msg = "<STR_LIT>" % stb<EOL>if stb is None:<EOL><INDENT>return []<EOL><DEDENT>elif isinstance(stb, str):<EOL><INDENT>return [stb]<EOL><DEDENT>elif not isinstance(stb, list):<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT>for line in stb:<EOL><INDENT>if not isinstance(line, str):<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT><DEDENT>return stb<EOL><DEDENT>if handler is None:<EOL><INDENT>wrapped = dummy_handler<EOL><DEDENT>else:<EOL><INDENT>def wrapped(self,etype,value,tb,tb_offset=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>stb = handler(self,etype,value,tb,tb_offset=tb_offset)<EOL>return validate_stb(stb)<EOL><DEDENT>except:<EOL><INDENT>self.set_custom_exc((), None)<EOL>print("<STR_LIT>", file=io.stderr)<EOL>stb = self.InteractiveTB.structured_traceback(*sys.exc_info())<EOL>print(self.InteractiveTB.stb2text(stb), file=io.stdout)<EOL>print("<STR_LIT>", file=io.stdout)<EOL>stb = self.InteractiveTB.structured_traceback(<EOL>(etype,value,tb), tb_offset=tb_offset<EOL>)<EOL><DEDENT>return stb<EOL><DEDENT><DEDENT>self.CustomTB = types.MethodType(wrapped,self)<EOL>self.custom_exceptions = exc_tuple<EOL>

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.


if value != <NUM_LIT:0> and not self.has_readline:<EOL><INDENT>if os.name == '<STR_LIT>':<EOL><INDENT>warn("<STR_LIT>")<EOL><DEDENT>self.autoindent = <NUM_LIT:0><EOL>return<EOL><DEDENT>if value is None:<EOL><INDENT>self.autoindent = not self.autoindent<EOL><DEDENT>else:<EOL><INDENT>self.autoindent = value<EOL><DEDENT>

Set the autoindent flag, checking for readline support.

        If called with no arguments, it acts as a toggle.


self._main_ns_cache[os.path.abspath(fname)] = ns.copy()<EOL>

Cache a main module's namespace.

        When scripts are executed via %run, we must keep a reference to the
        namespace of their __main__ module (a FakeModule instance) around so
        that Python doesn't clear it, rendering objects defined therein
        useless.

        This method keeps said reference in a private dict, keyed by the
        absolute path of the module object (which corresponds to the script
        path).  This way, for multiple executions of the same script we only
        keep one copy of the namespace (the last one), thus preventing memory
        leaks from old references while allowing the objects from the last
        execution to be accessible.

        Note: we can not allow the actual FakeModule instances to be deleted,
        because of how Python tears down modules (it hard-sets all their
        references to None without regard for reference counts).  This method
        must therefore make a *copy* of the given namespace, to allow the
        original module's __dict__ to be cleared and reused.

        Parameters
        ----------
          ns : a namespace (a dict, typically)

          fname : str
            Filename associated with the namespace.

        Examples
        --------

        In [10]: import IPython

        In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)

        In [12]: IPython.__file__ in _ip._main_ns_cache
        Out[12]: True


if frame:<EOL><INDENT>self.Completer.namespace = frame.f_locals<EOL>self.Completer.global_namespace = frame.f_globals<EOL><DEDENT>else:<EOL><INDENT>self.Completer.namespace = self.user_ns<EOL>self.Completer.global_namespace = self.user_global_ns<EOL><DEDENT>


def del_var(self, varname, by_name=False):

if varname in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>" % varname)<EOL><DEDENT>ns_refs = self.all_ns_refs<EOL>if by_name:                    <EOL><INDENT>for ns in ns_refs:<EOL><INDENT>try:<EOL><INDENT>del ns[varname]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>else:                         <EOL><INDENT>try:<EOL><INDENT>obj = self.user_ns[varname]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise NameError("<STR_LIT>" % varname)<EOL><DEDENT>ns_refs.append(self.history_manager.output_hist)<EOL>for ns in ns_refs:<EOL><INDENT>to_delete = [n for n, o in ns.items() if o is obj]<EOL>for name in to_delete:<EOL><INDENT>del ns[name]<EOL><DEDENT><DEDENT>for name in ('<STR_LIT:_>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if getattr(self.displayhook, name) is obj:<EOL><INDENT>setattr(self.displayhook, name, None)<EOL><DEDENT><DEDENT><DEDENT>

Delete a variable from the various namespaces, so that, as
        far as possible, we're not keeping any hidden references to it.

        Parameters
        ----------
        varname : str
            The name of the variable to delete.
        by_name : bool
            If True, delete variables with the given name in each
            namespace. If False (default), find the variable in the user
            namespace, and delete references to it.


def _inspect(self, meth, oname, namespaces=None, **kw):

info = self._object_find(oname, namespaces)<EOL>if info.found:<EOL><INDENT>pmethod = getattr(self.inspector, meth)<EOL>formatter = format_screen if info.ismagic else None<EOL>if meth == '<STR_LIT>':<EOL><INDENT>pmethod(info.obj, oname, formatter)<EOL><DEDENT>elif meth == '<STR_LIT>':<EOL><INDENT>pmethod(info.obj, oname, formatter, info, **kw)<EOL><DEDENT>else:<EOL><INDENT>pmethod(info.obj, oname)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % oname)<EOL>return '<STR_LIT>'<EOL><DEDENT>

Generic interface to the inspector system.

        This function is meant to be called by pdef, pdoc & friends.


This will be executed at the time of exit.

        Cleanup operations and saving of persistent data that is done
        unconditionally by IPython should be performed here.

        For things that may depend on startup flags or platform specifics (such
        as having readline or not), register a separate atexit function in the
        code that has the appropriate information, rather than trying to
        clutter


if self.embed:<EOL><INDENT>super(Image,self).reload()<EOL><DEDENT>


raw = kwargs.pop('<STR_LIT>',False)<EOL>if raw:<EOL><INDENT>for obj in objs:<EOL><INDENT>publish_latex(obj)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>display(*objs, include=['<STR_LIT>','<STR_LIT>'])<EOL><DEDENT>

Display the LaTeX representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw latex data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]


def __init__(self, data=None, url=None, filename=None, lib=None, css=None):

if isinstance(lib, basestring):<EOL><INDENT>lib = [lib]<EOL><DEDENT>elif lib is None:<EOL><INDENT>lib = []<EOL><DEDENT>if isinstance(css, basestring):<EOL><INDENT>css = [css]<EOL><DEDENT>elif css is None:<EOL><INDENT>css = []<EOL><DEDENT>if not isinstance(lib, (list,tuple)):<EOL><INDENT>raise TypeError('<STR_LIT>' % lib)<EOL><DEDENT>if not isinstance(css, (list,tuple)):<EOL><INDENT>raise TypeError('<STR_LIT>' % css)<EOL><DEDENT>self.lib = lib<EOL>self.css = css<EOL>super(Javascript, self).__init__(data=data, url=url, filename=filename)<EOL>

Create a Javascript display object given raw data.

        When this object is returned by an expression or passed to the
        display function, it will result in the data being displayed
        in the frontend. If the data is a URL, the data will first be
        downloaded and then displayed.

        In the Notebook, the containing element will be available as `element`,
        and jQuery will be available.  The output area starts hidden, so if
        the js appends content to `element` that should be visible, then
        it must call `container.show()` to unhide the area.

        Parameters
        ----------
        data : unicode, str or bytes
            The Javascript source code or a URL to download it from.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        lib : list or str
            A sequence of Javascript library URLs to load asynchronously before
            running the source code. The full URLs of the libraries should
            be given. A single Javascript library URL can also be given as a
            string.
        css: : list or str
            A sequence of css files to load before running the source code.
            The full URLs of the css files should be give. A single css URL
            can also be given as a string.


include = kwargs.get('<STR_LIT>')<EOL>exclude = kwargs.get('<STR_LIT>')<EOL>from IPython.core.interactiveshell import InteractiveShell<EOL>inst = InteractiveShell.instance()<EOL>format = inst.display_formatter.format<EOL>publish = inst.display_pub.publish<EOL>for obj in objs:<EOL><INDENT>format_dict = format(obj, include=include, exclude=exclude)<EOL>publish('<STR_LIT>', format_dict)<EOL><DEDENT>

Display a Python object in all frontends.

    By default all representations will be computed and sent to the frontends.
    Frontends can decide which representation is used and how.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display.
    include : list or tuple, optional
        A list of format type strings (MIME types) to include in the
        format data dict. If this is set *only* the format types included
        in this list will be computed.
    exclude : list or tuple, optional
        A list of format type string (MIME types) to exclue in the format
        data dict. If this is set all format types will be computed,
        except for those included in this argument.


def __init__(self, data=None, url=None, filename=None, format=u'<STR_LIT>', embed=None):

if filename is not None:<EOL><INDENT>ext = self._find_ext(filename)<EOL><DEDENT>elif url is not None:<EOL><INDENT>ext = self._find_ext(url)<EOL><DEDENT>elif data.startswith('<STR_LIT:http>'):<EOL><INDENT>ext = self._find_ext(data)<EOL><DEDENT>else:<EOL><INDENT>ext = None<EOL><DEDENT>if ext is not None:<EOL><INDENT>if ext == u'<STR_LIT>' or ext == u'<STR_LIT>':<EOL><INDENT>format = u'<STR_LIT>'<EOL><DEDENT>if ext == u'<STR_LIT>':<EOL><INDENT>format = u'<STR_LIT>'<EOL><DEDENT><DEDENT>self.format = unicode(format).lower()<EOL>self.embed = embed if embed is not None else (url is None)<EOL>super(Image, self).__init__(data=data, url=url, filename=filename)<EOL>

Create a display an PNG/JPEG image given raw data.

        When this object is returned by an expression or passed to the
        display function, it will result in the image being displayed
        in the frontend.

        Parameters
        ----------
        data : unicode, str or bytes
            The raw data or a URL to download the data from.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        format : unicode
            The format of the image data (png/jpeg/jpg). If a filename or URL is given
            for format will be inferred from the filename extension.
        embed : bool
            Should the image data be embedded using a data URI (True) or be
            loaded using an <img> tag. Set this to True if you want the image
            to be viewable later with no internet connection in the notebook.

            Default is `True`, unless the keyword argument `url` is set, then
            default value is `False`.

            Note that QtConsole is not able to display images if `embed` is set to `False`

        Examples
        --------
        # embed implicitly True, works in qtconsole and notebook
        Image('http://www.google.fr/images/srpr/logo3w.png')

        # embed implicitly False, does not works in qtconsole but works in notebook if
        # internet connection available
        Image(url='http://www.google.fr/images/srpr/logo3w.png')


cls.registered = True<EOL>cls.magics = dict(line = magics['<STR_LIT>'],<EOL>cell = magics['<STR_LIT>'])<EOL>magics['<STR_LIT>'] = {}<EOL>magics['<STR_LIT>'] = {}<EOL>return cls<EOL>

Class decorator for all subclasses of the main Magics class.

    Any class that subclasses Magics *must* also apply this decorator, to
    ensure that all the methods that have been decorated as line/cell magics
    get correctly registered in the class instance.  This is necessary because
    when method decorators run, the class does not exist yet, so they
    temporarily store their information into a module global.  Application of
    this class decorator copies that global data to the class instance and
    clears the global.

    Obviously, this mechanism is not thread-safe, which means that the
    *creation* of subclasses of Magic should only be done in a single-thread
    context.  Instantiation of the classes has no restrictions.  Given that
    these classes are typically created at IPython startup time and before user
    application code becomes active, in practice this should not pose any
    problems.


print('<STR_LIT>')<EOL>print(oinspect.getdoc(func))<EOL>

Print docstring if incorrect arguments were passed


<EOL>escape_re = re.compile(r'<STR_LIT>',re.MULTILINE)<EOL>cmd_name_re = re.compile(r'<STR_LIT>' % ESC_MAGIC,<EOL>re.MULTILINE)<EOL>cmd_re = re.compile(r'<STR_LIT>' % ESC_MAGIC,<EOL>re.MULTILINE)<EOL>par_re = re.compile(r'<STR_LIT>',re.MULTILINE)<EOL>newline_re = re.compile(r'<STR_LIT>')<EOL>strng = cmd_name_re.sub(r'<STR_LIT>',<EOL>strng)<EOL>strng = cmd_re.sub(r'<STR_LIT>',strng)<EOL>strng = par_re.sub(r'<STR_LIT>',strng)<EOL>strng = escape_re.sub(r'<STR_LIT>',strng)<EOL>strng = newline_re.sub(r'<STR_LIT>',strng)<EOL>return strng<EOL>


if fn not in self.lsmagic():<EOL><INDENT>error("<STR_LIT>" % fn)<EOL><DEDENT>self.options_table[fn] = optstr<EOL>

Make an entry in the options_table for fn, with value optstr


<EOL>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>obj = obj.__wrapped__<EOL><DEDENT>try:<EOL><INDENT>try:<EOL><INDENT>lineno = inspect.getsourcelines(obj)[<NUM_LIT:1>]<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>lineno = inspect.getsourcelines(obj.__class__)[<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>return lineno<EOL>

Find the line number in a file where an object was defined.

    This is essentially a robust wrapper around `inspect.getsourcelines`.

    Returns None if no file can be found.

    Parameters
    ----------
    obj : any Python object

    Returns
    -------
    lineno : int
      The line number where the object definition starts.


<EOL>argspec = oinfo.get('<STR_LIT>')<EOL>if argspec is None:<EOL><INDENT>call_line = None<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>has_self = argspec['<STR_LIT:args>'][<NUM_LIT:0>] == '<STR_LIT>'<EOL><DEDENT>except (KeyError, IndexError):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if has_self:<EOL><INDENT>argspec['<STR_LIT:args>'] = argspec['<STR_LIT:args>'][<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>call_line = oinfo['<STR_LIT:name>']+format_argspec(argspec)<EOL><DEDENT>doc = oinfo.get('<STR_LIT>')<EOL>if doc is None:<EOL><INDENT>doc = oinfo.get('<STR_LIT>')<EOL><DEDENT>if doc is None:<EOL><INDENT>doc = oinfo.get('<STR_LIT>','<STR_LIT>')<EOL><DEDENT>return call_line, doc<EOL>

Extract call tip data from an oinfo dict.

    Parameters
    ----------
    oinfo : dict

    format_call : bool, optional
      If True, the call line is formatted and returned as a string.  If not, a
      tuple of (name, argspec) is returned.

    Returns
    -------
    call_info : None, str or (str, dict) tuple.
      When format_call is True, the whole call information is formattted as a
      single string.  Otherwise, the object's name and its argspec dict are
      returned.  If no call information is available, None is returned.

    docstring : str or None
      The most relevant docstring for calling purposes is returned, if
      available.  The priority is: call docstring for callable instances, then
      constructor docstring for classes, then main object's docstring otherwise
      (regular functions).


if not callable(obj):<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>header = '<STR_LIT>'<EOL>if inspect.isclass(obj):<EOL><INDENT>header = self.__head('<STR_LIT>')<EOL>obj = obj.__init__<EOL><DEDENT>elif (not py3compat.PY3) and type(obj) is types.InstanceType:<EOL><INDENT>obj = obj.__call__<EOL><DEDENT>output = self._getdef(obj,oname)<EOL>if output is None:<EOL><INDENT>self.noinfo('<STR_LIT>',oname)<EOL><DEDENT>else:<EOL><INDENT>print(header,self.format(output), end='<STR_LIT:U+0020>', file=io.stdout)<EOL><DEDENT>

Print the definition header for any callable object.

        If the object is a class, print the constructor information.


fixed_records = []<EOL>for frame, filename, line_no, func_name, lines, index in records:<EOL><INDENT>better_fn = frame.f_globals.get('<STR_LIT>', None)<EOL>if isinstance(better_fn, str):<EOL><INDENT>filename = better_fn<EOL><DEDENT>fixed_records.append((frame, filename, line_no, func_name, lines, index))<EOL><DEDENT>return fixed_records<EOL>

Try to fix the filenames in each record from inspect.getinnerframes().

    Particularly, modules loaded from within zip files have useless filenames
    attached to their code object, and inspect.getinnerframes() just uses it.


return self.tb_join_char.join(stb)<EOL>

Convert a structured traceback (a list) to a string.


def structured_traceback(self, etype, evalue, etb, tb_offset=None,<EOL>context=<NUM_LIT:5>):

tb_offset = self.tb_offset if tb_offset is None else tb_offset<EOL>try:<EOL><INDENT>etype = etype.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>Colors        = self.Colors   <EOL>ColorsNormal  = Colors.Normal  <EOL>col_scheme    = self.color_scheme_table.active_scheme_name<EOL>indent        = '<STR_LIT:U+0020>'*INDENT_SIZE<EOL>em_normal     = '<STR_LIT>' % (Colors.valEm, indent,ColorsNormal)<EOL>undefined     = '<STR_LIT>' % (Colors.em, ColorsNormal)<EOL>exc = '<STR_LIT>' % (Colors.excName,etype,ColorsNormal)<EOL>def text_repr(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return pydoc.text.repr(value)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>try:<EOL><INDENT>return repr(value)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>try:<EOL><INDENT>name = getattr(value, '<STR_LIT>', None)<EOL>if name:<EOL><INDENT>return text_repr(name)<EOL><DEDENT>klass = getattr(value, '<STR_LIT>', None)<EOL>if klass:<EOL><INDENT>return '<STR_LIT>' % text_repr(klass)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT><DEDENT>def eqrepr(value, repr=text_repr): return '<STR_LIT>' % repr(value)<EOL>def nullrepr(value, repr=text_repr): return '<STR_LIT>'<EOL>try:<EOL><INDENT>etype = etype.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>if self.long_header:<EOL><INDENT>pyver = '<STR_LIT>' + sys.version.split()[<NUM_LIT:0>] + '<STR_LIT>' + sys.executable<EOL>date = time.ctime(time.time())<EOL>head = '<STR_LIT>' % (Colors.topline, '<STR_LIT:->'*<NUM_LIT>, ColorsNormal,<EOL>exc, '<STR_LIT:U+0020>'*(<NUM_LIT>-len(str(etype))-len(pyver)),<EOL>pyver, date.rjust(<NUM_LIT>) )<EOL>head += "<STR_LIT>""<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>head = '<STR_LIT>' % (Colors.topline, '<STR_LIT:->'*<NUM_LIT>, ColorsNormal,exc,<EOL>'<STR_LIT>'.rjust(<NUM_LIT> - len(str(etype)) ) )<EOL><DEDENT>frames = []<EOL>try:<EOL><INDENT>records = _fixed_getinnerframes(etb, context, tb_offset)<EOL><DEDENT>except:<EOL><INDENT>inspect_error()<EOL>traceback.print_exc(file=self.ostream)<EOL>info('<STR_LIT>')<EOL>return '<STR_LIT>'<EOL><DEDENT>tpl_link       = '<STR_LIT>' % (Colors.filenameEm,ColorsNormal)<EOL>tpl_call       = '<STR_LIT>' % (Colors.vName, Colors.valEm,<EOL>ColorsNormal)<EOL>tpl_call_fail  = '<STR_LIT>' %(Colors.vName, Colors.valEm, ColorsNormal)<EOL>tpl_local_var  = '<STR_LIT>' % (Colors.vName, ColorsNormal)<EOL>tpl_global_var = '<STR_LIT>' % (Colors.em, ColorsNormal,<EOL>Colors.vName, ColorsNormal)<EOL>tpl_name_val   = '<STR_LIT>' % (Colors.valEm, ColorsNormal)<EOL>tpl_line       = '<STR_LIT>' % (Colors.lineno, ColorsNormal)<EOL>tpl_line_em    = '<STR_LIT>' % (Colors.linenoEm,Colors.line,<EOL>ColorsNormal)<EOL>abspath = os.path.abspath<EOL>for frame, file, lnum, func, lines, index in records:<EOL><INDENT>if not file:<EOL><INDENT>file = '<STR_LIT:?>'<EOL><DEDENT>elif not(file.startswith("<STR_LIT:<>") and file.endswith("<STR_LIT:>>")):<EOL><INDENT>try:<EOL><INDENT>file = abspath(file)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>link = tpl_link % file<EOL>args, varargs, varkw, locals = inspect.getargvalues(frame)<EOL>if func == '<STR_LIT:?>':<EOL><INDENT>call = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>var_repr = self.include_vars and eqrepr or nullrepr<EOL>try:<EOL><INDENT>call = tpl_call % (func,inspect.formatargvalues(args,<EOL>varargs, varkw,<EOL>locals,formatvalue=var_repr))<EOL><DEDENT>except KeyError:<EOL><INDENT>call = tpl_call_fail % func<EOL><DEDENT><DEDENT>if file.endswith(('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>frames.append('<STR_LIT>' % (link,call))<EOL>continue<EOL><DEDENT>elif file.endswith(('<STR_LIT>','<STR_LIT>')):<EOL><INDENT>file = pyfile.source_from_cache(file)<EOL><DEDENT>def linereader(file=file, lnum=[lnum], getline=linecache.getline):<EOL><INDENT>line = getline(file, lnum[<NUM_LIT:0>])<EOL>lnum[<NUM_LIT:0>] += <NUM_LIT:1><EOL>return line<EOL><DEDENT>try:<EOL><INDENT>names = []<EOL>name_cont = False<EOL>for token_type, token, start, end, line in generate_tokens(linereader):<EOL><INDENT>if token_type == tokenize.NAME and token not in keyword.kwlist:<EOL><INDENT>if name_cont:<EOL><INDENT>try:<EOL><INDENT>names[-<NUM_LIT:1>].append(token)<EOL><DEDENT>except IndexError:<EOL><INDENT>names.append([token])<EOL><DEDENT>name_cont = False<EOL><DEDENT>else:<EOL><INDENT>names.append([token])<EOL><DEDENT><DEDENT>elif token == '<STR_LIT:.>':<EOL><INDENT>name_cont = True<EOL><DEDENT>elif token_type == tokenize.NEWLINE:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>except (IndexError, UnicodeDecodeError):<EOL><INDENT>pass<EOL><DEDENT>except tokenize.TokenError as msg:<EOL><INDENT>_m = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % msg)<EOL>error(_m)<EOL><DEDENT>names = ['<STR_LIT:.>'.join(n) for n in names]<EOL>unique_names = uniq_stable(names)<EOL>lvals = []<EOL>if self.include_vars:<EOL><INDENT>for name_full in unique_names:<EOL><INDENT>name_base = name_full.split('<STR_LIT:.>',<NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if name_base in frame.f_code.co_varnames:<EOL><INDENT>if name_base in locals:<EOL><INDENT>try:<EOL><INDENT>value = repr(eval(name_full,locals))<EOL><DEDENT>except:<EOL><INDENT>value = undefined<EOL><DEDENT><DEDENT>else:<EOL><INDENT>value = undefined<EOL><DEDENT>name = tpl_local_var % name_full<EOL><DEDENT>else:<EOL><INDENT>if name_base in frame.f_globals:<EOL><INDENT>try:<EOL><INDENT>value = repr(eval(name_full,frame.f_globals))<EOL><DEDENT>except:<EOL><INDENT>value = undefined<EOL><DEDENT><DEDENT>else:<EOL><INDENT>value = undefined<EOL><DEDENT>name = tpl_global_var % name_full<EOL><DEDENT>lvals.append(tpl_name_val % (name,value))<EOL><DEDENT><DEDENT>if lvals:<EOL><INDENT>lvals = '<STR_LIT>' % (indent,em_normal.join(lvals))<EOL><DEDENT>else:<EOL><INDENT>lvals = '<STR_LIT>'<EOL><DEDENT>level = '<STR_LIT>' % (link,call)<EOL>if index is None:<EOL><INDENT>frames.append(level)<EOL><DEDENT>else:<EOL><INDENT>frames.append('<STR_LIT>' % (level,'<STR_LIT>'.join(<EOL>_format_traceback_lines(lnum,index,lines,Colors,lvals,<EOL>col_scheme))))<EOL><DEDENT><DEDENT>try:<EOL><INDENT>etype_str,evalue_str = list(map(str,(etype,evalue)))<EOL><DEDENT>except:<EOL><INDENT>etype,evalue = str,sys.exc_info()[:<NUM_LIT:2>]<EOL>etype_str,evalue_str = list(map(str,(etype,evalue)))<EOL><DEDENT>exception = ['<STR_LIT>' % (Colors.excName, etype_str,<EOL>ColorsNormal, evalue_str)]<EOL>if (not py3compat.PY3) and type(evalue) is types.InstanceType:<EOL><INDENT>try:<EOL><INDENT>names = [w for w in dir(evalue) if isinstance(w, str)]<EOL><DEDENT>except:<EOL><INDENT>_m = '<STR_LIT>'<EOL>exception.append(_m % (Colors.excName,ColorsNormal))<EOL>etype_str,evalue_str = list(map(str,sys.exc_info()[:<NUM_LIT:2>]))<EOL>exception.append('<STR_LIT>' % (Colors.excName,etype_str,<EOL>ColorsNormal, evalue_str))<EOL>names = []<EOL><DEDENT>for name in names:<EOL><INDENT>value = text_repr(getattr(evalue, name))<EOL>exception.append('<STR_LIT>' % (indent, name, value))<EOL><DEDENT><DEDENT>if records:<EOL><INDENT>filepath, lnum = records[-<NUM_LIT:1>][<NUM_LIT:1>:<NUM_LIT:3>]<EOL>filepath = os.path.abspath(filepath)<EOL>ipinst = ipapi.get()<EOL>if ipinst is not None:<EOL><INDENT>ipinst.hooks.synchronize_with_editor(filepath, lnum, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>return [head] + frames + ['<STR_LIT>'.join(exception[<NUM_LIT:0>])]<EOL>

Return a nice text document describing the traceback.


def __init__(self,color_scheme = '<STR_LIT>', call_pdb=False, ostream=None,<EOL>tb_offset=<NUM_LIT:0>, long_header=False, include_vars=True,<EOL>check_cache=None):

TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,<EOL>ostream=ostream)<EOL>self.tb_offset = tb_offset<EOL>self.long_header = long_header<EOL>self.include_vars = include_vars<EOL>if check_cache is None:<EOL><INDENT>check_cache = linecache.checkcache<EOL><DEDENT>self.check_cache = check_cache<EOL>

Specify traceback offset, headers and color scheme.

        Define how many frames to drop from the tracebacks. Calling it with
        tb_offset=1 allows use of this handler in interpreters which will have
        their own code at the top of the traceback (VerboseTB will first
        remove that frame before printing the traceback info).


if force or self.call_pdb:<EOL><INDENT>if self.pdb is None:<EOL><INDENT>self.pdb = debugger.Pdb(<EOL>self.color_scheme_table.active_scheme_name)<EOL><DEDENT>display_trap = DisplayTrap(hook=sys.__displayhook__)<EOL>with display_trap:<EOL><INDENT>self.pdb.reset()<EOL>if hasattr(self,'<STR_LIT>') and self.tb is not None:<EOL><INDENT>etb = self.tb<EOL><DEDENT>else:<EOL><INDENT>etb = self.tb = sys.last_traceback<EOL><DEDENT>while self.tb is not None and self.tb.tb_next is not None:<EOL><INDENT>self.tb = self.tb.tb_next<EOL><DEDENT>if etb and etb.tb_next:<EOL><INDENT>etb = etb.tb_next<EOL><DEDENT>self.pdb.botframe = etb.tb_frame<EOL>self.pdb.interaction(self.tb.tb_frame, self.tb)<EOL><DEDENT><DEDENT>if hasattr(self,'<STR_LIT>'):<EOL><INDENT>del self.tb<EOL><DEDENT>

Call up the pdb debugger if desired, always clean up the tb
        reference.

        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 the call_pdb flag is set, the pdb interactive debugger is
        invoked. In all cases, the self.tb reference to the current traceback
        is deleted to prevent lingering references which hamper memory
        management.

        Note that each call to pdb() does an 'import readline', so if your app
        requires a special setup for the readline completers, you'll have to
        fix that by hand after invoking the exception handler.


Print a message about internal inspect errors.

    These are unfortunately quite common.


return '<STR_LIT:\n>'.join(stb)<EOL>


<EOL>return line<EOL>

Default input prefilter

    This returns the line as unchanged, so that the interpreter
    knows that nothing was done and proceeds with "classic" prefiltering
    (%magics, !shell commands etc.).

    Note that leading whitespace is not passed to this hook. Prefilter
    can't alter indentation.


def editor(self, filename, linenum=None, wait=True):

<EOL>editor = self.editor<EOL>if linenum is None or editor=='<STR_LIT>':<EOL><INDENT>linemark = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>linemark = '<STR_LIT>' % int(linenum)<EOL><DEDENT>if '<STR_LIT:U+0020>' in editor and os.path.isfile(editor) and editor[<NUM_LIT:0>] != '<STR_LIT:">':<EOL><INDENT>editor = '<STR_LIT>' % editor<EOL><DEDENT>proc = subprocess.Popen('<STR_LIT>' % (editor, linemark, filename),<EOL>shell=True)<EOL>if wait and proc.wait() != <NUM_LIT:0>:<EOL><INDENT>raise TryNext()<EOL><DEDENT>

Open the default editor at the given filename and linenumber.

    This is IPython's default editor hook, you can use it as an example to
    write your own modified one.  To set your own editor function as the
    new editor hook, call ip.set_hook('editor',yourfunc).


last_exc = TryNext()<EOL>for prio,cmd in self.chain:<EOL><INDENT>try:<EOL><INDENT>return cmd(*args, **kw)<EOL><DEDENT>except TryNext as exc:<EOL><INDENT>last_exc = exc<EOL><DEDENT><DEDENT>raise last_exc<EOL>

Command chain is called just like normal func.

        This will call all funcs in chain with the same args as were given to
        this function, and return the result of first func that didn't raise
        TryNext


def ast_parse(self, source, filename='<STR_LIT>', symbol='<STR_LIT>'):

return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, <NUM_LIT:1>)<EOL>

Parse code to an AST with the current compiler flags active.

        Arguments are exactly the same as ast.parse (in the standard library),
        and are passed to the built-in compile function.


def cache(self, code, number=<NUM_LIT:0>):

name = code_name(code, number)<EOL>entry = (len(code), time.time(),<EOL>[line+'<STR_LIT:\n>' for line in code.splitlines()], name)<EOL>linecache.cache[name] = entry<EOL>linecache._ipython_cache[name] = entry<EOL>return name<EOL>

Make a name for a block of code, and cache the code.

        Parameters
        ----------
        code : str
          The Python source code to cache.
        number : int
          A number which forms part of the code's name. Used for the execution
          counter.

        Returns
        -------
        The name of the cached code (as a string). Pass this as the filename
        argument to compilation, so that tracebacks are correctly hooked up.


<EOL>linecache._checkcache_ori(*args)<EOL>linecache.cache.update(linecache._ipython_cache)<EOL>

Call linecache.checkcache() safely protecting our cached values.


try:<EOL><INDENT>location = self.config.ProfileDir.location<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>if self.auto_create or self.profile=='<STR_LIT:default>':<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>self.log.fatal("<STR_LIT>"%self.profile)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%p.location)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.fatal("<STR_LIT>"%self.profile)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%p.location)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.find_profile_dir(location, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>if self.auto_create:<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.create_profile_dir(location, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>self.log.fatal("<STR_LIT>"%location)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%location)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.fatal("<STR_LIT>"%location)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%location)<EOL><DEDENT><DEDENT>self.profile_dir = p<EOL>self.config_file_paths.append(p.location)<EOL>


self.crash_handler = self.crash_handler_class(self)<EOL>sys.excepthook = self.excepthook<EOL>def unset_crashhandler():<EOL><INDENT>sys.excepthook = sys.__excepthook__<EOL><DEDENT>atexit.register(unset_crashhandler)<EOL>

Create a crash handler, typically setting sys.excepthook to it.


remove_builtin = self.remove_builtin<EOL>for key, val in self._orig_builtins.iteritems():<EOL><INDENT>remove_builtin(key, val)<EOL><DEDENT>self._orig_builtins.clear()<EOL>self._builtins_added = False<EOL>

Remove any builtins which might have been added by add_builtins, or
        restore overwritten ones to their previous values.


add_builtin = self.add_builtin<EOL>for name, func in self.auto_builtins.iteritems():<EOL><INDENT>add_builtin(name, func)<EOL><DEDENT>

Store ipython references in the __builtin__ namespace.


return "<STR_LIT>".join([(ch in PROTECTABLES and '<STR_LIT:\\>' + ch or ch)<EOL>for ch in s])<EOL>

Escape a string to protect certain characters.


try:<EOL><INDENT>words = getattr(obj, '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>return []<EOL><DEDENT>return [w for w in words if isinstance(w, basestring)]<EOL>

returns the strings in the __all__ attribute


if state==<NUM_LIT:0>:<EOL><INDENT>self.line_buffer = line_buffer = self.readline.get_line_buffer()<EOL>cursor_pos = self.readline.get_endidx()<EOL>if not (self.dumb_terminal or line_buffer.strip()):<EOL><INDENT>self.readline.insert_text('<STR_LIT:\t>')<EOL>sys.stdout.flush()<EOL>return None<EOL><DEDENT>DEBUG = False<EOL>if DEBUG:<EOL><INDENT>try:<EOL><INDENT>self.complete(text, line_buffer, cursor_pos)<EOL><DEDENT>except:<EOL><INDENT>import traceback; traceback.print_exc()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.complete(text, line_buffer, cursor_pos)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>return self.matches[state]<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT>

Return the state-th possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        Parameters
        ----------
          text : string
            Text to perform the completion on.

          state : int
            Counter used by readline.


def complete(self, text=None, line_buffer=None, cursor_pos=None):

<EOL>if cursor_pos is None:<EOL><INDENT>cursor_pos = len(line_buffer) if text is None else len(text)<EOL><DEDENT>if not text:<EOL><INDENT>text = self.splitter.split_line(line_buffer, cursor_pos)<EOL><DEDENT>if line_buffer is None:<EOL><INDENT>line_buffer = text<EOL><DEDENT>self.line_buffer = line_buffer<EOL>self.text_until_cursor = self.line_buffer[:cursor_pos]<EOL>self.matches[:] = []<EOL>custom_res = self.dispatch_custom_completer(text)<EOL>if custom_res is not None:<EOL><INDENT>self.matches = custom_res<EOL><DEDENT>else:<EOL><INDENT>if self.merge_completions:<EOL><INDENT>self.matches = []<EOL>for matcher in self.matchers:<EOL><INDENT>try:<EOL><INDENT>self.matches.extend(matcher(text))<EOL><DEDENT>except:<EOL><INDENT>sys.excepthook(*sys.exc_info())<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for matcher in self.matchers:<EOL><INDENT>self.matches = matcher(text)<EOL>if self.matches:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.matches = sorted(set(self.matches))<EOL>return text, self.matches<EOL>

Find completions for the given text and line context.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        Note that both the text and the line_buffer are optional, but at least
        one of them must be given.

        Parameters
        ----------
          text : string, optional
            Text to perform the completion on.  If not given, the line buffer
            is split using the instance's CompletionSplitter object.

          line_buffer : string, optional
            If not given, the completer attempts to obtain the current line
            buffer via readline.  This keyword allows clients which are
            requesting for text completions in non-readline contexts to inform
            the completer of the entire text.

          cursor_pos : int, optional
            Index of the cursor in the full line buffer.  Should be provided by
            remote frontends where kernel has no access to frontend state.

        Returns
        -------
        text : str
          Text that was actually used in the completion.

        matches : list
          A list of completion matches.


expr = '<STR_LIT:[>' + '<STR_LIT>'.join('<STR_LIT:\\>'+ c for c in delims) + '<STR_LIT:]>'<EOL>self._delim_re = re.compile(expr)<EOL>self._delims = delims<EOL>self._delim_expr = expr<EOL>


<EOL>lsm = self.shell.magics_manager.lsmagic()<EOL>line_magics = lsm['<STR_LIT>']<EOL>cell_magics = lsm['<STR_LIT>']<EOL>pre = self.magic_escape<EOL>pre2 = pre+pre<EOL>bare_text = text.lstrip(pre)<EOL>comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]<EOL>if not text.startswith(pre2):<EOL><INDENT>comp += [ pre+m for m in line_magics if m.startswith(bare_text)]<EOL><DEDENT>return comp<EOL>


startup_dir = self.profile_dir.startup_dir<EOL>startup_files = glob.glob(os.path.join(startup_dir, '<STR_LIT>'))<EOL>startup_files += glob.glob(os.path.join(startup_dir, '<STR_LIT>'))<EOL>if not startup_files:<EOL><INDENT>return<EOL><DEDENT>self.log.debug("<STR_LIT>", startup_dir)<EOL>try:<EOL><INDENT>for fname in sorted(startup_files):<EOL><INDENT>self._exec_file(fname)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>")<EOL>self.shell.showtraceback()<EOL><DEDENT>

Run files from profile startup directory


from IPython.core import page<EOL>page.page(gui_reference, auto_html=True)<EOL>

Show a basic reference about the GUI Console.


oldfunc = self.type_printers.get(typ, None)<EOL>if func is not None:<EOL><INDENT>self.type_printers[typ] = func<EOL><DEDENT>return oldfunc<EOL>

Add a format function for a given type.

        Parameters
        -----------
        typ : class
            The class of the object that will be formatted using `func`.
        func : callable
            The callable that will be called to compute the format data. The
            call signature of this function is simple, it must take the
            object to be formatted and return the raw data for the given
            format. Subclasses may use a different call signature for the
            `func` argument.


if self.enabled:<EOL><INDENT>obj_id = id(obj)<EOL>try:<EOL><INDENT>obj_class = getattr(obj, '<STR_LIT>', None) or type(obj)<EOL>try:<EOL><INDENT>printer = self.singleton_printers[obj_id]<EOL><DEDENT>except (TypeError, KeyError):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return printer(obj)<EOL><DEDENT>for cls in pretty._get_mro(obj_class):<EOL><INDENT>if cls in self.type_printers:<EOL><INDENT>return self.type_printers[cls](obj)<EOL><DEDENT>else:<EOL><INDENT>printer = self._in_deferred_types(cls)<EOL>if printer is not None:<EOL><INDENT>return printer(obj)<EOL><DEDENT><DEDENT><DEDENT>if hasattr(obj_class, self.print_method):<EOL><INDENT>printer = getattr(obj_class, self.print_method)<EOL>return printer(obj)<EOL><DEDENT>return None<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>


def _float_precision_changed(self, name, old, new):

if '<STR_LIT:%>' in new:<EOL><INDENT>fmt = new<EOL>try:<EOL><INDENT>fmt%<NUM_LIT><EOL><DEDENT>except Exception:<EOL><INDENT>raise ValueError("<STR_LIT>"%new)<EOL><DEDENT><DEDENT>elif new:<EOL><INDENT>try:<EOL><INDENT>i = int(new)<EOL>assert i >= <NUM_LIT:0><EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>"%new)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise ValueError("<STR_LIT>"%i)<EOL><DEDENT>fmt = '<STR_LIT>'%i<EOL>if '<STR_LIT>' in sys.modules:<EOL><INDENT>import numpy<EOL>numpy.set_printoptions(precision=i)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fmt = '<STR_LIT>'<EOL>if '<STR_LIT>' in sys.modules:<EOL><INDENT>import numpy<EOL>numpy.set_printoptions(precision=<NUM_LIT:8>)<EOL><DEDENT><DEDENT>self.float_format = fmt<EOL>

float_precision changed, set float_format accordingly.

        float_precision can be set by int or str.
        This will set float_format, after interpreting input.
        If numpy has been imported, numpy print precision will also be set.

        integer `n` sets format to '%.nf', otherwise, format set directly.

        An empty string returns to defaults (repr for float, 8 for numpy).

        This parameter can be set via the '%precision' magic.


return magic_func.parser.parse_argstring(argstring)<EOL>

Parse the string of arguments for the given magic function.


try:<EOL><INDENT>self.define_alias(name, cmd)<EOL><DEDENT>except AliasError as e:<EOL><INDENT>error("<STR_LIT>" % e)<EOL><DEDENT>

Define an alias, but don't raise on an AliasError.


<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>default_aliases = [('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL>if sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>ls_aliases = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>else:<EOL><INDENT>ls_aliases = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>default_aliases = default_aliases + ls_aliases<EOL><DEDENT>elif os.name in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>default_aliases = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>else:<EOL><INDENT>default_aliases = []<EOL><DEDENT>return default_aliases<EOL>

Return list of shell aliases to auto-define.


nargs = self.validate_alias(name, cmd)<EOL>self.alias_table[name] = (nargs, cmd)<EOL>

Define a new alias after validating it.

        This will raise an :exc:`AliasError` if there are validation
        problems.


from IPython.core.interactiveshell import InteractiveShell<EOL>return InteractiveShell.instance()<EOL>

Get the global InteractiveShell instance.


<EOL>if not fig.axes and not fig.lines:<EOL><INDENT>return<EOL><DEDENT>fc = fig.get_facecolor()<EOL>ec = fig.get_edgecolor()<EOL>fig.set_facecolor('<STR_LIT>')<EOL>fig.set_edgecolor('<STR_LIT>')<EOL>try:<EOL><INDENT>bytes_io = BytesIO()<EOL>fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='<STR_LIT>')<EOL>data = bytes_io.getvalue()<EOL><DEDENT>finally:<EOL><INDENT>fig.set_facecolor(fc)<EOL>fig.set_edgecolor(ec)<EOL><DEDENT>return data<EOL>

Convert a figure to svg or png for inline display.


def configure_inline_support(shell, backend, user_ns=None):

<EOL>try:<EOL><INDENT>from IPython.zmq.pylab.backend_inline import InlineBackend<EOL><DEDENT>except ImportError:<EOL><INDENT>return<EOL><DEDENT>user_ns = shell.user_ns if user_ns is None else user_ns<EOL>cfg = InlineBackend.instance(config=shell.config)<EOL>cfg.shell = shell<EOL>if cfg not in shell.configurables:<EOL><INDENT>shell.configurables.append(cfg)<EOL><DEDENT>if backend == backends['<STR_LIT>']:<EOL><INDENT>from IPython.zmq.pylab.backend_inline import flush_figures<EOL>from matplotlib import pyplot<EOL>shell.register_post_execute(flush_figures)<EOL>pyplot.rcParams.update(cfg.rc)<EOL>user_ns['<STR_LIT>'] = pyplot.figsize = figsize<EOL><DEDENT>fmt = cfg.figure_format<EOL>select_figure_format(shell, fmt)<EOL>from IPython.core.display import display<EOL>user_ns['<STR_LIT>'] = display<EOL>user_ns['<STR_LIT>'] = getfigs<EOL>

Configure an IPython shell object for matplotlib use.

    Parameters
    ----------
    shell : InteractiveShell instance

    backend : matplotlib backend

    user_ns : dict
      A namespace where all configured variables will be placed.  If not given,
      the `user_ns` attribute of the shell object is used.


import matplotlib<EOL>matplotlib.rcParams['<STR_LIT>'] = [sizex, sizey]<EOL>

Set the default figure size to be [sizex, sizey].

    This is just an easy to remember, convenience wrapper that sets::

      matplotlib.rcParams['figure.figsize'] = [sizex, sizey]


<EOL>s = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>exec(s, user_ns)<EOL>if import_all:<EOL><INDENT>s = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>exec(s, user_ns)<EOL><DEDENT>

Import the standard pylab symbols into user_ns.


if line_info.the_rest and line_info.the_rest[<NUM_LIT:0>] in '<STR_LIT>':<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

If the 'rest' of the line begins with a function call or pretty much
        any python operator, we should simply execute the line (regardless of
        whether or not there's a possible autocall expansion).  This avoids
        spurious (and very confusing) geattr() accesses.


def prefilter_lines(self, lines, continue_prompt=False):

llines = lines.rstrip('<STR_LIT:\n>').split('<STR_LIT:\n>')<EOL>if len(llines) > <NUM_LIT:1>:<EOL><INDENT>out = '<STR_LIT:\n>'.join([self.prefilter_line(line, lnum><NUM_LIT:0>)<EOL>for lnum, line in enumerate(llines) ])<EOL><DEDENT>else:<EOL><INDENT>out = self.prefilter_line(llines[<NUM_LIT:0>], continue_prompt)<EOL><DEDENT>return out<EOL>

Prefilter multiple input lines of text.

        This is the main entry point for prefiltering multiple lines of
        input.  This simply calls :meth:`prefilter_line` for each line of
        input.

        This covers cases where there are multiple lines in the user entry,
        which is the case when the user goes back to a multiline history
        entry and presses enter.


normal_handler = self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL>line = line_info.line<EOL>try:<EOL><INDENT>codeop.compile_command(line)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>if line[<NUM_LIT:0>]==ESC_HELP:<EOL><INDENT>line = line[<NUM_LIT:1>:]<EOL><DEDENT>elif line[-<NUM_LIT:1>]==ESC_HELP:<EOL><INDENT>line = line[:-<NUM_LIT:1>]<EOL><DEDENT>if line:<EOL><INDENT>self.shell.magic('<STR_LIT>' % line_info.ifun)<EOL><DEDENT>else:<EOL><INDENT>self.shell.show_usage()<EOL><DEDENT>return '<STR_LIT>' <EOL><DEDENT>except:<EOL><INDENT>raise<EOL>return normal_handler.handle(line_info)<EOL><DEDENT>else:<EOL><INDENT>return normal_handler.handle(line_info)<EOL><DEDENT>

Try to get some help for the object.

        obj? or ?obj   -> basic information.
        obj?? or ??obj -> more details.


def prefilter_line(self, line, continue_prompt=False):

<EOL>self.shell._last_input_line = line<EOL>if not line:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if not continue_prompt or (continue_prompt and self.multi_line_specials):<EOL><INDENT>line = self.transform_line(line, continue_prompt)<EOL><DEDENT>line_info = LineInfo(line, continue_prompt)<EOL>stripped = line.strip()<EOL>normal_handler = self.get_handler_by_name('<STR_LIT>')<EOL>if not stripped:<EOL><INDENT>if not continue_prompt:<EOL><INDENT>self.shell.displayhook.prompt_count -= <NUM_LIT:1><EOL><DEDENT>return normal_handler.handle(line_info)<EOL><DEDENT>if continue_prompt and not self.multi_line_specials:<EOL><INDENT>return normal_handler.handle(line_info)<EOL><DEDENT>prefiltered = self.prefilter_line_info(line_info)<EOL>return prefiltered<EOL>

Prefilter a single input line as text.

        This method prefilters a single line of text by calling the
        transformers and then the checkers/handlers.


def transform_line(self, line, continue_prompt):

for transformer in self.transformers:<EOL><INDENT>if transformer.enabled:<EOL><INDENT>line = transformer.transform(line, continue_prompt)<EOL><DEDENT><DEDENT>return line<EOL>

Calls the enabled transformers in order of increasing priority.


if line_info.the_rest:<EOL><INDENT>if line_info.the_rest[<NUM_LIT:0>] in '<STR_LIT>':<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Check to see if user is assigning to a var for the first time, in
        which case we want to avoid any sort of automagic / autocall games.

        This allows users to assign to either alias or magic names true python
        variables (the magic/alias systems always take second seat to true
        python code).  E.g. ls='hi', or ls,that=1,2


def register_handler(self, name, handler, esc_strings):

self._handlers[name] = handler<EOL>for esc_str in esc_strings:<EOL><INDENT>self._esc_handlers[esc_str] = handler<EOL><DEDENT>

Register a handler instance by name with esc_strings.


if line_info.line.endswith('<STR_LIT>'):<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Emacs ipython-mode tags certain input lines.


<EOL>return (identifier in ip.user_nsor identifier in ip.user_global_nsor identifier in ip.ns_table['<STR_LIT>'])<EOL>

Is the given identifier defined in one of the namespaces which shadow
    the alias and magic namespaces?  Note that an identifier is different
    than ifun, because it can not contain a '.' character.


return self._checkers<EOL>

Return a list of checkers, sorted by priority.


def unregister_handler(self, name, handler, esc_strings):

try:<EOL><INDENT>del self._handlers[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>for esc_str in esc_strings:<EOL><INDENT>h = self._esc_handlers.get(esc_str)<EOL>if h is handler:<EOL><INDENT>del self._esc_handlers[esc_str]<EOL><DEDENT><DEDENT>

Unregister a handler instance by name with esc_strings.


return self._esc_handlers.get(esc_str)<EOL>


if transformer in self._transformers:<EOL><INDENT>self._transformers.remove(transformer)<EOL><DEDENT>


<EOL>line = line_info.line<EOL>continue_prompt = line_info.continue_prompt<EOL>if (continue_prompt and<EOL>self.shell.autoindent and<EOL>line.isspace() and<EOL><NUM_LIT:0> < abs(len(line) - self.shell.indent_current_nsp) <= <NUM_LIT:2>):<EOL><INDENT>line = '<STR_LIT>'<EOL><DEDENT>return line<EOL>

Handle normal input lines. Use as a template for handlers.


if checker not in self._checkers:<EOL><INDENT>self._checkers.append(checker)<EOL>self.sort_checkers()<EOL><DEDENT>


if not src: return False<EOL>ll  = src.splitlines()[-<NUM_LIT:1>]<EOL>return (ll == '<STR_LIT>') or ll.isspace()<EOL>

Determine if the input source ends in a blank.

    A blank is either a newline or a line consisting of whitespace.

    Parameters
    ----------
    src : string
      A single or multiline string.


tpl = '<STR_LIT>'<EOL>cmd = '<STR_LIT:U+0020>'.join([line_info.ifun, line_info.the_rest]).strip()<EOL>return tpl % (line_info.pre, cmd)<EOL>


<EOL>if not self._is_complete:<EOL><INDENT>return True<EOL><DEDENT>if self.indent_spaces==<NUM_LIT:0>:<EOL><INDENT>if self.input_mode=='<STR_LIT>':<EOL><INDENT>if not self._full_dedent:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>code_ast = ast.parse(u'<STR_LIT>'.join(self._buffer))<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>if len(code_ast.body) == <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>last_line = self.source.splitlines()[-<NUM_LIT:1>]<EOL>return bool(last_line and not last_line.isspace())<EOL>

Return whether a block of interactive input can accept more input.

        This method is meant to be used by line-oriented frontends, who need to
        guess whether a block is complete or not based solely on prior and
        current input lines.  The InputSplitter considers it has a complete
        interactive block and will not accept more input only when either a
        SyntaxError is raised, or *all* of the following are true:

        1. The input compiles to a complete statement.

        2. The indentation level is flush-left (because if we are indented,
           like inside a function definition or for loop, we need to keep
           reading new input).

        3. There is one extra line consisting only of whitespace.

        Because of condition #3, this method should be used only by
        *line-oriented* frontends, since it means that intermediate blank lines
        are not allowed in function definitions (or any other indented block).

        If the current input produces a syntax error, this method immediately
        returns False but does *not* raise the syntax error exception, as
        typically clients will want to send invalid syntax to an execution
        backend which might convert the invalid syntax into valid Python via
        one of the dynamic IPython mechanisms.


def _make_help_call(target, esc, lspace, next_input=None):

method  = '<STR_LIT>' if esc == '<STR_LIT>'else '<STR_LIT>' if '<STR_LIT:*>' in targetelse '<STR_LIT>'<EOL>arg = "<STR_LIT:U+0020>".join([method, target])<EOL>if next_input is None:<EOL><INDENT>return '<STR_LIT>' % (lspace, arg)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>' %(lspace, next_input, arg)<EOL><DEDENT>

Prepares a pinfo(2)/psearch call from a target name and the escape
    (i.e. ? or ??)


super(IPythonInputSplitter, self).reset()<EOL>self._buffer_raw[:] = []<EOL>self.source_raw = '<STR_LIT>'<EOL>self.cell_magic_parts = []<EOL>self.processing_cell_magic = False<EOL>

Reset the input buffer and associated state.


self.indent_spaces = <NUM_LIT:0><EOL>self._buffer[:] = []<EOL>self.source = '<STR_LIT>'<EOL>self.code = None<EOL>self._is_complete = False<EOL>self._full_dedent = False<EOL>


ex_colors = ColorSchemeTable()<EOL>C = TermColors <EOL>ex_colors.add_scheme(ColorScheme(<EOL>'<STR_LIT>',<EOL>topline = C.NoColor,<EOL>filename = C.NoColor,<EOL>lineno = C.NoColor,<EOL>name = C.NoColor,<EOL>vName = C.NoColor,<EOL>val = C.NoColor,<EOL>em = C.NoColor,<EOL>normalEm = C.NoColor,<EOL>filenameEm = C.NoColor,<EOL>linenoEm = C.NoColor,<EOL>nameEm = C.NoColor,<EOL>valEm = C.NoColor,<EOL>excName = C.NoColor,<EOL>line = C.NoColor,<EOL>caret = C.NoColor,<EOL>Normal = C.NoColor<EOL>))<EOL>ex_colors.add_scheme(ColorScheme(<EOL>'<STR_LIT>',<EOL>topline = C.LightRed,<EOL>filename = C.Green,<EOL>lineno = C.Green,<EOL>name = C.Purple,<EOL>vName = C.Cyan,<EOL>val = C.Green,<EOL>em = C.LightCyan,<EOL>normalEm = C.LightCyan,<EOL>filenameEm = C.LightGreen,<EOL>linenoEm = C.LightGreen,<EOL>nameEm = C.LightPurple,<EOL>valEm = C.LightBlue,<EOL>excName = C.LightRed,<EOL>line = C.Yellow,<EOL>caret = C.White,<EOL>Normal = C.Normal<EOL>))<EOL>ex_colors.add_scheme(ColorScheme(<EOL>'<STR_LIT>',<EOL>topline = C.Red,<EOL>filename = C.LightGreen,<EOL>lineno = C.LightGreen,<EOL>name = C.LightPurple,<EOL>vName = C.Cyan,<EOL>val = C.LightGreen,<EOL>em = C.Cyan,<EOL>normalEm = C.Cyan,<EOL>filenameEm = C.Green,<EOL>linenoEm = C.Green,<EOL>nameEm = C.Purple,<EOL>valEm = C.Blue,<EOL>excName = C.Red,<EOL>line = C.Red,<EOL>caret = C.Normal,<EOL>Normal = C.Normal,<EOL>))<EOL>return ex_colors<EOL>

Return a color table with fields for exception reporting.

    The table is an instance of ColorSchemeTable with schemes added for
    'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
    in.

    Examples:

    >>> ec = exception_colors()
    >>> ec.active_scheme_name
    ''
    >>> print ec.active_colors
    None

    Now we activate a color scheme:
    >>> ec.set_active_scheme('NoColor')
    >>> ec.active_scheme_name
    'NoColor'
    >>> sorted(ec.active_colors.keys())
    ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
    'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
    'val', 'valEm']


def _validate_data(self, source, data, metadata=None):

if not isinstance(source, basestring):<EOL><INDENT>raise TypeError('<STR_LIT>' % source)<EOL><DEDENT>if not isinstance(data, dict):<EOL><INDENT>raise TypeError('<STR_LIT>' % data)<EOL><DEDENT>if metadata is not None:<EOL><INDENT>if not isinstance(metadata, dict):<EOL><INDENT>raise TypeError('<STR_LIT>' % data)<EOL><DEDENT><DEDENT>

Validate the display data.

        Parameters
        ----------
        source : str
            The fully dotted name of the callable that created the data, like
            :func:`foo.bar.my_formatter`.
        data : dict
            The formata data dictionary.
        metadata : dict
            Any metadata for the data.


publish_display_data(<EOL>u'<STR_LIT>',<EOL>{'<STR_LIT>':data},<EOL>metadata=metadata<EOL>)<EOL>

Publish raw HTML data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw HTML data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw LaTeX data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw LaTeX data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


<EOL>return module_completion(event.line)<EOL>

Give completions after user has typed 'import ...' or 'from ...


ip = get_ipython()<EOL>relpath = event.symbol<EOL>if event.line.endswith('<STR_LIT>') or '<STR_LIT>' in event.line:<EOL><INDENT>bkms = self.db.get('<STR_LIT>', None)<EOL>if bkms:<EOL><INDENT>return bkms.keys()<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>if event.symbol == '<STR_LIT:->':<EOL><INDENT>width_dh = str(len(str(len(ip.user_ns['<STR_LIT>']) + <NUM_LIT:1>)))<EOL>fmt = '<STR_LIT>' + width_dh +'<STR_LIT>'<EOL>ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['<STR_LIT>'])]<EOL>if len(ents) > <NUM_LIT:1>:<EOL><INDENT>return ents<EOL><DEDENT>return []<EOL><DEDENT>if event.symbol.startswith('<STR_LIT>'):<EOL><INDENT>return ["<STR_LIT>" + os.path.basename(d) for d in ip.user_ns['<STR_LIT>']]<EOL><DEDENT>relpath, tilde_expand, tilde_val = expand_user(relpath)<EOL>relpath = relpath.replace('<STR_LIT:\\>','<STR_LIT:/>')<EOL>found = []<EOL>for d in [f.replace('<STR_LIT:\\>','<STR_LIT:/>') + '<STR_LIT:/>' for f in glob.glob(relpath+'<STR_LIT:*>')<EOL>if os.path.isdir(f)]:<EOL><INDENT>if '<STR_LIT:U+0020>' in d:<EOL><INDENT>raise TryNext<EOL><DEDENT>found.append(d)<EOL><DEDENT>if not found:<EOL><INDENT>if os.path.isdir(relpath):<EOL><INDENT>return [compress_user(relpath, tilde_expand, tilde_val)]<EOL><DEDENT>bks = self.db.get('<STR_LIT>',{}).iterkeys()<EOL>bkmatches = [s for s in bks if s.startswith(event.symbol)]<EOL>if bkmatches:<EOL><INDENT>return bkmatches<EOL><DEDENT>raise TryNext<EOL><DEDENT>return [compress_user(p, tilde_expand, tilde_val) for p in found]<EOL>

Completer function for cd, which only returns directories.


ip = get_ipython()<EOL>if '<STR_LIT>' in ip.db:<EOL><INDENT>return ip.db['<STR_LIT>']<EOL><DEDENT>t = time()<EOL>store = False<EOL>modules = list(sys.builtin_module_names)<EOL>for path in sys.path:<EOL><INDENT>modules += module_list(path)<EOL>if time() - t >= TIMEOUT_STORAGE and not store:<EOL><INDENT>store = True<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>sys.stdout.flush()<EOL><DEDENT>if time() - t > TIMEOUT_GIVEUP:<EOL><INDENT>print("<STR_LIT>")<EOL>ip.db['<STR_LIT>'] = []<EOL>return []<EOL><DEDENT><DEDENT>modules = set(modules)<EOL>if '<STR_LIT>' in modules:<EOL><INDENT>modules.remove('<STR_LIT>')<EOL><DEDENT>modules = list(modules)<EOL>if store:<EOL><INDENT>ip.db['<STR_LIT>'] = modules<EOL><DEDENT>return modules<EOL>

Returns a list containing the names of all the modules available in the
folders of the pythonpath.


comps = arg_split(event.line, strict=False)<EOL>relpath = (len(comps) > <NUM_LIT:1> and comps[-<NUM_LIT:1>] or '<STR_LIT>').strip("<STR_LIT>")<EOL>lglob = glob.glob<EOL>isdir = os.path.isdir<EOL>relpath, tilde_expand, tilde_val = expand_user(relpath)<EOL>dirs = [f.replace('<STR_LIT:\\>','<STR_LIT:/>') + "<STR_LIT:/>" for f in lglob(relpath+'<STR_LIT:*>') if isdir(f)]<EOL>if filter(magic_run_re.match, comps):<EOL><INDENT>pys =  [f.replace('<STR_LIT:\\>','<STR_LIT:/>') for f in lglob('<STR_LIT:*>')]<EOL><DEDENT>else:<EOL><INDENT>pys =  [f.replace('<STR_LIT:\\>','<STR_LIT:/>')<EOL>for f in lglob(relpath+'<STR_LIT>') + lglob(relpath+'<STR_LIT>') +<EOL>lglob(relpath + '<STR_LIT>')]<EOL><DEDENT>return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]<EOL>

Complete files that end in .py or .ipy for the %run command.


return '<STR_LIT>'.split()<EOL>


words = line.split('<STR_LIT:U+0020>')<EOL>nwords = len(words)<EOL>if nwords == <NUM_LIT:3> and words[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>return ['<STR_LIT>']<EOL><DEDENT>if nwords < <NUM_LIT:3> and (words[<NUM_LIT:0>] in ['<STR_LIT>','<STR_LIT>']) :<EOL><INDENT>if nwords == <NUM_LIT:1>:<EOL><INDENT>return get_root_modules()<EOL><DEDENT>mod = words[<NUM_LIT:1>].split('<STR_LIT:.>')<EOL>if len(mod) < <NUM_LIT:2>:<EOL><INDENT>return get_root_modules()<EOL><DEDENT>completion_list = try_import('<STR_LIT:.>'.join(mod[:-<NUM_LIT:1>]), True)<EOL>return ['<STR_LIT:.>'.join(mod[:-<NUM_LIT:1>] + [el]) for el in completion_list]<EOL><DEDENT>if nwords >= <NUM_LIT:3> and words[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>mod = words[<NUM_LIT:1>]<EOL>return try_import(mod)<EOL><DEDENT>

Returns a list containing the completion possibilities for an import line.

The line looks like this :
'import xml.d'
'from xml.dom import'


if session == <NUM_LIT:0>:<EOL><INDENT>return str(line)<EOL><DEDENT>return "<STR_LIT>" % (session, line)<EOL>

Helper function to format line numbers properly.


return os.path.join(locate_profile(profile), '<STR_LIT>')<EOL>

Find the history file for the given profile name.

        This is overridden by the HistoryManager subclass, to use the shell's
        active profile.

        Parameters
        ----------
        profile : str
          The name of a profile which has a history file.


with self.db:<EOL><INDENT>self.db.execute("<STR_LIT>",<EOL>(name, self.session_number))<EOL><DEDENT>

Give the current session a name in the history database.


self.output_hist.clear()<EOL>self.dir_hist[:] = [os.getcwdu()]<EOL>if new_session:<EOL><INDENT>if self.session_number:<EOL><INDENT>self.end_session()<EOL><DEDENT>self.input_hist_parsed[:] = ["<STR_LIT>"]<EOL>self.input_hist_raw[:] = ["<STR_LIT>"]<EOL>self.new_session()<EOL><DEDENT>

Clear the session history, releasing all object references, and
        optionally open a new session.


def get_range(self, session, start=<NUM_LIT:1>, stop=None, raw=True,output=False):

if stop:<EOL><INDENT>lineclause = "<STR_LIT>"<EOL>params = (session, start, stop)<EOL><DEDENT>else:<EOL><INDENT>lineclause = "<STR_LIT>"<EOL>params = (session, start)<EOL><DEDENT>return self._run_sql("<STR_LIT>""<STR_LIT>" % lineclause,<EOL>params, raw=raw, output=output)<EOL>

Retrieve input by session.

        Parameters
        ----------
        session : int
            Session number to retrieve.
        start : int
            First line to retrieve.
        stop : int
            End of line range (excluded from output itself). If None, retrieve
            to the end of the session.
        raw : bool
            If True, return untranslated input
        output : bool
            If True, attempt to include output. This will be 'real' Python
            objects for the current session, or text reprs from previous
            sessions if db_log_output was enabled at the time. Where no output
            is found, None is used.

        Returns
        -------
        An iterator over the desired lines. Each line is a 3-tuple, either
        (session, line, input) if output is False, or
        (session, line, (input, output)) if output is True.


profile_dir = self.shell.profile_dir.location<EOL>return os.path.join(profile_dir, '<STR_LIT>')<EOL>

Get default history file name based on the Shell's profile.

        The profile parameter is ignored, but must exist for compatibility with
        the parent class.


self.stop_now = True<EOL>self.history_manager.save_flag.set()<EOL>self.join()<EOL>

This can be called from the main thread to safely stop this thread.

        Note that it does not attempt to write out remaining history before
        exiting. That should be done by calling the HistoryManager's
        end_session method.


def _run_sql(self, sql, params, raw=True, output=False):

toget = '<STR_LIT>' if raw else '<STR_LIT:source>'<EOL>sqlfrom = "<STR_LIT>"<EOL>if output:<EOL><INDENT>sqlfrom = "<STR_LIT>"<EOL>toget = "<STR_LIT>" % toget<EOL><DEDENT>cur = self.db.execute("<STR_LIT>" %(toget, sqlfrom) + sql, params)<EOL>if output:    <EOL><INDENT>return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)<EOL><DEDENT>return cur<EOL>

Prepares and runs an SQL query for the history database.

        Parameters
        ----------
        sql : str
          Any filtering expressions to go after SELECT ... FROM ...
        params : tuple
          Parameters passed to the SQL query (to replace "?")
        raw, output : bool
          See :meth:`get_range`

        Returns
        -------
        Tuples as :meth:`get_range`


def get_range(self, session=<NUM_LIT:0>, start=<NUM_LIT:1>, stop=None, raw=True,output=False):

if session <= <NUM_LIT:0>:<EOL><INDENT>session += self.session_number<EOL><DEDENT>if session==self.session_number:          <EOL><INDENT>return self._get_range_session(start, stop, raw, output)<EOL><DEDENT>return super(HistoryManager, self).get_range(session, start, stop, raw,<EOL>output)<EOL>

Retrieve input by session.

        Parameters
        ----------
        session : int
            Session number to retrieve. The current session is 0, and negative
            numbers count back from current session, so -1 is previous session.
        start : int
            First line to retrieve.
        stop : int
            End of line range (excluded from output itself). If None, retrieve
            to the end of the session.
        raw : bool
            If True, return untranslated input
        output : bool
            If True, attempt to include output. This will be 'real' Python
            objects for the current session, or text reprs from previous
            sessions if db_log_output was enabled at the time. Where no output
            is found, None is used.

        Returns
        -------
        An iterator over the desired lines. Each line is a 3-tuple, either
        (session, line, input) if output is False, or
        (session, line, (input, output)) if output is True.


for range_str in ranges_str.split():<EOL><INDENT>rmatch = range_re.match(range_str)<EOL>if not rmatch:<EOL><INDENT>continue<EOL><DEDENT>start = int(rmatch.group("<STR_LIT:start>"))<EOL>end = rmatch.group("<STR_LIT:end>")<EOL>end = int(end) if end else start+<NUM_LIT:1>   <EOL>if rmatch.group("<STR_LIT>") == "<STR_LIT:->":       <EOL><INDENT>end += <NUM_LIT:1><EOL><DEDENT>startsess = rmatch.group("<STR_LIT>") or "<STR_LIT:0>"<EOL>endsess = rmatch.group("<STR_LIT>") or startsess<EOL>startsess = int(startsess.replace("<STR_LIT>","<STR_LIT:->"))<EOL>endsess = int(endsess.replace("<STR_LIT>","<STR_LIT:->"))<EOL>assert endsess >= startsess<EOL>if endsess == startsess:<EOL><INDENT>yield (startsess, start, end)<EOL>continue<EOL><DEDENT>yield (startsess, start, None)<EOL>for sess in range(startsess+<NUM_LIT:1>, endsess):<EOL><INDENT>yield (sess, <NUM_LIT:1>, None)<EOL><DEDENT>yield (endsess, <NUM_LIT:1>, end)<EOL><DEDENT>

Turn a string of history ranges into 3-tuples of (session, start, stop).

    Examples
    --------
    list(extract_input_ranges("~8/5-~7/4 2"))
    [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]


def _get_range_session(self, start=<NUM_LIT:1>, stop=None, raw=True, output=False):

input_hist = self.input_hist_raw if raw else self.input_hist_parsed<EOL>n = len(input_hist)<EOL>if start < <NUM_LIT:0>:<EOL><INDENT>start += n<EOL><DEDENT>if not stop or (stop > n):<EOL><INDENT>stop = n<EOL><DEDENT>elif stop < <NUM_LIT:0>:<EOL><INDENT>stop += n<EOL><DEDENT>for i in range(start, stop):<EOL><INDENT>if output:<EOL><INDENT>line = (input_hist[i], self.output_hist_reprs.get(i))<EOL><DEDENT>else:<EOL><INDENT>line = input_hist[i]<EOL><DEDENT>yield (<NUM_LIT:0>, i, line)<EOL><DEDENT>

Get input and output history from the current session. Called by
        get_range, and takes similar parameters.


def log_write(self, data, kind='<STR_LIT:input>'):

<EOL>if self.log_active and data:<EOL><INDENT>write = self.logfile.write<EOL>if kind=='<STR_LIT:input>':<EOL><INDENT>if self.timestamp:<EOL><INDENT>write(str_to_unicode(time.strftime('<STR_LIT>',<EOL>time.localtime())))<EOL><DEDENT>write(data)<EOL><DEDENT>elif kind=='<STR_LIT>' and self.log_output:<EOL><INDENT>odata = '<STR_LIT:\n>'.join(['<STR_LIT>' % s<EOL>for s in data.splitlines()])<EOL>write('<STR_LIT>' % odata)<EOL><DEDENT>self.logfile.flush()<EOL><DEDENT>


if self.logfile is None:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>state = self.log_active and '<STR_LIT>' or '<STR_LIT>'<EOL>print('<STR_LIT>',self.logfname)<EOL>print('<STR_LIT>',self.logmode)<EOL>print('<STR_LIT>',self.log_output)<EOL>print('<STR_LIT>',self.log_raw_input)<EOL>print('<STR_LIT>',self.timestamp)<EOL>print('<STR_LIT>',state)<EOL><DEDENT>

Print a status message about the logger.


try:<EOL><INDENT>del self.modules[module_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>self.skip_modules[module_name] = True<EOL>

Skip reloading the named module in the future


update_generic(old.fdel, new.fdel)<EOL>update_generic(old.fget, new.fget)<EOL>update_generic(old.fset, new.fset)<EOL>

Replace get/set/del functions of a property


@line_magic<EOL><INDENT>def aimport(self, parameter_s='<STR_LIT>', stream=None):<DEDENT>

modname = parameter_s<EOL>if not modname:<EOL><INDENT>to_reload = self._reloader.modules.keys()<EOL>to_reload.sort()<EOL>to_skip = self._reloader.skip_modules.keys()<EOL>to_skip.sort()<EOL>if stream is None:<EOL><INDENT>stream = sys.stdout<EOL><DEDENT>if self._reloader.check_all:<EOL><INDENT>stream.write("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>stream.write("<STR_LIT>" % '<STR_LIT:U+0020>'.join(to_reload))<EOL><DEDENT>stream.write("<STR_LIT>" % '<STR_LIT:U+0020>'.join(to_skip))<EOL><DEDENT>elif modname.startswith('<STR_LIT:->'):<EOL><INDENT>modname = modname[<NUM_LIT:1>:]<EOL>self._reloader.mark_module_skipped(modname)<EOL><DEDENT>else:<EOL><INDENT>top_module, top_name = self._reloader.aimport_module(modname)<EOL>self.shell.push({top_name: top_module})<EOL><DEDENT>

%aimport => Import modules for automatic reloading.

        %aimport
        List modules to automatically import and not to import.

        %aimport foo
        Import module 'foo' and mark it to be autoreloaded for %autoreload 1

        %aimport -foo
        Mark module 'foo' to not be autoreloaded for %autoreload 1


if parameter_s == '<STR_LIT>':<EOL><INDENT>self._reloader.check(True)<EOL><DEDENT>elif parameter_s == '<STR_LIT:0>':<EOL><INDENT>self._reloader.enabled = False<EOL><DEDENT>elif parameter_s == '<STR_LIT:1>':<EOL><INDENT>self._reloader.check_all = False<EOL>self._reloader.enabled = True<EOL><DEDENT>elif parameter_s == '<STR_LIT:2>':<EOL><INDENT>self._reloader.check_all = True<EOL>self._reloader.enabled = True<EOL><DEDENT>

r"""%autoreload => Reload modules automatically

        %autoreload
        Reload all modules (except those excluded by %aimport) automatically
        now.

        %autoreload 0
        Disable automatic reloading.

        %autoreload 1
        Reload all modules imported with %aimport every time before executing
        the Python code typed.

        %autoreload 2
        Reload all modules (except those excluded by %aimport) every time
        before executing the Python code typed.

        Reloading Python modules in a reliable way is in general
        difficult, and unexpected things may occur. %autoreload tries to
        work around common pitfalls by replacing function code objects and
        parts of classes previously in the module with new versions. This
        makes the following things to work:

        - Functions and classes imported via 'from xxx import foo' are upgraded
          to new versions when 'xxx' is reloaded.

        - Methods and properties of classes are upgraded on reload, so that
          calling 'c.foo()' on an object 'c' created before the reload causes
          the new code for 'foo' to be executed.

        Some of the known remaining caveats are:

        - Replacing code objects does not always succeed: changing a @property
          in a class to an ordinary method or a method to a member variable
          can cause problems (but in old objects only).

        - Functions that are removed (eg. via monkey-patching) from a module
          before it is reloaded are not upgraded.

        - C extension modules cannot be reloaded, and so cannot be
          autoreloaded.


self.mark_module_reloadable(module_name)<EOL>__import__(module_name)<EOL>top_name = module_name.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>top_module = sys.modules[top_name]<EOL>return top_module, top_name<EOL>

Import a module, and mark it reloadable

        Returns
        -------
        top_module : module
            The imported module if it is top-level, or the top-level
        top_name : module
            Name of top_module


global _loaded<EOL>if not _loaded:<EOL><INDENT>ip.register_magics(RMagics)<EOL>_loaded = True<EOL><DEDENT>


value = '<STR_LIT>'.join([str_to_unicode(s, '<STR_LIT:utf-8>') for s in self.Rstdout_cache])<EOL>self.Rstdout_cache = []<EOL>return value<EOL>

Flush R's stdout cache to a string, returning the string.


A hook to capture R's stdout in a cache.


s = latex(o, mode='<STR_LIT>')<EOL>s = s.replace('<STR_LIT>','<STR_LIT>')<EOL>s = s.replace('<STR_LIT>', '<STR_LIT>')<EOL>png = latex_to_png(s)<EOL>return png<EOL>

A function to display sympy expression using inline style LaTeX in PNG.


if cycle:<EOL><INDENT>return p.text('<STR_LIT>')<EOL><DEDENT>out = pretty(o, use_unicode=True)<EOL>if '<STR_LIT:\n>' in out:<EOL><INDENT>p.text(u'<STR_LIT:\n>')<EOL><DEDENT>p.text(out)<EOL>

A function to pretty print sympy Basic objects.


config = kwargs.pop('<STR_LIT>', None)<EOL>if config is not None:<EOL><INDENT>self.config = config<EOL><DEDENT>super(Configurable, self).__init__(**kwargs)<EOL>self.created = datetime.datetime.now()<EOL>

Create a configurable given a config config.

        Parameters
        ----------
        config : Config
            If this is empty, default values are used. If config is a
            :class:`Config` instance, it will be used to configure the
            instance.

        Notes
        -----
        Subclasses of Configurable must call the :meth:`__init__` method of
        :class:`Configurable` *before* doing anything else and using
        :func:`super`::

            class MyConfigurable(Configurable):
                def __init__(self, config=None):
                    super(MyConfigurable, self).__init__(config)
                    # Then any other code you need to finish initialization.

        This ensures that instances will be configured properly.


def c(s):<EOL><INDENT>"""<STR_LIT>"""<EOL>s = '<STR_LIT>'.join(wrap_paragraphs(s, <NUM_LIT>))<EOL>return '<STR_LIT>' + s.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL><DEDENT>breaker = '<STR_LIT:#>' + '<STR_LIT:->'*<NUM_LIT><EOL>s = "<STR_LIT>"%cls.__name__<EOL>lines = [breaker, s, breaker, '<STR_LIT>']<EOL>desc = cls.class_traits().get('<STR_LIT:description>')<EOL>if desc:<EOL><INDENT>desc = desc.default_value<EOL><DEDENT>else:<EOL><INDENT>desc = getattr(cls, '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>if desc:<EOL><INDENT>lines.append(c(desc))<EOL>lines.append('<STR_LIT>')<EOL><DEDENT>parents = []<EOL>for parent in cls.mro():<EOL><INDENT>if parent is not cls and issubclass(parent, Configurable) andparent.class_traits(config=True):<EOL><INDENT>parents.append(parent)<EOL><DEDENT><DEDENT>if parents:<EOL><INDENT>pstr = '<STR_LIT:U+002CU+0020>'.join([ p.__name__ for p in parents ])<EOL>lines.append(c('<STR_LIT>'%(cls.__name__, pstr)))<EOL>lines.append('<STR_LIT>')<EOL><DEDENT>for name,trait in cls.class_traits(config=True).items():<EOL><INDENT>help = trait.get_metadata('<STR_LIT>') or '<STR_LIT>'<EOL>lines.append(c(help))<EOL>lines.append('<STR_LIT>'%(cls.__name__, name, trait.get_default_value()))<EOL>lines.append('<STR_LIT>')<EOL><DEDENT>return '<STR_LIT:\n>'.join(lines)<EOL>


return hasattr(cls, "<STR_LIT>") and cls._instance is not None<EOL>


argv = sys.argv[<NUM_LIT:1>:] if argv is None else argv<EOL>if argv and argv[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>argv = argv[<NUM_LIT:1>:] + ['<STR_LIT>']<EOL><DEDENT>if self.subcommands and len(argv) > <NUM_LIT:0>:<EOL><INDENT>subc, subargv = argv[<NUM_LIT:0>], argv[<NUM_LIT:1>:]<EOL>if re.match(r'<STR_LIT>', subc) and subc in self.subcommands:<EOL><INDENT>return self.initialize_subcommand(subc, subargv)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in argv or '<STR_LIT>' in argv or '<STR_LIT>' in argv:<EOL><INDENT>self.print_description()<EOL>self.print_help('<STR_LIT>' in argv)<EOL>self.print_examples()<EOL>self.exit(<NUM_LIT:0>)<EOL><DEDENT>if '<STR_LIT>' in argv or '<STR_LIT>' in argv:<EOL><INDENT>self.print_version()<EOL>self.exit(<NUM_LIT:0>)<EOL><DEDENT>flags,aliases = self.flatten_flags()<EOL>loader = KVArgParseConfigLoader(argv=argv, aliases=aliases,<EOL>flags=flags)<EOL>config = loader.load_config()<EOL>self.update_config(config)<EOL>self.extra_args = loader.extra_args<EOL>


def _log_level_changed(self, name, old, new):

if isinstance(new, str):<EOL><INDENT>new = getattr(logging, new)<EOL>self.log_level = new<EOL><DEDENT>self.log.setLevel(new)<EOL>

Adjust the log level when log_level is set.


lines = ["<STR_LIT>"%self.name]<EOL>lines.append('<STR_LIT>')<EOL>lines.append('<STR_LIT>')<EOL>lines.append('<STR_LIT>')<EOL>for cls in self.classes:<EOL><INDENT>lines.append(cls.class_config_section())<EOL><DEDENT>return '<STR_LIT:\n>'.join(lines)<EOL>

generate default config file from Configurables


self.clear()<EOL>return self.config<EOL>

Load a config from somewhere, return a :class:`Config` instance.

        Usually, this will cause self.config to be set and then returned.
        However, in most cases, :meth:`ConfigLoader.clear` should be called
        to erase any previous state.


def load_config(self, argv=None, aliases=None, flags=None):

self.clear()<EOL>if argv is None:<EOL><INDENT>argv = self.argv<EOL><DEDENT>if aliases is None:<EOL><INDENT>aliases = self.aliases<EOL><DEDENT>if flags is None:<EOL><INDENT>flags = self.flags<EOL><DEDENT>self._create_parser(aliases, flags)<EOL>self._parse_args(argv)<EOL>self._convert_to_config()<EOL>return self.config<EOL>

Parse command line arguments and return as a Config object.

        Parameters
        ----------

        args : optional, list
          If given, a list with the structure of sys.argv[1:] to parse
          arguments from. If not given, the instance's self.argv attribute
          (given at construction time) is used.


def __init__(self, filename, path=None):

super(PyFileConfigLoader, self).__init__()<EOL>self.filename = filename<EOL>self.path = path<EOL>self.full_filename = '<STR_LIT>'<EOL>self.data = None<EOL>

Build a config loader for a filename and path.

        Parameters
        ----------
        filename : str
            The file name of the config file.
        path : str, list, tuple
            The path to search for the config file on, or a sequence of
            paths to try in order.


uargv = []<EOL>if enc is None:<EOL><INDENT>enc = DEFAULT_ENCODING<EOL><DEDENT>for arg in argv:<EOL><INDENT>if not isinstance(arg, str):<EOL><INDENT>arg = arg.decode(enc)<EOL><DEDENT>uargv.append(arg)<EOL><DEDENT>return uargv<EOL>

decode argv if bytes, using stin.encoding, falling back on default enc


def post_notification(self, ntype, sender, *args, **kwargs):

if(ntype==None or sender==None):<EOL><INDENT>raise NotificationError(<EOL>"<STR_LIT>")<EOL><DEDENT>if((ntype not in self.registered_types and<EOL>None not in self.registered_types) or<EOL>(sender not in self.registered_senders and<EOL>None not in self.registered_senders)):<EOL><INDENT>return<EOL><DEDENT>for o in self._observers_for_notification(ntype, sender):<EOL><INDENT>o(ntype, sender, *args, **kwargs)<EOL><DEDENT>

Post notification to all registered observers.

        The registered callback will be called as::

            callback(ntype, sender, *args, **kwargs)

        Parameters
        ----------
        ntype : hashable
            The notification type.
        sender : hashable
            The object sending the notification.
        *args : tuple
            The positional arguments to be passed to the callback.
        **kwargs : dict
            The keyword argument to be passed to the callback.

        Notes
        -----
        * If no registered observers, performance is O(1).
        * Notificaiton order is undefined.
        * Notifications are posted synchronously.


def _observers_for_notification(self, ntype, sender):

keys = (<EOL>(ntype,sender),<EOL>(ntype, None),<EOL>(None, sender),<EOL>(None,None)<EOL>)<EOL>obs = set()<EOL>for k in keys:<EOL><INDENT>obs.update(self.observers.get(k, set()))<EOL><DEDENT>return obs<EOL>

Find all registered observers that should recieve notification


self.registered_types = set() <EOL>self.registered_senders = set() <EOL>self.observers = {}<EOL>


from IPython.core.profiledir import ProfileDir, ProfileDirError<EOL>try:<EOL><INDENT>pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>raise IOError("<STR_LIT>" % profile)<EOL><DEDENT>return pd.location<EOL>

Find the path to the folder associated with a given profile.

    I.e. find $IPYTHONDIR/profile_whatever.


env = os.environ<EOL>if os.name == '<STR_LIT>' and sys.platform != '<STR_LIT>':<EOL><INDENT>xdg = env.get("<STR_LIT>", None) or os.path.join(get_home_dir(), '<STR_LIT>')<EOL>if xdg and _writable_dir(xdg):<EOL><INDENT>return py3compat.cast_unicode(xdg, fs_encoding)<EOL><DEDENT><DEDENT>return None<EOL>

Return the XDG_CONFIG_HOME, if it is defined and exists, else None.

    This is only for non-OS X posix (Linux,Unix,etc.) systems.


return _get_long_path_name(path)<EOL>

Expand a path into its long form.

    On Windows this expands any ~ in the paths. On other platforms, it is
    a null operation.


ipdir = os.path.dirname(IPython.__file__)<EOL>return py3compat.cast_unicode(ipdir, fs_encoding)<EOL>

Get the base directory where IPython itself is installed.


with open(path, "<STR_LIT>") as f:<EOL><INDENT>return md5(py3compat.str_to_bytes(f.read())).hexdigest()<EOL><DEDENT>

Make an MD5 hash of a file, ignoring any differences in line
    ending characters.


env = os.environ<EOL>pjoin = os.path.join<EOL>ipdir_def = '<STR_LIT>'<EOL>xdg_def = '<STR_LIT>'<EOL>home_dir = get_home_dir()<EOL>xdg_dir = get_xdg_dir()<EOL>if '<STR_LIT>' in env:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>ipdir = env.get('<STR_LIT>', env.get('<STR_LIT>', None))<EOL>if ipdir is None:<EOL><INDENT>home_ipdir = pjoin(home_dir, ipdir_def)<EOL>if xdg_dir:<EOL><INDENT>xdg_ipdir = pjoin(xdg_dir, xdg_def)<EOL>if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):<EOL><INDENT>ipdir = xdg_ipdir<EOL><DEDENT><DEDENT>if ipdir is None:<EOL><INDENT>ipdir = home_ipdir<EOL><DEDENT><DEDENT>ipdir = os.path.normpath(os.path.expanduser(ipdir))<EOL>if os.path.exists(ipdir) and not _writable_dir(ipdir):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"%ipdir)<EOL>ipdir = tempfile.mkdtemp()<EOL><DEDENT>elif not os.path.exists(ipdir):<EOL><INDENT>parent = ipdir.rsplit(os.path.sep, <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if not _writable_dir(parent):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"%parent)<EOL>ipdir = tempfile.mkdtemp()<EOL><DEDENT><DEDENT>return py3compat.cast_unicode(ipdir, fs_encoding)<EOL>

Get the IPython directory for this platform and user.

    This uses the logic in `get_home_dir` to find the home directory
    and then adds .ipython to the end of the path.


self.getter = func<EOL>self.name = func.func_name<EOL>

Create a OneTimeProperty instance.

         Parameters
         ----------
           func : method

             The method that will be called the first time to compute a value.
             Afterwards, the method's name will be a standard attribute holding
             the value of this computation.


return OneTimeProperty(func)<EOL>

Decorator to create OneTimeProperty attributes.

    Parameters
    ----------
      func : method
        The method that will be called the first time to compute a value.
        Afterwards, the method's name will be a standard attribute holding the
        value of this computation.

    Examples
    --------
    >>> class MagicProp(object):
    ...     @auto_attr
    ...     def a(self):
    ...         return 99
    ...
    >>> x = MagicProp()
    >>> 'a' in x.__dict__
    False
    >>> x.a
    99
    >>> 'a' in x.__dict__
    True


warn(msg,exit_val=exit_val,level=<NUM_LIT:4>)<EOL>


<EOL>os.makedirs(IP_TEST_DIR)<EOL>os.makedirs(os.path.join(XDG_TEST_DIR, '<STR_LIT>'))<EOL>

Setup testenvironment for the module:

            - Adds dummy home dir tree


global ignore_termtitle<EOL>ignore_termtitle = not(val)<EOL>

Control whether set_term_title is active or not.

    set_term_title() allows writing to the console titlebar.  In embedded
    widgets this can cause problems, so this call can be used to toggle it on
    or off as needed.

    The default state of the module is for the function to be disabled.

    Parameters
    ----------
      val : bool
        If True, set_term_title() actually writes to the terminal (using the
        appropriate platform-specific module).  If False, it is a no-op.


hfiles = self.keys(hashroot + "<STR_LIT>")<EOL>hfiles.sort()<EOL>last = len(hfiles) and hfiles[-<NUM_LIT:1>] or '<STR_LIT>'<EOL>if last.endswith('<STR_LIT>'):<EOL><INDENT>hfiles = [last] + hfiles[:-<NUM_LIT:1>]<EOL><DEDENT>all = {}<EOL>for f in hfiles:<EOL><INDENT>try:<EOL><INDENT>all.update(self[f])<EOL><DEDENT>except KeyError:<EOL><INDENT>print("<STR_LIT>",f,"<STR_LIT>")<EOL>del self[f]<EOL><DEDENT>self.uncache(f)<EOL><DEDENT>return all<EOL>

Get all data contained in hashed category 'hashroot' as dict


self.root = Path(root).expanduser().abspath()<EOL>if not self.root.isdir():<EOL><INDENT>self.root.makedirs()<EOL><DEDENT>self.cache = {}<EOL>

Return a db object that will manage the specied directory


def waitget(self,key, maxwaittime = <NUM_LIT> ):

wtimes = [<NUM_LIT>] * <NUM_LIT:3> + [<NUM_LIT:0.5>] * <NUM_LIT:2> + [<NUM_LIT:1>]<EOL>tries = <NUM_LIT:0><EOL>waited = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>val = self[key]<EOL>return val<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if waited > maxwaittime:<EOL><INDENT>raise KeyError(key)<EOL><DEDENT>time.sleep(wtimes[tries])<EOL>waited+=wtimes[tries]<EOL>if tries < len(wtimes) -<NUM_LIT:1>:<EOL><INDENT>tries+=<NUM_LIT:1><EOL><DEDENT><DEDENT>

Wait (poll) for a key to get a value

        Will wait for `maxwaittime` seconds before raising a KeyError.
        The call exits normally if the `key` field in db gets a value
        within the timeout period.

        Use this for synchronizing different processes or for ensuring
        that an unfortunately timed "db['key'] = newvalue" operation
        in another process (which causes all 'get' operation to cause a
        KeyError for the duration of pickling) won't screw up your program
        logic.


hfiles = self.keys(hashroot + "<STR_LIT>")<EOL>all = {}<EOL>for f in hfiles:<EOL><INDENT>all.update(self[f])<EOL>self.uncache(f)<EOL><DEDENT>self[hashroot + '<STR_LIT>'] = all<EOL>for f in hfiles:<EOL><INDENT>p = self.root / f<EOL>if p.basename() == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>p.remove()<EOL><DEDENT>

Compress category 'hashroot', so hset is fast again

        hget will fail if fast_only is True for compressed items (that were
        hset before hcompress).


if not items:<EOL><INDENT>self.cache = {}<EOL><DEDENT>for it in items:<EOL><INDENT>self.cache.pop(it,None)<EOL><DEDENT>

Removes all, or specified items from cache

        Use this after reading a large amount of large objects
        to free up memory, when you won't be needing the objects
        for a while.


hroot = self.root / hashroot<EOL>if not hroot.isdir():<EOL><INDENT>hroot.makedirs()<EOL><DEDENT>hfile = hroot / gethashfile(key)<EOL>d = self.get(hfile, {})<EOL>d.update( {key : value})<EOL>self[hfile] = d<EOL>


fil = self.root / key<EOL>self.cache.pop(fil,None)<EOL>try:<EOL><INDENT>fil.remove()<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>


traits = dict([memb for memb in getmembers(cls) ifisinstance(memb[<NUM_LIT:1>], TraitType)])<EOL>if len(metadata) == <NUM_LIT:0>:<EOL><INDENT>return traits<EOL><DEDENT>for meta_name, meta_eval in list(metadata.items()):<EOL><INDENT>if type(meta_eval) is not FunctionType:<EOL><INDENT>metadata[meta_name] = _SimpleTest(meta_eval)<EOL><DEDENT><DEDENT>result = {}<EOL>for name, trait in list(traits.items()):<EOL><INDENT>for meta_name, meta_eval in list(metadata.items()):<EOL><INDENT>if not meta_eval(trait.get_metadata(meta_name)):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result[name] = trait<EOL><DEDENT><DEDENT>return result<EOL>

Get a list of all the traits of this class.

        This method is just like the :meth:`traits` method, but is unbound.

        The TraitTypes returned don't know anything about the values
        that the various HasTrait's instances are holding.

        This follows the same algorithm as traits does and does not allow
        for any simple way of specifying merely that a metadata name
        exists, but has any value.  This is because get_metadata returns
        None if a metadata key doesn't exist.


def trait_metadata(self, traitname, key):

try:<EOL><INDENT>trait = getattr(self.__class__, traitname)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TraitError("<STR_LIT>" %<EOL>(self.__class__.__name__, traitname))<EOL><DEDENT>else:<EOL><INDENT>return trait.get_metadata(key)<EOL><DEDENT>


return list(cls.class_traits(**metadata).keys())<EOL>

Get a list of all the names of this classes traits.

        This method is just like the :meth:`trait_names` method, but is unbound.


def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):

if default_value is None:<EOL><INDENT>if klass is None:<EOL><INDENT>klass = object<EOL><DEDENT><DEDENT>elif klass is None:<EOL><INDENT>klass = default_value<EOL><DEDENT>if not (inspect.isclass(klass) or isinstance(klass, str)):<EOL><INDENT>raise TraitError("<STR_LIT>")<EOL><DEDENT>self.klass       = klass<EOL>self._allow_none = allow_none<EOL>super(Type, self).__init__(default_value, **metadata)<EOL>

Construct a Type trait

        A Type trait specifies that its values must be subclasses of
        a particular class.

        If only ``default_value`` is given, it is used for the ``klass`` as
        well.

        Parameters
        ----------
        default_value : class, str or None
            The default value must be a subclass of klass.  If an str,
            the str must be a fully specified class name, like 'foo.bar.Bah'.
            The string is resolved into real class, when the parent
            :class:`HasTraits` class is instantiated.
        klass : class, str, None
            Values of this trait must be a subclass of klass.  The klass
            may be specified in a string like: 'foo.bar.MyClass'.
            The string is resolved into real class, when the parent
            :class:`HasTraits` class is instantiated.
        allow_none : boolean
            Indicates whether None is allowed as an assignable value. Even if
            ``False``, the default value may be ``None``.


the_type = type(obj)<EOL>if (not py3compat.PY3) and the_type is InstanceType:<EOL><INDENT>the_type = obj.__class__<EOL><DEDENT>msg = '<STR_LIT>' % (obj, the_type)<EOL>return msg<EOL>

Return a string representation of a value and its type for readable
    error messages.


if obj is None:<EOL><INDENT>return self<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>value = obj._trait_values[self.name]<EOL><DEDENT>except KeyError:<EOL><INDENT>if self.name in obj._trait_dyn_inits:<EOL><INDENT>value = obj._trait_dyn_inits[self.name](obj)<EOL>value = self._validate(obj, value)<EOL>obj._trait_values[self.name] = value<EOL>return value<EOL><DEDENT>else:<EOL><INDENT>raise TraitError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>raise TraitError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return value<EOL><DEDENT><DEDENT>

Get the value of the trait by self.name for the instance.

        Default values are instantiated when :meth:`HasTraits.__new__`
        is called.  Thus by the time this method gets called either the
        default value or a user defined value (they called :meth:`__set__`)
        is in the :class:`HasTraits` instance.


def __init__(self, trait=None, default_value=None, minlen=<NUM_LIT:0>, maxlen=sys.maxsize,<EOL>allow_none=True, **metadata):

self._minlen = minlen<EOL>self._maxlen = maxlen<EOL>super(List, self).__init__(trait=trait, default_value=default_value,<EOL>allow_none=allow_none, **metadata)<EOL>

Create a List trait type from a list, set, or tuple.

        The default value is created by doing ``List(default_value)``,
        which creates a copy of the ``default_value``.

        ``trait`` can be specified, which restricts the type of elements
        in the container to that TraitType.

        If only one arg is given and it is not a Trait, it is taken as
        ``default_value``:

        ``c = List([1,2,3])``

        Parameters
        ----------

        trait : TraitType [ optional ]
            the type for restricting the contents of the Container.  If unspecified,
            types are not checked.

        default_value : SequenceType [ optional ]
            The default value for the Trait.  Must be list/tuple/set, and
            will be cast to the container type.

        minlen : Int [ default 0 ]
            The minimum length of the input list

        maxlen : Int [ default sys.maxint ]
            The maximum length of the input list

        allow_none : Bool [ default True ]
            Whether to allow the value to be None

        **metadata : any
            further keys for extensions to the Trait (e.g. config)


def __init__(self, *traits, **metadata):

default_value = metadata.pop('<STR_LIT>', None)<EOL>allow_none = metadata.pop('<STR_LIT>', True)<EOL>istrait = lambda t: isinstance(t, type) and issubclass(t, TraitType)<EOL>if len(traits) == <NUM_LIT:1> and default_value is None and not istrait(traits[<NUM_LIT:0>]):<EOL><INDENT>default_value = traits[<NUM_LIT:0>]<EOL>traits = ()<EOL><DEDENT>if default_value is None:<EOL><INDENT>args = ()<EOL><DEDENT>elif isinstance(default_value, self._valid_defaults):<EOL><INDENT>args = (default_value,)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' %(self.__class__.__name__, default_value))<EOL><DEDENT>self._traits = []<EOL>for trait in traits:<EOL><INDENT>t = trait()<EOL>t.name = '<STR_LIT>'<EOL>self._traits.append(t)<EOL><DEDENT>if self._traits and default_value is None:<EOL><INDENT>args = None<EOL><DEDENT>super(Container,self).__init__(klass=self.klass, args=args,<EOL>allow_none=allow_none, **metadata)<EOL>

Tuple(*traits, default_value=None, allow_none=True, **medatata)

        Create a tuple from a list, set, or tuple.

        Create a fixed-type tuple with Traits:

        ``t = Tuple(Int, Str, CStr)``

        would be length 3, with Int,Str,CStr for each element.

        If only one arg is given and it is not a Trait, it is taken as
        default_value:

        ``t = Tuple((1,2,3))``

        Otherwise, ``default_value`` *must* be specified by keyword.

        Parameters
        ----------

        *traits : TraitTypes [ optional ]
            the tsype for restricting the contents of the Tuple.  If unspecified,
            types are not checked. If specified, then each positional argument
            corresponds to an element of the tuple.  Tuples defined with traits
            are of fixed length.

        default_value : SequenceType [ optional ]
            The default value for the Tuple.  Must be list/tuple/set, and
            will be cast to a tuple. If `traits` are specified, the
            `default_value` must conform to the shape and type they specify.

        allow_none : Bool [ default True ]
            Whether to allow the value to be None

        **metadata : any
            further keys for extensions to the Trait (e.g. config)


This is called by :meth:`HasTraits.__new__` to finish init'ing.

        Some stages of initialization must be delayed until the parent
        :class:`HasTraits` instance has been created.  This method is
        called in :meth:`HasTraits.__new__` after the instance has been
        created.

        This method trigger the creation and validation of default values
        and also things like the resolution of str given class names in
        :class:`Type` and :class`Instance`.

        Parameters
        ----------
        obj : :class:`HasTraits` instance
            The parent :class:`HasTraits` instance that has just been
            created.


return [x in checklist for x in candidates]<EOL>

Check whether a list of items appear in a given list of options.

    Returns a list of 1 and 0, one for each candidate given.