self.showtraceback((etype,value,tb),tb_offset=<NUM_LIT:0>)<EOL>

One more defense for GUI apps that call sys.excepthook.

        GUI frameworks like wxPython trap exceptions and call
        sys.excepthook themselves.  I guess this is a feature that
        enables them to keep running after exceptions that would
        otherwise kill their mainloop. This is a bother for IPython
        which excepts to catch all of the program exceptions with a try:
        except: statement.

        Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
        any app directly invokes sys.excepthook, it will look to the user like
        IPython crashed.  In order to work around this, we can disable the
        CrashHandler and replace it with this excepthook instead, which prints a
        regular traceback using our InteractiveTB.  In this fashion, apps which
        call sys.excepthook will generate a regular-looking exception from
        IPython, and the CrashHandler will only be triggered by real IPython
        crashes.

        This hook should be used sparingly, only in places which are not likely
        to be true IPython errors.


if exc_tuple is None:<EOL><INDENT>etype, value, tb = sys.exc_info()<EOL><DEDENT>else:<EOL><INDENT>etype, value, tb = exc_tuple<EOL><DEDENT>if etype is None:<EOL><INDENT>if hasattr(sys, '<STR_LIT>'):<EOL><INDENT>etype, value, tb = sys.last_type, sys.last_value,sys.last_traceback<EOL><DEDENT><DEDENT>if etype is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>sys.last_type = etype<EOL>sys.last_value = value<EOL>sys.last_traceback = tb<EOL>return etype, value, tb<EOL>

get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.

        Ensures sys.last_type,value,traceback hold the exc_info we found,
        from whichever source.

        raises ValueError if none of these contain any information


def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,<EOL>exception_only=False):

try:<EOL><INDENT>try:<EOL><INDENT>etype, value, tb = self._get_exc_info(exc_tuple)<EOL><DEDENT>except ValueError:<EOL><INDENT>self.write_err('<STR_LIT>')<EOL>return<EOL><DEDENT>if etype is SyntaxError:<EOL><INDENT>self.showsyntaxerror(filename)<EOL><DEDENT>elif etype is UsageError:<EOL><INDENT>self.write_err("<STR_LIT>" % value)<EOL><DEDENT>else:<EOL><INDENT>if exception_only:<EOL><INDENT>stb = ['<STR_LIT>'<EOL>'<STR_LIT>']<EOL>stb.extend(self.InteractiveTB.get_exception_only(etype,<EOL>value))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>stb = value._render_traceback_()<EOL><DEDENT>except Exception:<EOL><INDENT>stb = self.InteractiveTB.structured_traceback(etype,<EOL>value, tb, tb_offset=tb_offset)<EOL><DEDENT>self._showtraceback(etype, value, stb)<EOL>if self.call_pdb:<EOL><INDENT>self.debugger(force=True)<EOL><DEDENT>return<EOL><DEDENT>self._showtraceback(etype, value, stb)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>self.write_err("<STR_LIT>")<EOL><DEDENT>

Display the exception that just occurred.

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

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


def _showtraceback(self, etype, evalue, stb):

print(self.InteractiveTB.stb2text(stb), file=io.stdout)<EOL>

Actually show a traceback.

        Subclasses may override this method to put the traceback on a different
        place, like a side channel.


etype, value, last_traceback = self._get_exc_info()<EOL>if filename and etype is SyntaxError:<EOL><INDENT>try:<EOL><INDENT>value.filename = filename<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>stb = self.SyntaxTB.structured_traceback(etype, value, [])<EOL>self._showtraceback(etype, value, stb)<EOL>

Display the syntax error that just occurred.

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

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


self.showsyntaxerror()<EOL>

Called by run_cell when there's an IndentationError in code entered
        at the prompt.

        This is overridden in TerminalInteractiveShell to show a message about
        the %paste magic.


if self.readline_use:<EOL><INDENT>import IPython.utils.rlineimpl as readline<EOL><DEDENT>self.rl_next_input = None<EOL>self.rl_do_indent = False<EOL>if not self.readline_use or not readline.have_readline:<EOL><INDENT>self.has_readline = False<EOL>self.readline = None<EOL>self.readline_no_record = no_op_context<EOL>self.set_readline_completer = no_op<EOL>self.set_custom_completer = no_op<EOL>if self.readline_use:<EOL><INDENT>warn('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.has_readline = True<EOL>self.readline = readline<EOL>sys.modules['<STR_LIT>'] = readline<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>self.readline_startup_hook = readline.set_pre_input_hook<EOL><DEDENT>else:<EOL><INDENT>self.readline_startup_hook = readline.set_startup_hook<EOL><DEDENT>inputrc_name = os.environ.get('<STR_LIT>')<EOL>if inputrc_name is None:<EOL><INDENT>inputrc_name = '<STR_LIT>'<EOL>if readline.uses_libedit:<EOL><INDENT>inputrc_name = '<STR_LIT>'<EOL><DEDENT>inputrc_name = os.path.join(self.home_dir, inputrc_name)<EOL><DEDENT>if os.path.isfile(inputrc_name):<EOL><INDENT>try:<EOL><INDENT>readline.read_init_file(inputrc_name)<EOL><DEDENT>except:<EOL><INDENT>warn('<STR_LIT>'<EOL>% inputrc_name)<EOL><DEDENT><DEDENT>if not readline.uses_libedit:<EOL><INDENT>for rlcommand in self.readline_parse_and_bind:<EOL><INDENT>readline.parse_and_bind(rlcommand)<EOL><DEDENT><DEDENT>delims = readline.get_completer_delims()<EOL>if not py3compat.PY3:<EOL><INDENT>delims = delims.encode("<STR_LIT:ascii>", "<STR_LIT:ignore>")<EOL><DEDENT>for d in self.readline_remove_delims:<EOL><INDENT>delims = delims.replace(d, "<STR_LIT>")<EOL><DEDENT>delims = delims.replace(ESC_MAGIC, '<STR_LIT>')<EOL>readline.set_completer_delims(delims)<EOL>readline.set_history_length(self.history_length)<EOL>self.refill_readline_hist()<EOL>self.readline_no_record = ReadlineNoRecord(self)<EOL><DEDENT>self.set_autoindent(self.autoindent)<EOL>


self.rl_next_input = py3compat.cast_bytes_py2(s)<EOL>

Sets the 'default' input string for the next command line.

        Requires readline.

        Example:

        [D:\ipython]|1> _ip.set_next_input("Hello Word")
        [D:\ipython]|2> Hello Word_  # cursor is here


if self.rl_do_indent:<EOL><INDENT>self.readline.insert_text(self._indent_current_str())<EOL><DEDENT>if self.rl_next_input is not None:<EOL><INDENT>self.readline.insert_text(self.rl_next_input)<EOL>self.rl_next_input = None<EOL><DEDENT>

readline hook to be used at the start of each line.

        Currently it handles auto-indent only.


return self.input_splitter.indent_spaces * '<STR_LIT:U+0020>'<EOL>

return the current level of indentation as a string


from IPython.core.completer import IPCompleter<EOL>from IPython.core.completerlib import (module_completer,<EOL>magic_run_completer, cd_completer, reset_completer)<EOL>self.Completer = IPCompleter(shell=self,<EOL>namespace=self.user_ns,<EOL>global_namespace=self.user_global_ns,<EOL>alias_table=self.alias_manager.alias_table,<EOL>use_readline=self.has_readline,<EOL>config=self.config,<EOL>)<EOL>self.configurables.append(self.Completer)<EOL>sdisp = self.strdispatchers.get('<STR_LIT>', StrDispatch())<EOL>self.strdispatchers['<STR_LIT>'] = sdisp<EOL>self.Completer.custom_completers = sdisp<EOL>self.set_hook('<STR_LIT>', module_completer, str_key = '<STR_LIT>')<EOL>self.set_hook('<STR_LIT>', module_completer, str_key = '<STR_LIT>')<EOL>self.set_hook('<STR_LIT>', magic_run_completer, str_key = '<STR_LIT>')<EOL>self.set_hook('<STR_LIT>', cd_completer, str_key = '<STR_LIT>')<EOL>self.set_hook('<STR_LIT>', reset_completer, str_key = '<STR_LIT>')<EOL>if self.has_readline:<EOL><INDENT>self.set_readline_completer()<EOL><DEDENT>

Initialize the completion machinery.

        This creates completion machinery that can be used by client code,
        either interactively in-process (typically triggered by the readline
        library), programatically (such as in test suites) or out-of-prcess
        (typically over the network by remote frontends).


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

<EOL>with self.builtin_trap:<EOL><INDENT>return self.Completer.complete(text, line, cursor_pos)<EOL><DEDENT>

Return the completed text and a list of completions.

        Parameters
        ----------

           text : string
             A string of text to be completed on.  It can be given as empty and
             instead a line/position pair are given.  In this case, the
             completer itself will split the line like readline does.

           line : string, optional
             The complete line that text is part of.

           cursor_pos : int, optional
             The position of the cursor on the input line.

        Returns
        -------
          text : string
            The actual text that was completed.

          matches : list
            A sorted list with all possible completions.

        The optional arguments allow the completion to take more context into
        account, and are part of the low-level completion API.

        This is a wrapper around the completion mechanism, similar to what
        readline does at the command line when the TAB key is hit.  By
        exposing it as a method, it can be used by other non-readline
        environments (such as GUIs) for text completion.

        Simple usage example:

        In [1]: x = 'hello'

        In [2]: _ip.complete('x.l')
        Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])


def set_custom_completer(self, completer, pos=<NUM_LIT:0>):

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

Adds a new custom completer function.

        The position argument (defaults to 0) is the index in the completers
        list where you want the completer to be inserted.


self.readline.set_completer(self.Completer.rlcomplete)<EOL>

Reset readline's completer to be our own.


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 run_line_magic(self, magic_name, line):

fn = self.find_line_magic(magic_name)<EOL>if fn is None:<EOL><INDENT>cm = self.find_cell_magic(magic_name)<EOL>etpl = "<STR_LIT>"<EOL>extra = '<STR_LIT>' if cm is None else ('<STR_LIT>'<EOL>'<STR_LIT>' % magic_name )<EOL>error(etpl % (magic_name, extra))<EOL><DEDENT>else:<EOL><INDENT>stack_depth = <NUM_LIT:2><EOL>magic_arg_s = self.var_expand(line, stack_depth)<EOL>args = [magic_arg_s]<EOL>if getattr(fn, "<STR_LIT>", False):<EOL><INDENT>args.append(sys._getframe(stack_depth).f_locals)<EOL><DEDENT>with self.builtin_trap:<EOL><INDENT>result = fn(*args)<EOL><DEDENT>return result<EOL><DEDENT>

Execute the given line magic.

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

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


def run_cell_magic(self, magic_name, line, cell):

fn = self.find_cell_magic(magic_name)<EOL>if fn is None:<EOL><INDENT>lm = self.find_line_magic(magic_name)<EOL>etpl = "<STR_LIT>"<EOL>extra = '<STR_LIT>' if lm is None else ('<STR_LIT>'<EOL>'<STR_LIT>' % magic_name )<EOL>error(etpl % (magic_name, extra))<EOL><DEDENT>else:<EOL><INDENT>stack_depth = <NUM_LIT:2><EOL>magic_arg_s = self.var_expand(line, stack_depth)<EOL>with self.builtin_trap:<EOL><INDENT>result = fn(line, cell)<EOL><DEDENT>return result<EOL><DEDENT>

Execute the given cell magic.

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

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

        cell : str
          The body of the cell as a (possibly multiline) string.


return self.magics_manager.magics['<STR_LIT>'].get(magic_name)<EOL>

Find and return a line magic by name.

        Returns None if the magic isn't found.


Find and return a cell magic by name.

        Returns None if the magic isn't found.


def find_magic(self, magic_name, magic_kind='<STR_LIT>'):

return self.magics_manager.magics[magic_kind].get(magic_name)<EOL>

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

        Returns None if the magic isn't found.


<EOL>magic_name, _, magic_arg_s = arg_s.partition('<STR_LIT:U+0020>')<EOL>magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)<EOL>return self.run_line_magic(magic_name, magic_arg_s)<EOL>

DEPRECATED. Use run_line_magic() instead.

        Call a magic function by name.

        Input: a string containing the name of the magic function to call and
        any additional arguments to be passed to the magic.

        magic('name -opt foo bar') is equivalent to typing at the ipython
        prompt:

        In[1]: %name -opt foo bar

        To call a magic without arguments, simply use magic('name').

        This provides a proper Python function to call IPython's magics in any
        valid Python code you can type at the interpreter, including loops and
        compound statements.


from IPython.core import macro<EOL>if isinstance(themacro, str):<EOL><INDENT>themacro = macro.Macro(themacro)<EOL><DEDENT>if not isinstance(themacro, macro.Macro):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.user_ns[name] = themacro<EOL>

Define a new macro

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


if cmd.rstrip().endswith('<STR_LIT:&>'):<EOL><INDENT>raise OSError("<STR_LIT>")<EOL><DEDENT>self.user_ns['<STR_LIT>'] = system(self.var_expand(cmd, depth=<NUM_LIT:1>))<EOL>

Call the given cmd in a subprocess, piping stdout/err

        Parameters
        ----------
        cmd : str
          Command to execute (can not end in '&', as background processes are
          not supported.  Should not be a command that expects input
          other than simple text.


cmd = self.var_expand(cmd, depth=<NUM_LIT:1>)<EOL>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>from IPython.utils._process_win32 import AvoidUNCPath<EOL>with AvoidUNCPath() as path:<EOL><INDENT>if path is not None:<EOL><INDENT>cmd = '<STR_LIT>' % (path, cmd)<EOL><DEDENT>cmd = py3compat.unicode_to_str(cmd)<EOL>ec = os.system(cmd)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cmd = py3compat.unicode_to_str(cmd)<EOL>ec = os.system(cmd)<EOL><DEDENT>self.user_ns['<STR_LIT>'] = ec<EOL>

Call the given cmd in a subprocess using os.system

        Parameters
        ----------
        cmd : str
          Command to execute.


def getoutput(self, cmd, split=True, depth=<NUM_LIT:0>):

if cmd.rstrip().endswith('<STR_LIT:&>'):<EOL><INDENT>raise OSError("<STR_LIT>")<EOL><DEDENT>out = getoutput(self.var_expand(cmd, depth=depth+<NUM_LIT:1>))<EOL>if split:<EOL><INDENT>out = SList(out.splitlines())<EOL><DEDENT>else:<EOL><INDENT>out = LSString(out)<EOL><DEDENT>return out<EOL>

Get output (possibly including stderr) from a subprocess.

        Parameters
        ----------
        cmd : str
          Command to execute (can not end in '&', as background processes are
          not supported.
        split : bool, optional
          If True, split the output into an IPython SList.  Otherwise, an
          IPython LSString is returned.  These are objects similar to normal
          lists and strings, with a few convenience attributes for easier
          manipulation of line-based output.  You can use '?' on them for
          details.
        depth : int, optional
          How many frames above the caller are the local variables which should
          be expanded in the command string? The default (0) assumes that the
          expansion variables are in the stack frame calling this function.


if not self.show_rewritten_input:<EOL><INDENT>return<EOL><DEDENT>rw = self.prompt_manager.render('<STR_LIT>') + cmd<EOL>try:<EOL><INDENT>rw = str(rw)<EOL>print(rw, file=io.stdout)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>print("<STR_LIT>" + cmd)<EOL><DEDENT>

Print to the screen the rewritten form of the user's command.

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

          /f x

        into::

          ------> f(x)

        after the user's input prompt.  This helps the user understand that the
        input line was transformed automatically by IPython.


out = {}<EOL>user_ns = self.user_ns<EOL>for varname in names:<EOL><INDENT>try:<EOL><INDENT>value = repr(user_ns[varname])<EOL><DEDENT>except:<EOL><INDENT>value = self._simple_error()<EOL><DEDENT>out[varname] = value<EOL><DEDENT>return out<EOL>

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

        Parameters
        ----------
        names : list of strings
          A list of names of variables to be read from the user namespace.

        Returns
        -------
        A dict, keyed by the input names and with the repr() of each value.


out = {}<EOL>user_ns = self.user_ns<EOL>global_ns = self.user_global_ns<EOL>for key, expr in expressions.items():<EOL><INDENT>try:<EOL><INDENT>value = repr(eval(expr, global_ns, user_ns))<EOL><DEDENT>except:<EOL><INDENT>value = self._simple_error()<EOL><DEDENT>out[key] = value<EOL><DEDENT>return out<EOL>

Evaluate a dict of expressions in the user's namespace.

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

        Returns
        -------
        A dict, keyed like the input expressions dict, with the repr() of each
        value.


with self.builtin_trap:<EOL><INDENT>exec(cmd, self.user_global_ns, self.user_ns)<EOL><DEDENT>

Execute a normal python statement in user namespace.


with self.builtin_trap:<EOL><INDENT>return eval(expr, self.user_global_ns, self.user_ns)<EOL><DEDENT>

Evaluate python expression expr in user namespace.

        Returns the result of evaluation


def safe_execfile(self, fname, *where, **kw):

kw.setdefault('<STR_LIT>', False)<EOL>kw.setdefault('<STR_LIT>', False)<EOL>fname = os.path.abspath(os.path.expanduser(fname))<EOL>try:<EOL><INDENT>with open(fname) as thefile:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>except:<EOL><INDENT>warn('<STR_LIT>' % fname)<EOL>return<EOL><DEDENT>dname = os.path.dirname(fname)<EOL>with prepended_to_syspath(dname):<EOL><INDENT>try:<EOL><INDENT>py3compat.execfile(fname,*where)<EOL><DEDENT>except SystemExit as status:<EOL><INDENT>if kw['<STR_LIT>']:<EOL><INDENT>raise<EOL><DEDENT>if status.code not in (<NUM_LIT:0>, None) and not kw['<STR_LIT>']:<EOL><INDENT>self.showtraceback(exception_only=True)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>if kw['<STR_LIT>']:<EOL><INDENT>raise<EOL><DEDENT>self.showtraceback()<EOL><DEDENT><DEDENT>

A safe version of the builtin execfile().

        This version will never throw an exception, but instead print
        helpful error messages to the screen.  This only works on pure
        Python files with the .py extension.

        Parameters
        ----------
        fname : string
            The name of the file to be executed.
        where : tuple
            One or two namespaces, passed to execfile() as (globals,locals).
            If only one is given, it is passed as both.
        exit_ignore : bool (False)
            If True, then silence SystemExit for non-zero status (it is always
            silenced for zero status, as it is so common).
        raise_exceptions : bool (False)
            If True raise exceptions everywhere. Meant for testing.


fname = os.path.abspath(os.path.expanduser(fname))<EOL>try:<EOL><INDENT>with open(fname) as thefile:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>except:<EOL><INDENT>warn('<STR_LIT>' % fname)<EOL>return<EOL><DEDENT>dname = os.path.dirname(fname)<EOL>with prepended_to_syspath(dname):<EOL><INDENT>try:<EOL><INDENT>with open(fname) as thefile:<EOL><INDENT>self.run_cell(thefile.read(), store_history=False)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.showtraceback()<EOL>warn('<STR_LIT>' % fname)<EOL><DEDENT><DEDENT>

Like safe_execfile, but for .ipy files with IPython syntax.

        Parameters
        ----------
        fname : str
            The name of the file to execute.  The filename must have a
            .ipy extension.


def safe_run_module(self, mod_name, where):

A safe version of runpy.run_module().

        This version will never throw an exception, but instead print
        helpful error messages to the screen.

        Parameters
        ----------
        mod_name : string
            The name of the module to be executed.
        where : dict
            The globals namespace.


def _run_cached_cell_magic(self, magic_name, line):

cell = self._current_cell_magic_body<EOL>self._current_cell_magic_body = None<EOL>return self.run_cell_magic(magic_name, line, cell)<EOL>

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


def run_cell(self, raw_cell, store_history=False, silent=False):

if (not raw_cell) or raw_cell.isspace():<EOL><INDENT>return<EOL><DEDENT>if silent:<EOL><INDENT>store_history = False<EOL><DEDENT>self.input_splitter.push(raw_cell)<EOL>if self.input_splitter.cell_magic_parts:<EOL><INDENT>self._current_cell_magic_body ='<STR_LIT>'.join(self.input_splitter.cell_magic_parts)<EOL><DEDENT>cell = self.input_splitter.source_reset()<EOL>with self.builtin_trap:<EOL><INDENT>prefilter_failed = False<EOL>if len(cell.splitlines()) == <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>cell = self.prefilter_manager.prefilter_lines(cell) + '<STR_LIT:\n>'<EOL><DEDENT>except AliasError as e:<EOL><INDENT>error(e)<EOL>prefilter_failed = True<EOL><DEDENT>except Exception:<EOL><INDENT>self.showtraceback()<EOL>prefilter_failed = True<EOL><DEDENT><DEDENT>if store_history:<EOL><INDENT>self.history_manager.store_inputs(self.execution_count,<EOL>cell, raw_cell)<EOL><DEDENT>if not silent:<EOL><INDENT>self.logger.log(cell, raw_cell)<EOL><DEDENT>if not prefilter_failed:<EOL><INDENT>cell_name = self.compile.cache(cell, self.execution_count)<EOL>with self.display_trap:<EOL><INDENT>try:<EOL><INDENT>code_ast = self.compile.ast_parse(cell,<EOL>filename=cell_name)<EOL><DEDENT>except IndentationError:<EOL><INDENT>self.showindentationerror()<EOL>if store_history:<EOL><INDENT>self.execution_count += <NUM_LIT:1><EOL><DEDENT>return None<EOL><DEDENT>except (OverflowError, SyntaxError, ValueError, TypeError,<EOL>MemoryError):<EOL><INDENT>self.showsyntaxerror()<EOL>if store_history:<EOL><INDENT>self.execution_count += <NUM_LIT:1><EOL><DEDENT>return None<EOL><DEDENT>interactivity = "<STR_LIT:none>" if silent else self.ast_node_interactivity<EOL>self.run_ast_nodes(code_ast.body, cell_name,<EOL>interactivity=interactivity)<EOL>post_exec = [] if silent else iter(self._post_execute.items())<EOL>for func, status in post_exec:<EOL><INDENT>if self.disable_failing_post_execute and not status:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>func()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>", file=io.stderr)<EOL><DEDENT>except Exception:<EOL><INDENT>self._post_execute[func] = False<EOL>self.showtraceback()<EOL>print('<STR_LIT:\n>'.join([<EOL>"<STR_LIT>" % func,<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]), file=io.stderr)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if store_history:<EOL><INDENT>self.history_manager.store_output(self.execution_count)<EOL>self.execution_count += <NUM_LIT:1><EOL><DEDENT>

Run a complete IPython cell.

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


def run_ast_nodes(self, nodelist, cell_name, interactivity='<STR_LIT>'):

if not nodelist:<EOL><INDENT>return<EOL><DEDENT>if interactivity == '<STR_LIT>':<EOL><INDENT>if isinstance(nodelist[-<NUM_LIT:1>], ast.Expr):<EOL><INDENT>interactivity = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>interactivity = "<STR_LIT:none>"<EOL><DEDENT><DEDENT>if interactivity == '<STR_LIT:none>':<EOL><INDENT>to_run_exec, to_run_interactive = nodelist, []<EOL><DEDENT>elif interactivity == '<STR_LIT>':<EOL><INDENT>to_run_exec, to_run_interactive = nodelist[:-<NUM_LIT:1>], nodelist[-<NUM_LIT:1>:]<EOL><DEDENT>elif interactivity == '<STR_LIT:all>':<EOL><INDENT>to_run_exec, to_run_interactive = [], nodelist<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % interactivity)<EOL><DEDENT>exec_count = self.execution_count<EOL>try:<EOL><INDENT>for i, node in enumerate(to_run_exec):<EOL><INDENT>mod = ast.Module([node])<EOL>code = self.compile(mod, cell_name, "<STR_LIT>")<EOL>if self.run_code(code):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>for i, node in enumerate(to_run_interactive):<EOL><INDENT>mod = ast.Interactive([node])<EOL>code = self.compile(mod, cell_name, "<STR_LIT>")<EOL>if self.run_code(code):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if softspace(sys.stdout, <NUM_LIT:0>):<EOL><INDENT>print()<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.showtraceback()<EOL><DEDENT>return False<EOL>

Run a sequence of AST nodes. The execution mode depends on the
        interactivity parameter.

        Parameters
        ----------
        nodelist : list
          A sequence of AST nodes to run.
        cell_name : str
          Will be passed to the compiler as the filename of the cell. Typically
          the value returned by ip.compile.cache(cell).
        interactivity : str
          'all', 'last', 'last_expr' or 'none', specifying which nodes should be
          run interactively (displaying output from expressions). 'last_expr'
          will run the last node interactively only if it is an expression (i.e.
          expressions in loops or other blocks are not displayed. Other values
          for this parameter will raise a ValueError.


<EOL>old_excepthook,sys.excepthook = sys.excepthook, self.excepthook<EOL>self.sys_excepthook = old_excepthook<EOL>outflag = <NUM_LIT:1>  <EOL>try:<EOL><INDENT>try:<EOL><INDENT>self.hooks.pre_run_code_hook()<EOL>exec(code_obj, self.user_global_ns, self.user_ns)<EOL><DEDENT>finally:<EOL><INDENT>sys.excepthook = old_excepthook<EOL><DEDENT><DEDENT>except SystemExit:<EOL><INDENT>self.showtraceback(exception_only=True)<EOL>warn("<STR_LIT>", level=<NUM_LIT:1>)<EOL><DEDENT>except self.custom_exceptions:<EOL><INDENT>etype,value,tb = sys.exc_info()<EOL>self.CustomTB(etype,value,tb)<EOL><DEDENT>except:<EOL><INDENT>self.showtraceback()<EOL><DEDENT>else:<EOL><INDENT>outflag = <NUM_LIT:0><EOL><DEDENT>return outflag<EOL>

Execute a code object.

        When an exception occurs, self.showtraceback() is called to display a
        traceback.

        Parameters
        ----------
        code_obj : code object
          A compiled code object, to be executed

        Returns
        -------
        False : successful execution.
        True : an error occurred.


def enable_pylab(self, gui=None, import_all=True):

from IPython.core.pylabtools import mpl_runner<EOL>ns = {}<EOL>try:<EOL><INDENT>gui = pylab_activate(ns, gui, import_all, self)<EOL><DEDENT>except KeyError:<EOL><INDENT>error("<STR_LIT>" % gui)<EOL>return<EOL><DEDENT>self.user_ns.update(ns)<EOL>self.user_ns_hidden.update(ns)<EOL>self.enable_gui(gui)<EOL>self.magics_manager.registry['<STR_LIT>'].default_runner =mpl_runner(self.safe_execfile)<EOL>

Activate pylab support at runtime.

        This turns on support for matplotlib, preloads into the interactive
        namespace all of numpy and pylab, and configures IPython to correctly
        interact with the GUI event loop.  The GUI backend to be used can be
        optionally selected with the optional :param:`gui` argument.

        Parameters
        ----------
        gui : optional, string

          If given, dictates the choice of matplotlib GUI backend to use
          (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
          'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
          matplotlib (as dictated by the matplotlib build-time options plus the
          user's matplotlibrc configuration file).  Note that not all backends
          make sense in all contexts, for example a terminal ipython can't
          display figures inline.


def var_expand(self, cmd, depth=<NUM_LIT:0>, formatter=DollarFormatter()):

ns = self.user_ns.copy()<EOL>ns.update(sys._getframe(depth+<NUM_LIT:1>).f_locals)<EOL>ns.pop('<STR_LIT>', None)<EOL>try:<EOL><INDENT>cmd = formatter.format(cmd, **ns)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return cmd<EOL>

Expand python variables in a string.

        The depth argument indicates how many frames above the caller should
        be walked to look for the local namespace where to expand variables.

        The global namespace for expansion is always the user's interactive
        namespace.


def mktempfile(self, data=None, prefix='<STR_LIT>'):

filename = tempfile.mktemp('<STR_LIT>', prefix)<EOL>self.tempfiles.append(filename)<EOL>if data:<EOL><INDENT>tmp_file = open(filename,'<STR_LIT:w>')<EOL>tmp_file.write(data)<EOL>tmp_file.close()<EOL><DEDENT>return filename<EOL>

Make a new tempfile and return its filename.

        This makes a call to tempfile.mktemp, but it registers the created
        filename internally so ipython cleans it up at exit time.

        Optional inputs:

          - data(None): if data is given, it gets written out to the temp file
          immediately, and the file is closed again.


io.stdout.write(data)<EOL>


io.stderr.write(data)<EOL>

Write a string to the default error output


page.page(IPython.core.usage.interactive_usage)<EOL>


def extract_input_lines(self, range_str, raw=False):

lines = self.history_manager.get_range_by_str(range_str, raw=raw)<EOL>return "<STR_LIT:\n>".join(x for _, _, x in lines)<EOL>

Return as a string a set of input history slices.

        Parameters
        ----------
        range_str : string
            The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
            since this function is for use by magic functions which get their
            arguments as strings. The number before the / is the session
            number: ~n goes n back from the current session.

        Optional Parameters:
          - raw(False): by default, the processed input is used.  If this is
          true, the raw input history is used instead.

        Note that slices can be called with two notations:

        N:M -> standard python form, means including items N...(M-1).

        N-M -> include items N..M (closed endpoint).


def find_user_code(self, target, raw=True, py_only=False):

code = self.extract_input_lines(target, raw=raw)  <EOL>if code:<EOL><INDENT>return code<EOL><DEDENT>utarget = unquote_filename(target)<EOL>try:<EOL><INDENT>if utarget.startswith(('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>return openpy.read_py_url(utarget, skip_encoding_cookie=True)<EOL><DEDENT><DEDENT>except UnicodeDecodeError:<EOL><INDENT>if not py_only :<EOL><INDENT>response = urllib.request.urlopen(target)<EOL>return response.read().decode('<STR_LIT>')<EOL><DEDENT>raise ValueError(("<STR_LIT>") % utarget)<EOL><DEDENT>potential_target = [target]<EOL>try :<EOL><INDENT>potential_target.insert(<NUM_LIT:0>,get_py_filename(target))<EOL><DEDENT>except IOError:<EOL><INDENT>pass<EOL><DEDENT>for tgt in potential_target :<EOL><INDENT>if os.path.isfile(tgt):                        <EOL><INDENT>try :<EOL><INDENT>return openpy.read_py_file(tgt, skip_encoding_cookie=True)<EOL><DEDENT>except UnicodeDecodeError :<EOL><INDENT>if not py_only :<EOL><INDENT>with io_open(tgt,'<STR_LIT:r>', encoding='<STR_LIT>') as f :<EOL><INDENT>return f.read()<EOL><DEDENT><DEDENT>raise ValueError(("<STR_LIT>") % target)<EOL><DEDENT><DEDENT><DEDENT>try:                                              <EOL><INDENT>codeobj = eval(target, self.user_ns)<EOL><DEDENT>except Exception:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>") % target)<EOL><DEDENT>if isinstance(codeobj, str):<EOL><INDENT>return codeobj<EOL><DEDENT>elif isinstance(codeobj, Macro):<EOL><INDENT>return codeobj.value<EOL><DEDENT>raise TypeError("<STR_LIT>" % target,<EOL>codeobj)<EOL>

Get a code string from history, file, url, or a string or macro.

        This is mainly used by magic functions.

        Parameters
        ----------

        target : str

          A string specifying code to retrieve. This will be tried respectively
          as: ranges of input history (see %history for syntax), url,
          correspnding .py file, filename, or an expression evaluating to a
          string or Macro in the user namespace.

        raw : bool
          If true (default), retrieve raw history. Has no effect on the other
          retrieval mechanisms.

        py_only : bool (default False)
          Only try to fetch python code, do not try alternative methods to decode file
          if unicode fails.

        Returns
        -------
        A string of code.

        ValueError is raised if nothing is found, and TypeError if it evaluates
        to an object of another type. In each case, .args[0] is a printable
        message.


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


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.


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

Display the pretty (default) representation of an object.

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


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

Display the HTML representation of an object.

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


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

Display the SVG representation of an object.

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


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

Display the PNG representation of an object.

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


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

Display the JPEG representation of an object.

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


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]


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

Display the JSON representation of an object.

    Note that not many frontends support displaying JSON.

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


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

Display the Javascript representation of an object.

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


def clear_output(stdout=True, stderr=True, other=True):

from IPython.core.interactiveshell import InteractiveShell<EOL>if InteractiveShell.initialized():<EOL><INDENT>InteractiveShell.instance().display_pub.clear_output(<EOL>stdout=stdout, stderr=stderr, other=other,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>from IPython.utils import io<EOL>if stdout:<EOL><INDENT>print('<STR_LIT>', file=io.stdout, end='<STR_LIT>')<EOL>io.stdout.flush()<EOL><DEDENT>if stderr:<EOL><INDENT>print('<STR_LIT>', file=io.stderr, end='<STR_LIT>')<EOL>io.stderr.flush()<EOL><DEDENT><DEDENT>

Clear the output of the current cell receiving output.

    Optionally, each of stdout/stderr or other non-stream data (e.g. anything
    produced by display()) can be excluded from the clear event.

    By default, everything is cleared.

    Parameters
    ----------
    stdout : bool [default: True]
        Whether to clear stdout.
    stderr : bool [default: True]
        Whether to clear stderr.
    other : bool [default: True]
        Whether to clear everything else that is not stdout/stderr
        (e.g. figures,images,HTML, any result of display()).


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

if data is not None and data.startswith('<STR_LIT:http>'):<EOL><INDENT>self.url = data<EOL>self.filename = None<EOL>self.data = None<EOL><DEDENT>else:<EOL><INDENT>self.data = data<EOL>self.url = url<EOL>self.filename = None if filename is None else unicode(filename)<EOL><DEDENT>self.reload()<EOL>

Create a 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. The MIME type of the data should match the
        subclasses used, so the Png subclass should be used for 'image/png'
        data. If the data is a URL, the data will first be downloaded
        and then displayed. If

        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.


if self.filename is not None:<EOL><INDENT>with open(self.filename, self._read_flags) as f:<EOL><INDENT>self.data = f.read()<EOL><DEDENT><DEDENT>elif self.url is not None:<EOL><INDENT>try:<EOL><INDENT>import urllib2<EOL>response = urllib2.urlopen(self.url)<EOL>self.data = response.read()<EOL>encoding = None<EOL>for sub in response.headers['<STR_LIT>'].split('<STR_LIT:;>'):<EOL><INDENT>sub = sub.strip()<EOL>if sub.startswith('<STR_LIT>'):<EOL><INDENT>encoding = sub.split('<STR_LIT:=>')[-<NUM_LIT:1>].strip()<EOL>break<EOL><DEDENT><DEDENT>if encoding:<EOL><INDENT>self.data = self.data.decode(encoding, '<STR_LIT:replace>')<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.data = None<EOL><DEDENT><DEDENT>


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.


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')


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


return ['<STR_LIT>','<STR_LIT>'][tag]<EOL>

Return an ON/OFF string for a 1/0 input. Simple utility function.


head, tail = dh[:-<NUM_LIT:10>], dh[-<NUM_LIT:10>:]<EOL>newhead = []<EOL>done = set()<EOL>for h in head:<EOL><INDENT>if h in done:<EOL><INDENT>continue<EOL><DEDENT>newhead.append(h)<EOL>done.add(h)<EOL><DEDENT>return newhead + tail<EOL>

Compress a directory history into a new one with at most 20 entries.

    Return a new list made from the first and last 10 elements of dhist after
    removal of duplicates.


func.needs_local_scope = True<EOL>return func<EOL>

Decorator to mark magic functions which need to local scope to run.


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.


def record_magic(dct, magic_kind, magic_name, func):

if magic_kind == '<STR_LIT>':<EOL><INDENT>dct['<STR_LIT>'][magic_name] = dct['<STR_LIT>'][magic_name] = func<EOL><DEDENT>else:<EOL><INDENT>dct[magic_kind][magic_name] = func<EOL><DEDENT>

Utility function to store a function as a magic of a specific kind.

    Parameters
    ----------
    dct : dict
      A dictionary with 'line' and 'cell' subdicts.

    magic_kind : str
      Kind of magic to be stored.

    magic_name : str
      Key to store the magic as.

    func : function
      Callable object to store.


if magic_kind not in magic_spec:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>magic_kinds, magic_kind)<EOL><DEDENT>

Ensure that the given magic_kind is valid.

    Check that the given magic_kind is one of the accepted spec types (stored
    in the global `magic_spec`), raise ValueError otherwise.


validate_type(magic_kind)<EOL>def magic_deco(arg):<EOL><INDENT>call = lambda f, *a, **k: f(*a, **k)<EOL>if callable(arg):<EOL><INDENT>func = arg<EOL>name = func.__name__<EOL>retval = decorator(call, func)<EOL>record_magic(magics, magic_kind, name, name)<EOL><DEDENT>elif isinstance(arg, str):<EOL><INDENT>name = arg<EOL>def mark(func, *a, **kw):<EOL><INDENT>record_magic(magics, magic_kind, name, func.__name__)<EOL>return decorator(call, func)<EOL><DEDENT>retval = mark<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return retval<EOL><DEDENT>magic_deco.__doc__ = _docstring_template.format('<STR_LIT>', magic_kind)<EOL>return magic_deco<EOL>

Decorator factory for methods in Magics subclasses.


validate_type(magic_kind)<EOL>def magic_deco(arg):<EOL><INDENT>call = lambda f, *a, **k: f(*a, **k)<EOL>caller = sys._getframe(<NUM_LIT:1>)<EOL>for ns in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>get_ipython = getattr(caller, ns).get('<STR_LIT>')<EOL>if get_ipython is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NameError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>ip = get_ipython()<EOL>if callable(arg):<EOL><INDENT>func = arg<EOL>name = func.__name__<EOL>ip.register_magic_function(func, magic_kind, name)<EOL>retval = decorator(call, func)<EOL><DEDENT>elif isinstance(arg, str):<EOL><INDENT>name = arg<EOL>def mark(func, *a, **kw):<EOL><INDENT>ip.register_magic_function(func, magic_kind, name)<EOL>return decorator(call, func)<EOL><DEDENT>retval = mark<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return retval<EOL><DEDENT>ds = _docstring_template.format('<STR_LIT>', magic_kind)<EOL>ds += dedent("""<STR_LIT>""")<EOL>magic_deco.__doc__ = ds<EOL>return magic_deco<EOL>

Decorator factory for standalone functions.


return self._auto_status[self.auto_magic]<EOL>

Return descriptive string with automagic status.


return self.magics<EOL>

Return a dict of currently available magic functions.

        The return dict has the keys 'line' and 'cell', corresponding to the
        two types of magics we support.  Each value is a list of names.


def lsmagic_docs(self, brief=False, missing='<STR_LIT>'):

docs = {}<EOL>for m_type in self.magics:<EOL><INDENT>m_docs = {}<EOL>for m_name, m_func in self.magics[m_type].items():<EOL><INDENT>if m_func.__doc__:<EOL><INDENT>if brief:<EOL><INDENT>m_docs[m_name] = m_func.__doc__.split('<STR_LIT:\n>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>m_docs[m_name] = m_func.__doc__.rstrip()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>m_docs[m_name] = missing<EOL><DEDENT><DEDENT>docs[m_type] = m_docs<EOL><DEDENT>return docs<EOL>

Return dict of documentation of magic functions.

        The return dict has the keys 'line' and 'cell', corresponding to the
        two types of magics we support. Each value is a dict keyed by magic
        name whose value is the function docstring. If a docstring is
        unavailable, the value of `missing` is used instead.

        If brief is True, only the first line of each docstring will be returned.


<EOL>for m in magic_objects:<EOL><INDENT>if not m.registered:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if type(m) in (type, MetaHasTraits):<EOL><INDENT>m = m(shell=self.shell)<EOL><DEDENT>self.registry[m.__class__.__name__] = m<EOL>for mtype in magic_kinds:<EOL><INDENT>self.magics[mtype].update(m.magics[mtype])<EOL><DEDENT><DEDENT>

Register one or more instances of Magics.

        Take one or more classes or instances of classes that subclass the main
        `core.Magic` class, and register them with IPython to use the magic
        functions they provide.  The registration process will then ensure that
        any methods that have decorated to provide line and/or cell magics will
        be recognized with the `%x`/`%%x` syntax as a line/cell magic
        respectively.

        If classes are given, they will be instantiated with the default
        constructor.  If your classes need a custom constructor, you should
        instanitate them first and pass the instance.

        The provided arguments can be an arbitrary mix of classes and instances.

        Parameters
        ----------
        magic_objects : one or more classes or instances


def register_function(self, func, magic_kind='<STR_LIT>', magic_name=None):

<EOL>validate_type(magic_kind)<EOL>magic_name = func.__name__ if magic_name is None else magic_name<EOL>setattr(self.user_magics, magic_name, func)<EOL>record_magic(self.magics, magic_kind, magic_name, func)<EOL>

Expose a standalone function as magic function for IPython.

        This will create an IPython magic (line, cell or both) from a
        standalone function.  The functions should have the following
        signatures:

        * For line magics: `def f(line)`
        * For cell magics: `def f(line, cell)`
        * For a function that does both: `def f(line, cell=None)`

        In the latter case, the function will be called with `cell==None` when
        invoked as `%f`, and with cell as a string when invoked as `%%f`.

        Parameters
        ----------
        func : callable
          Function to be registered as a magic.

        magic_kind : str
          Kind of magic, one of 'line', 'cell' or 'line_cell'

        magic_name : optional str
          If given, the name the magic will have in the IPython namespace.  By
          default, the name of the function itself is used.


meth = types.MethodType(func, self.user_magics)<EOL>setattr(self.user_magics, name, meth)<EOL>record_magic(self.magics, '<STR_LIT>', name, meth)<EOL>

[Deprecated] Expose own function as magic function for IPython.

        Example::

            def foo_impl(self, parameter_s=''):
                'My very own magic!. (Use docstrings, IPython reads them).'
                print 'Magic function. Passed parameter is between < >:'
                print '<%s>' % parameter_s
                print 'The self object is:', self

            ip.define_magic('foo',foo_impl)


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>


def parse_options(self, arg_str, opt_str, *long_opts, **kw):

<EOL>caller = sys._getframe(<NUM_LIT:1>).f_code.co_name<EOL>arg_str = '<STR_LIT>' % (self.options_table.get(caller,'<STR_LIT>'),arg_str)<EOL>mode = kw.get('<STR_LIT>','<STR_LIT:string>')<EOL>if mode not in ['<STR_LIT:string>','<STR_LIT:list>']:<EOL><INDENT>raise ValueError('<STR_LIT>' % mode)<EOL><DEDENT>list_all = kw.get('<STR_LIT>',<NUM_LIT:0>)<EOL>posix = kw.get('<STR_LIT>', os.name == '<STR_LIT>')<EOL>strict = kw.get('<STR_LIT:strict>', True)<EOL>odict = {}  <EOL>args = arg_str.split()<EOL>if len(args) >= <NUM_LIT:1>:<EOL><INDENT>argv = arg_split(arg_str, posix, strict)<EOL>try:<EOL><INDENT>opts,args = getopt(argv, opt_str, long_opts)<EOL><DEDENT>except GetoptError as e:<EOL><INDENT>raise UsageError('<STR_LIT>' % (e.msg,opt_str,<EOL>"<STR_LIT:U+0020>".join(long_opts)))<EOL><DEDENT>for o,a in opts:<EOL><INDENT>if o.startswith('<STR_LIT>'):<EOL><INDENT>o = o[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>o = o[<NUM_LIT:1>:]<EOL><DEDENT>try:<EOL><INDENT>odict[o].append(a)<EOL><DEDENT>except AttributeError:<EOL><INDENT>odict[o] = [odict[o],a]<EOL><DEDENT>except KeyError:<EOL><INDENT>if list_all:<EOL><INDENT>odict[o] = [a]<EOL><DEDENT>else:<EOL><INDENT>odict[o] = a<EOL><DEDENT><DEDENT><DEDENT><DEDENT>opts = Struct(odict)<EOL>if mode == '<STR_LIT:string>':<EOL><INDENT>args = '<STR_LIT:U+0020>'.join(args)<EOL><DEDENT>return opts,args<EOL>

Parse options passed to an argument string.

        The interface is similar to that of getopt(), but it returns back a
        Struct with the options as keys and the stripped argument string still
        as a string.

        arg_str is quoted as a true sys.argv vector by using shlex.split.
        This allows us to easily expand variables, glob files, quote
        arguments, etc.

        Options:
          -mode: default 'string'. If given as 'list', the argument string is
          returned as a list (split on whitespace) instead of a string.

          -list_all: put all option values in lists. Normally only options
          appearing more than once are put in a list.

          -posix (True): whether to split the input line in POSIX mode or not,
          as per the conventions outlined in the shlex module from the
          standard library.


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


infodict = dict(zip_longest(info_fields, [None]))<EOL>infodict.update(kw)<EOL>return infodict<EOL>

Make an object info dict with all fields present.


<EOL>try:<EOL><INDENT>ds = obj.getdoc()<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if isinstance(ds, str):<EOL><INDENT>return inspect.cleandoc(ds)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>return inspect.getdoc(obj)<EOL><DEDENT>except Exception:<EOL><INDENT>return None<EOL><DEDENT>

Stable wrapper around inspect.getdoc.

    This can't crash because of attribute problems.

    It also attempts to call a getdoc() method on the given object.  This
    allows objects which provide their docstrings via non-standard mechanisms
    (like Pyro proxies) to still be inspected by ipython's ? system.


if is_binary:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>if hasattr(obj,"<STR_LIT>"):<EOL><INDENT>obj = obj.__wrapped__<EOL><DEDENT>try:<EOL><INDENT>src = inspect.getsource(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(obj,'<STR_LIT>'):<EOL><INDENT>src = inspect.getsource(obj.__class__)<EOL><DEDENT><DEDENT>return src<EOL><DEDENT>

Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Inputs:

    - obj: an object whose source code we will attempt to extract.

    Optional inputs:

    - is_binary: whether the object is known to come from a binary source.
    This implementation will skip returning any output for binary objects, but
    custom extractors may know how to meaningfully process them.


if inspect.isfunction(obj):<EOL><INDENT>func_obj = obj<EOL><DEDENT>elif inspect.ismethod(obj):<EOL><INDENT>func_obj = obj.__func__<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>'):<EOL><INDENT>func_obj = obj.__call__<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>args, varargs, varkw = inspect.getargs(func_obj.__code__)<EOL>return args, varargs, varkw, func_obj.__defaults__<EOL>

Get the names and default values of a function's arguments.

    A tuple of four things is returned: (args, varargs, varkw, defaults).
    'args' is a list of the argument names (it may contain nested lists).
    'varargs' and 'varkw' are the names of the * and ** arguments or None.
    'defaults' is an n-tuple of the default values of the last n arguments.

    Modified version of inspect.getargspec from the Python Standard
    Library.


return inspect.formatargspec(argspec['<STR_LIT:args>'], argspec['<STR_LIT>'],<EOL>argspec['<STR_LIT>'], argspec['<STR_LIT>'])<EOL>

Format argspect, convenience wrapper around inspect's.

    This takes a dict instead of ordered arguments and calls
    inspect.format_argspec with the arguments in the necessary order.


<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).


<EOL>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>obj = obj.__wrapped__<EOL><DEDENT>fname = None<EOL>try:<EOL><INDENT>fname = inspect.getabsfile(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>fname = inspect.getabsfile(obj.__class__)<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return fname<EOL>

Find the absolute path to the file where an object was defined.

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

    Returns None if no file can be found.

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

    Returns
    -------
    fname : str
      The absolute path to the file where the object was defined.


<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.


try:<EOL><INDENT>hdef = oname + inspect.formatargspec(*getargspec(obj))<EOL>return py3compat.unicode_to_str(hdef, '<STR_LIT:ascii>')<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>

Return the definition header for any callable object.

        If any exception is generated, None is returned instead and the
        exception is suppressed.


return '<STR_LIT>' % (self.color_table.active_colors.header,h,<EOL>self.color_table.active_colors.normal)<EOL>

Return a header string with proper colors.


print('<STR_LIT>' % msg, end='<STR_LIT:U+0020>')<EOL>if oname:<EOL><INDENT>print('<STR_LIT>' % oname)<EOL><DEDENT>else:<EOL><INDENT>print()<EOL><DEDENT>

Generic message when no information is found.


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.


def pfile(self, obj, oname='<STR_LIT>'):

lineno = find_source_lines(obj)<EOL>if lineno is None:<EOL><INDENT>self.noinfo('<STR_LIT:file>', oname)<EOL>return<EOL><DEDENT>ofile = find_file(obj)<EOL>if ofile.endswith(('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>print('<STR_LIT>' % ofile)<EOL><DEDENT>elif not os.path.isfile(ofile):<EOL><INDENT>print('<STR_LIT>' % ofile)<EOL><DEDENT>else:<EOL><INDENT>page.page(self.format(open(ofile).read()), lineno-<NUM_LIT:1>)<EOL><DEDENT>

Show the whole file where an object was defined.


def _format_fields(self, fields, title_width=<NUM_LIT:12>):

out = []<EOL>header = self.__head<EOL>for title, content in fields:<EOL><INDENT>if len(content.splitlines()) > <NUM_LIT:1>:<EOL><INDENT>title = header(title + "<STR_LIT::>") + "<STR_LIT:\n>"<EOL><DEDENT>else:<EOL><INDENT>title = header((title+"<STR_LIT::>").ljust(title_width))<EOL><DEDENT>out.append(title + content)<EOL><DEDENT>return "<STR_LIT:\n>".join(out)<EOL>

Formats a list of fields for display.

        Parameters
        ----------
        fields : list
          A list of 2-tuples: (field_title, field_content)
        title_width : int
          How many characters to pad titles to. Default 12.


info = self.info(obj, oname=oname, formatter=formatter,<EOL>info=info, detail_level=detail_level)<EOL>displayfields = []<EOL>def add_fields(fields):<EOL><INDENT>for title, key in fields:<EOL><INDENT>field = info[key]<EOL>if field is not None:<EOL><INDENT>displayfields.append((title, field.rstrip()))<EOL><DEDENT><DEDENT><DEDENT>add_fields(self.pinfo_fields1)<EOL>if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['<STR_LIT>']:<EOL><INDENT>displayfields.append(("<STR_LIT>", info['<STR_LIT>'].rstrip()))<EOL><DEDENT>add_fields(self.pinfo_fields2)<EOL>if info['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>displayfields.append(("<STR_LIT>", info['<STR_LIT>'].rstrip()))<EOL><DEDENT>add_fields(self.pinfo_fields3)<EOL>if detail_level > <NUM_LIT:0> and info['<STR_LIT:source>'] is not None:<EOL><INDENT>displayfields.append(("<STR_LIT>", self.format(py3compat.cast_bytes_py2(info['<STR_LIT:source>']))))<EOL><DEDENT>elif info['<STR_LIT>'] is not None:<EOL><INDENT>displayfields.append(("<STR_LIT>", info["<STR_LIT>"]))<EOL><DEDENT>if info['<STR_LIT>']:<EOL><INDENT>if info['<STR_LIT>'] or info['<STR_LIT>']:<EOL><INDENT>displayfields.append(("<STR_LIT>", "<STR_LIT>"))<EOL>if info['<STR_LIT>'] is not None:<EOL><INDENT>displayfields.append(("<STR_LIT>",<EOL>info['<STR_LIT>'].rstrip()))<EOL><DEDENT>if info['<STR_LIT>'] is not None:<EOL><INDENT>displayfields.append(("<STR_LIT>",<EOL>indent(info['<STR_LIT>'])))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>add_fields(self.pinfo_fields_obj)<EOL><DEDENT>if displayfields:<EOL><INDENT>page.page(self._format_fields(displayfields))<EOL><DEDENT>

Show detailed information about an object.

        Optional arguments:

        - oname: name of the variable pointing to the object.

        - formatter: special formatter for docstrings (see pdoc)

        - info: a structure with some information fields which may have been
        precomputed already.

        - detail_level: if set to 1, more information is given.


def info(self, obj, oname='<STR_LIT>', formatter=None, info=None, detail_level=<NUM_LIT:0>):

obj_type = type(obj)<EOL>header = self.__head<EOL>if info is None:<EOL><INDENT>ismagic = <NUM_LIT:0><EOL>isalias = <NUM_LIT:0><EOL>ospace = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>ismagic = info.ismagic<EOL>isalias = info.isalias<EOL>ospace = info.namespace<EOL><DEDENT>if isalias:<EOL><INDENT>if not callable(obj):<EOL><INDENT>try:<EOL><INDENT>ds = "<STR_LIT>" % obj[<NUM_LIT:1>]<EOL><DEDENT>except:<EOL><INDENT>ds = "<STR_LIT>" + str(obj)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ds = "<STR_LIT>" + str(obj)<EOL>if obj.__doc__:<EOL><INDENT>ds += "<STR_LIT>" + obj.__doc__<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>ds = getdoc(obj)<EOL>if ds is None:<EOL><INDENT>ds = '<STR_LIT>'<EOL><DEDENT><DEDENT>if formatter is not None:<EOL><INDENT>ds = formatter(ds)<EOL><DEDENT>out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)<EOL>string_max = <NUM_LIT:200> <EOL>shalf = int((string_max -<NUM_LIT:5>)/<NUM_LIT:2>)<EOL>if ismagic:<EOL><INDENT>obj_type_name = '<STR_LIT>'<EOL><DEDENT>elif isalias:<EOL><INDENT>obj_type_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>obj_type_name = obj_type.__name__<EOL><DEDENT>out['<STR_LIT>'] = obj_type_name<EOL>try:<EOL><INDENT>bclass = obj.__class__<EOL>out['<STR_LIT>'] = str(bclass)<EOL><DEDENT>except: pass<EOL>if detail_level >= self.str_detail_level:<EOL><INDENT>try:<EOL><INDENT>ostr = str(obj)<EOL>str_head = '<STR_LIT>'<EOL>if not detail_level and len(ostr)>string_max:<EOL><INDENT>ostr = ostr[:shalf] + '<STR_LIT>' + ostr[-shalf:]<EOL>ostr = ("<STR_LIT:\n>" + "<STR_LIT:U+0020>" * len(str_head.expandtabs())).join(q.strip() for q in ostr.split("<STR_LIT:\n>"))<EOL><DEDENT>out[str_head] = ostr<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if ospace:<EOL><INDENT>out['<STR_LIT>'] = ospace<EOL><DEDENT>try:<EOL><INDENT>out['<STR_LIT>'] = str(len(obj))<EOL><DEDENT>except: pass<EOL>binary_file = False<EOL>fname = find_file(obj)<EOL>if fname is None:<EOL><INDENT>binary_file = True<EOL><DEDENT>else:<EOL><INDENT>if fname.endswith(('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>binary_file = True<EOL><DEDENT>elif fname.endswith('<STR_LIT>'):<EOL><INDENT>fname = '<STR_LIT>'<EOL><DEDENT>out['<STR_LIT:file>'] = fname<EOL><DEDENT>defln = self._getdef(obj, oname)<EOL>if defln:<EOL><INDENT>out['<STR_LIT>'] = self.format(defln)<EOL><DEDENT>if ds and detail_level == <NUM_LIT:0>:<EOL><INDENT>out['<STR_LIT>'] = ds<EOL><DEDENT>if detail_level:<EOL><INDENT>linecache.checkcache()<EOL>source = None<EOL>try:<EOL><INDENT>try:<EOL><INDENT>source = getsource(obj, binary_file)<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>source = getsource(obj.__class__, binary_file)<EOL><DEDENT><DEDENT>if source is not None:<EOL><INDENT>out['<STR_LIT:source>'] = source.rstrip()<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>if ds and source is None:<EOL><INDENT>out['<STR_LIT>'] = ds<EOL><DEDENT><DEDENT>if inspect.isclass(obj):<EOL><INDENT>out['<STR_LIT>'] = True<EOL>try:<EOL><INDENT>obj_init =  obj.__init__<EOL><DEDENT>except AttributeError:<EOL><INDENT>init_def = init_ds = None<EOL><DEDENT>else:<EOL><INDENT>init_def = self._getdef(obj_init,oname)<EOL>init_ds  = getdoc(obj_init)<EOL>if init_ds andinit_ds.startswith('<STR_LIT>'):<EOL><INDENT>init_ds = None<EOL><DEDENT><DEDENT>if init_def or init_ds:<EOL><INDENT>if init_def:<EOL><INDENT>out['<STR_LIT>'] = self.format(init_def)<EOL><DEDENT>if init_ds:<EOL><INDENT>out['<STR_LIT>'] = init_ds<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if ds:<EOL><INDENT>try:<EOL><INDENT>cls = getattr(obj,'<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>class_ds = None<EOL><DEDENT>else:<EOL><INDENT>class_ds = getdoc(cls)<EOL><DEDENT>if class_ds and(class_ds.startswith('<STR_LIT>') orclass_ds.startswith('<STR_LIT>') orclass_ds.startswith('<STR_LIT>') ):<EOL><INDENT>class_ds = None<EOL><DEDENT>if class_ds and ds != class_ds:<EOL><INDENT>out['<STR_LIT>'] = class_ds<EOL><DEDENT><DEDENT>try:<EOL><INDENT>init_ds = getdoc(obj.__init__)<EOL>if init_ds andinit_ds.startswith('<STR_LIT>'):<EOL><INDENT>init_ds = None<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>init_ds = None<EOL><DEDENT>if init_ds:<EOL><INDENT>out['<STR_LIT>'] = init_ds<EOL><DEDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>call_def = self._getdef(obj.__call__, oname)<EOL>if call_def is not None:<EOL><INDENT>out['<STR_LIT>'] = self.format(call_def)<EOL><DEDENT>call_ds = getdoc(obj.__call__)<EOL>if call_ds and call_ds.startswith('<STR_LIT>'):<EOL><INDENT>call_ds = None<EOL><DEDENT>if call_ds:<EOL><INDENT>out['<STR_LIT>'] = call_ds<EOL><DEDENT><DEDENT><DEDENT>if inspect.isclass(obj):<EOL><INDENT>callable_obj = getattr(obj, "<STR_LIT>", None)<EOL><DEDENT>elif callable(obj):<EOL><INDENT>callable_obj = obj<EOL><DEDENT>else:<EOL><INDENT>callable_obj = None<EOL><DEDENT>if callable_obj:<EOL><INDENT>try:<EOL><INDENT>args,  varargs, varkw, defaults = getargspec(callable_obj)<EOL><DEDENT>except (TypeError, AttributeError):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>out['<STR_LIT>'] = dict(args=args, varargs=varargs,<EOL>varkw=varkw, defaults=defaults)<EOL><DEDENT><DEDENT>return object_info(**out)<EOL>

Compute a dict with detailed information about an object.

        Optional arguments:

        - oname: name of the variable pointing to the object.

        - formatter: special formatter for docstrings (see pdoc)

        - info: a structure with some information fields which may have been
        precomputed already.

        - detail_level: if set to 1, more information is given.


<EOL>type_pattern = '<STR_LIT:all>'<EOL>filter = '<STR_LIT>'<EOL>cmds = pattern.split()<EOL>len_cmds  =  len(cmds)<EOL>if len_cmds == <NUM_LIT:1>:<EOL><INDENT>filter = cmds[<NUM_LIT:0>]<EOL><DEDENT>elif len_cmds == <NUM_LIT:2>:<EOL><INDENT>filter,type_pattern = cmds<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>pattern)<EOL><DEDENT>for name in ns_search:<EOL><INDENT>if name not in ns_table:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(name,list(ns_table.keys())))<EOL><DEDENT><DEDENT>search_result, namespaces_seen = set(), set()<EOL>for ns_name in ns_search:<EOL><INDENT>ns = ns_table[ns_name]<EOL>if id(ns) in namespaces_seen:<EOL><INDENT>continue<EOL><DEDENT>namespaces_seen.add(id(ns))<EOL>tmp_res = list_namespace(ns, type_pattern, filter,<EOL>ignore_case=ignore_case, show_all=show_all)<EOL>search_result.update(tmp_res)<EOL><DEDENT>page.page('<STR_LIT:\n>'.join(sorted(search_result)))<EOL>

Search namespaces with wildcards for objects.

        Arguments:

        - pattern: string containing shell-like wildcards to use in namespace
        searches and optionally a type specification to narrow the search to
        objects of that type.

        - ns_table: dict of name->namespaces for search.

        Optional arguments:

          - ns_search: list of namespace names to include in search.

          - ignore_case(False): make the search case-insensitive.

          - show_all(False): show all names, including those starting with
          underscores.


Print a message about internal inspect errors.

    These are unfortunately quite common.


file = getsourcefile(object) or getfile(object)<EOL>globals_dict = None<EOL>if inspect.isframe(object):<EOL><INDENT>globals_dict = object.f_globals<EOL><DEDENT>else:<EOL><INDENT>module = getmodule(object, file)<EOL>if module:<EOL><INDENT>globals_dict = module.__dict__<EOL><DEDENT><DEDENT>lines = linecache.getlines(file, globals_dict)<EOL>if not lines:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>if ismodule(object):<EOL><INDENT>return lines, <NUM_LIT:0><EOL><DEDENT>if isclass(object):<EOL><INDENT>name = object.__name__<EOL>pat = re.compile(r'<STR_LIT>' + name + r'<STR_LIT>')<EOL>candidates = []<EOL>for i in range(len(lines)):<EOL><INDENT>match = pat.match(lines[i])<EOL>if match:<EOL><INDENT>if lines[i][<NUM_LIT:0>] == '<STR_LIT:c>':<EOL><INDENT>return lines, i<EOL><DEDENT>candidates.append((match.group(<NUM_LIT:1>), i))<EOL><DEDENT><DEDENT>if candidates:<EOL><INDENT>candidates.sort()<EOL>return lines, candidates[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT><DEDENT>if ismethod(object):<EOL><INDENT>object = object.__func__<EOL><DEDENT>if isfunction(object):<EOL><INDENT>object = object.__code__<EOL><DEDENT>if istraceback(object):<EOL><INDENT>object = object.tb_frame<EOL><DEDENT>if isframe(object):<EOL><INDENT>object = object.f_code<EOL><DEDENT>if iscode(object):<EOL><INDENT>if not hasattr(object, '<STR_LIT>'):<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>pat = re.compile(r'<STR_LIT>')<EOL>pmatch = pat.match<EOL>lnum = min(object.co_firstlineno,len(lines))-<NUM_LIT:1><EOL>while lnum > <NUM_LIT:0>:<EOL><INDENT>if pmatch(lines[lnum]): break<EOL>lnum -= <NUM_LIT:1><EOL><DEDENT>return lines, lnum<EOL><DEDENT>raise IOError('<STR_LIT>')<EOL>

Return the entire source file and starting line number for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a list of all the lines
    in the file and the line number indexes a line in that list.  An IOError
    is raised if the source code cannot be retrieved.

    FIXED version with which we monkeypatch the stdlib to work around a bug.


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 io.stdout if self._ostream is None else self._ostream<EOL>

Output stream that exceptions are written to.

        Valid values are:

        - None: the default, which means that IPython will dynamically resolve
        to io.stdout.  This ensures compatibility with most tools, including
        Windows (where plain stdout doesn't recognize ANSI escapes).

        - Any object with 'write' and 'flush' attributes.


<EOL>self.color_scheme_table.set_active_scheme(*args,**kw)<EOL>self.Colors = self.color_scheme_table.active_colors<EOL>if hasattr(self,'<STR_LIT>') and self.pdb is not None:<EOL><INDENT>self.pdb.set_colors(*args,**kw)<EOL><DEDENT>

Shorthand access to the color table scheme selector method.


if self.color_scheme_table.active_scheme_name == '<STR_LIT>':<EOL><INDENT>self.color_scheme_table.set_active_scheme(self.old_scheme)<EOL>self.Colors = self.color_scheme_table.active_colors<EOL><DEDENT>else:<EOL><INDENT>self.old_scheme = self.color_scheme_table.active_scheme_name<EOL>self.color_scheme_table.set_active_scheme('<STR_LIT>')<EOL>self.Colors = self.color_scheme_table.active_colors<EOL><DEDENT>

Toggle between the currently active color scheme and NoColor.


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

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


def text(self, etype, value, tb, tb_offset=None, context=<NUM_LIT:5>):

tb_list = self.structured_traceback(etype, value, tb,<EOL>tb_offset, context)<EOL>return self.stb2text(tb_list)<EOL>

Return formatted traceback.

        Subclasses may override this if they add extra arguments.


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

raise NotImplementedError()<EOL>

Return a list of traceback frames.

        Must be implemented by each class.


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

tb_offset = self.tb_offset if tb_offset is None else tb_offset<EOL>Colors = self.Colors<EOL>out_list = []<EOL>if elist:<EOL><INDENT>if tb_offset and len(elist) > tb_offset:<EOL><INDENT>elist = elist[tb_offset:]<EOL><DEDENT>out_list.append('<STR_LIT>' %<EOL>(Colors.normalEm, Colors.Normal) + '<STR_LIT:\n>')<EOL>out_list.extend(self._format_list(elist))<EOL><DEDENT>lines = '<STR_LIT>'.join(self._format_exception_only(etype, value))<EOL>out_list.append(lines)<EOL>return out_list<EOL>

Return a color formatted string with the traceback info.

        Parameters
        ----------
        etype : exception type
          Type of the exception raised.

        value : object
          Data stored in the exception

        elist : list
          List of frames, see class docstring for details.

        tb_offset : int, optional
          Number of frames in the traceback to skip.  If not given, the
          instance value is used (set in constructor).

        context : int, optional
          Number of lines of context information to print.

        Returns
        -------
        String with formatted exception.


Colors = self.Colors<EOL>list = []<EOL>for filename, lineno, name, line in extracted_list[:-<NUM_LIT:1>]:<EOL><INDENT>item = '<STR_LIT>' %(Colors.filename, filename, Colors.Normal,<EOL>Colors.lineno, lineno, Colors.Normal,<EOL>Colors.name, name, Colors.Normal)<EOL>if line:<EOL><INDENT>item += '<STR_LIT>' % line.strip()<EOL><DEDENT>list.append(item)<EOL><DEDENT>filename, lineno, name, line = extracted_list[-<NUM_LIT:1>]<EOL>item = '<STR_LIT>' %(Colors.normalEm,<EOL>Colors.filenameEm, filename, Colors.normalEm,<EOL>Colors.linenoEm, lineno, Colors.normalEm,<EOL>Colors.nameEm, name, Colors.normalEm,<EOL>Colors.Normal)<EOL>if line:<EOL><INDENT>item += '<STR_LIT>' % (Colors.line, line.strip(),<EOL>Colors.Normal)<EOL><DEDENT>list.append(item)<EOL>return list<EOL>

Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py


def _format_exception_only(self, etype, value):

have_filedata = False<EOL>Colors = self.Colors<EOL>list = []<EOL>stype = Colors.excName + etype.__name__ + Colors.Normal<EOL>if value is None:<EOL><INDENT>list.append( str(stype) + '<STR_LIT:\n>')<EOL><DEDENT>else:<EOL><INDENT>if etype is SyntaxError:<EOL><INDENT>have_filedata = True<EOL>if not value.filename: value.filename = "<STR_LIT>"<EOL>list.append('<STR_LIT>' %(Colors.normalEm,<EOL>Colors.filenameEm, value.filename, Colors.normalEm,<EOL>Colors.linenoEm, value.lineno, Colors.Normal  ))<EOL>if value.text is not None:<EOL><INDENT>i = <NUM_LIT:0><EOL>while i < len(value.text) and value.text[i].isspace():<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT>list.append('<STR_LIT>' % (Colors.line,<EOL>value.text.strip(),<EOL>Colors.Normal))<EOL>if value.offset is not None:<EOL><INDENT>s = '<STR_LIT:U+0020>'<EOL>for c in value.text[i:value.offset-<NUM_LIT:1>]:<EOL><INDENT>if c.isspace():<EOL><INDENT>s += c<EOL><DEDENT>else:<EOL><INDENT>s += '<STR_LIT:U+0020>'<EOL><DEDENT><DEDENT>list.append('<STR_LIT>' % (Colors.caret, s,<EOL>Colors.Normal) )<EOL><DEDENT><DEDENT><DEDENT>try:<EOL><INDENT>s = value.msg<EOL><DEDENT>except Exception:<EOL><INDENT>s = self._some_str(value)<EOL><DEDENT>if s:<EOL><INDENT>list.append('<STR_LIT>' % (str(stype), Colors.excName,<EOL>Colors.Normal, s))<EOL><DEDENT>else:<EOL><INDENT>list.append('<STR_LIT>' % str(stype))<EOL><DEDENT><DEDENT>if have_filedata:<EOL><INDENT>ipinst = ipapi.get()<EOL>if ipinst is not None:<EOL><INDENT>ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>return list<EOL>

Format the exception part of a traceback.

        The arguments are the exception type and value such as given by
        sys.exc_info()[:2]. The return value is a list of strings, each ending
        in a newline.  Normally, the list contains a single string; however,
        for SyntaxError exceptions, it contains several lines that (when
        printed) display detailed information about where the syntax error
        occurred.  The message indicating which exception occurred is the
        always last string in the list.

        Also lifted nearly verbatim from traceback.py


def get_exception_only(self, etype, value):

return ListTB.structured_traceback(self, etype, value, [])<EOL>

Only print the exception type and message, without a traceback.

        Parameters
        ----------
        etype : exception type
        value : exception value


def show_exception_only(self, etype, evalue):

<EOL>ostream = self.ostream<EOL>ostream.flush()<EOL>ostream.write('<STR_LIT:\n>'.join(self.get_exception_only(etype, evalue)))<EOL>ostream.flush()<EOL>


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).


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.


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.


def __call__(self, etype=None, evalue=None, etb=None):

if etb is None:<EOL><INDENT>self.handler()<EOL><DEDENT>else:<EOL><INDENT>self.handler((etype, evalue, etb))<EOL><DEDENT>try:<EOL><INDENT>self.debugger()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>

This hook can replace sys.excepthook (for Python 2.1 or higher).


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


if not mode:<EOL><INDENT>new_idx = ( self.valid_modes.index(self.mode) + <NUM_LIT:1> ) %len(self.valid_modes)<EOL>self.mode = self.valid_modes[new_idx]<EOL><DEDENT>elif mode not in self.valid_modes:<EOL><INDENT>raise ValueError('<STR_LIT>'+mode+'<STR_LIT>''<STR_LIT>'+str(self.valid_modes))<EOL><DEDENT>else:<EOL><INDENT>self.mode = mode<EOL><DEDENT>self.include_vars = (self.mode == self.valid_modes[<NUM_LIT:2>])<EOL>self.tb_join_char = self._join_chars[self.mode]<EOL>

Switch to the desired mode.

        If mode is not specified, cycles through the available modes.


if out is None:<EOL><INDENT>out = self.ostream<EOL><DEDENT>out.flush()<EOL>out.write(self.text(etype, evalue, etb, tb_offset))<EOL>out.write('<STR_LIT:\n>')<EOL>out.flush()<EOL>try:<EOL><INDENT>self.debugger()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>

Print out a formatted exception traceback.

        Optional arguments:
          - out: an open file-like object to direct output to.

          - tb_offset: the number of frames to skip over in the stack, on a
          per-call basis (this overrides temporarily the instance's tb_offset
          given at initialization time.


e = self.last_syntax_error<EOL>self.last_syntax_error = None<EOL>return e<EOL>

Return the current error state and clear it


return '<STR_LIT>'.join(stb)<EOL>


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).