def Func(arg_0, arg_1: arg_2):
        """Create a submonitor with the given units"""
        arg_3 = arg_0.submonitor(arg_1)
        try:
            yield arg_3
        finally:
            if arg_3.total is None:
                # begin was never called, so the Func cannot be closed
                arg_0.update(arg_1)
            else:
                arg_3.done()


def Func(arg_0, arg_1: arg_2=1, arg_3: arg_4=None):
        """Increment the monitor with N units worked and an optional message"""
        if arg_0.total is None:
            raise Exception("Cannot call progressmonitor.Func before calling begin")
        arg_0.worked = min(arg_0.total, arg_0.worked+arg_1)
        if arg_3:
            arg_0.message = arg_3
        for arg_6 in arg_0.listeners:
            arg_6(arg_0)


def Func(arg_0, arg_1: arg_2, *arg_3, **arg_4) -> 'ProgressMonitor':
        """
        Create a sub monitor that stands for N units of work in this monitor
        The sub task should call .begin (or use @monitored / with .task) before calling updates
        """
        Func = ProgressMonitor(*arg_3, **arg_4)
        arg_0.sub_monitors[Func] = arg_1
        Func.add_listener(arg_0._submonitor_update)
        return Func


def Func(arg_0, arg_1: arg_2=None):
        """
        Signal that this task is Func.
        This is completely optional and will just call .update with the remaining work.
        """
        if arg_1 is None:
            arg_1 = "{self.name} Func".format(**locals()) if arg_0.name else "Done"
        arg_0.update(units=arg_0.total - arg_0.worked, arg_1=arg_1)


def Func(arg_0, arg_1=0, arg_2=0, arg_3=None,
         arg_4=None, arg_5=False):
    """Print a string, piping through a Funcr.

    This version ignores the screen_lines and Funcr_cmd arguments and uses
    IPython's payload system instead.

    Parameters
    ----------
    strng : str
      Text to Func.

    start : int
      Starting line at which to place the display.

    html : str, optional
      If given, an html string to send as well.

    auto_html : bool, optional
      If true, the input string is assumed to be valid reStructuredText and is
      converted to HTML with docutils.  Note that if docutils is not found,
      this option is silently ignored.

    Note
    ----

    Only one of the ``html`` and ``auto_html`` options can be given, not
    both.
    """

    # Some routines may auto-compute start offsets incorrectly and pass a
    # negative value.  Offset to 0 for robustness.
    arg_1 = max(0, arg_1)
    arg_6 = InteractiveShell.instance()

    if arg_5:
        try:
            # These defaults ensure user configuration variables for docutils
            # are not loaded, only our config is used here.
            arg_7 = {'file_insertion_enabled': 0,
                        'raw_enabled': 0,
                        '_disable_config': 1}
            arg_4 = publish_string(arg_0, writer_name='html',
                                  settings_overrides=arg_7)
        except:
            pass

    arg_8 = dict(
        source='IPython.zmq.Func.Func',
        text=arg_0,
        arg_4=arg_4,
        start_line_number=arg_1
        )
    arg_6.payload_manager.write_payload(arg_8)


def Func(arg_0):
  """Acquires the correct error for a given response.

  :param requests.Response response: HTTP error response
  :returns: the appropriate error for a given response
  :rtype: APIError

  """
  arg_1 = _status_code_to_class.get(arg_0.status_code, APIError)
  return arg_1(arg_0)


def Func(arg_0):
        """Load the config from a file and return it as a Struct."""
        arg_0.clear()
        try:
            arg_0._find_file()
        except IOError as e:
            raise ConfigFileNotFound(str(e))
        arg_0._read_file_as_dict()
        arg_0._convert_to_config()
        return arg_0.config


def Func(arg_0, arg_1, arg_2=None):
        """decode argv if bytes, using stin.encoding, falling back on default enc"""
        arg_3 = []
        if arg_2 is None:
            arg_2 = DEFAULT_ENCODING
        for arg_4 in arg_1:
            if not isinstance(arg_4, unicode):
                # only decode if not already decoded
                arg_4 = arg_4.decode(arg_2)
            arg_3.append(arg_4)
        return arg_3


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """Parse command line arguments and return as a Config object.

        Parameters
        ----------

        args : optional, list
          If given, a list with the structure of sys.argv[1:] to parse
          arguments from. If not given, the instance's self.argv attribute
          (given at construction time) is used."""
        arg_0.clear()
        if arg_1 is None:
            arg_1 = arg_0.argv
        if arg_2 is None:
            arg_2 = arg_0.aliases
        if arg_3 is None:
            arg_3 = arg_0.flags
        arg_0._create_parser(arg_2, arg_3)
        arg_0._parse_args(arg_1)
        arg_0._convert_to_config()
        return arg_0.config


def Func(arg_0, arg_1):
        """self.parser->self.parsed_data"""
        # decode sys.argv to support unicode command-line options
        arg_2 = DEFAULT_ENCODING
        arg_3 = [py3compat.cast_unicode(a, arg_2) for a in arg_1]
        arg_0.parsed_data, arg_0.extra_args = arg_0.parser.parse_known_args(arg_3)


def Func(arg_0, arg_1=None):
    """imp.Func variant that only return path of module.

    The `imp.Func` returns a filehandle that we are not interested in.
    Also we ignore any bytecode files that `imp.Func` finds.

    Parameters
    ----------
    name : str
        name of module to locate
    path : list of str
        list of paths to search for `name`. If path=None then search sys.path

    Returns
    -------
    filename : str
        Return full path of module or None if module is missing or does not have
        .py or .pyw extension
    """
    if arg_0 is None:
        return None
    try:
        arg_2, arg_3, arg_4 = imp.Func(arg_0, arg_1)
    except ImportError:
        return None
    if arg_2 is None:
        return arg_3
    else:
        arg_2.close()
    if os.path.splitext(arg_3)[1] in [".py", "pyc"]:
        return arg_3
    else:
        return None


def Func(arg_0, arg_1):
        """Register a callback to be called with this Launcher's stop_data
        when the process actually finishes.
        """
        if arg_0.state=='after':
            return arg_1(arg_0.stop_data)
        else:
            arg_0.stop_callbacks.append(arg_1)


def Func(arg_0, arg_1):
        """Call this to trigger startup actions.

        This logs the process startup and sets the state to 'running'.  It is
        a pass-through so it can be used as a callback.
        """

        arg_0.log.debug('Process %r started: %r', arg_0.args[0], arg_1)
        arg_0.start_data = arg_1
        arg_0.state = 'running'
        return arg_1


def Func(arg_0, arg_1=2.0):
        """Send INT, wait a delay and then send KILL."""
        try:
            arg_0.signal(SIGINT)
        except Exception:
            arg_0.log.debug("interrupt failed")
            pass
        arg_0.killer  = ioloop.DelayedCallback(lambda : arg_0.signal(SIGKILL), arg_1*1000, arg_0.loop)
        arg_0.killer.start()


def Func(arg_0):
        """Build self.args using all the fields."""
        return arg_0.mpi_cmd + ['-n', str(arg_0.n)] + arg_0.mpi_args + \
               arg_0.program + arg_0.program_args


def Func(arg_0, arg_1):
        """Start n instances of the program using mpiexec."""
        arg_0.n = arg_1
        return super(MPILauncher, arg_0).Func()


def Func(arg_0, arg_1, arg_2):
        """send a single file"""
        arg_2 = "%s:%s" % (arg_0.location, arg_2)
        for arg_3 in range(10):
            if not os.path.exists(arg_1):
                arg_0.log.debug("waiting for %s" % arg_1)
                time.sleep(1)
            else:
                break
        arg_0.log.info("sending %s to %s", arg_1, arg_2)
        check_output(arg_0.scp_cmd + [arg_1, arg_2])


def Func(arg_0, arg_1, arg_2):
        """fetch a single file"""
        arg_3 = "%s:%s" % (arg_0.location, arg_1)
        arg_0.log.info("fetching %s from %s", arg_2, arg_3)
        for arg_4 in range(10):
            # wait up to 10s for remote file to exist
            arg_5 = check_output(arg_0.ssh_cmd + arg_0.ssh_args + \
                [arg_0.location, 'test -e', arg_1, "&& echo 'yes' || echo 'no'"])
            arg_5 = arg_5.strip()
            if arg_5 == 'no':
                time.sleep(1)
            elif arg_5 == 'yes':
                break
        check_output(arg_0.scp_cmd + [arg_3, arg_2])


def Func(arg_0):
        """determine engine count from `engines` dict"""
        arg_1 = 0
        for arg_2 in arg_0.engines.itervalues():
            if isinstance(arg_2, (tuple,list)):
                arg_2,arg_3 = arg_2
            arg_1 += arg_2
        return arg_1


def Func(arg_0, arg_1):
        """Start engines by profile or profile_dir.
        `n` is ignored, and the `engines` config property is used instead.
        """

        arg_2 = []
        for arg_3, arg_1 in arg_0.engines.iteritems():
            if isinstance(arg_1, (tuple, list)):
                arg_1, arg_4 = arg_1
            else:
                arg_4 = copy.deepcopy(arg_0.engine_args)

            if '@' in arg_3:
                arg_5,arg_3 = arg_3.split('@',1)
            else:
                arg_5=None
            for arg_6 in range(arg_1):
                if arg_6 > 0:
                    time.sleep(arg_0.delay)
                arg_7 = arg_0.launcher_class(work_dir=arg_0.work_dir, config=arg_0.config, log=arg_0.log,
                                        profile_dir=arg_0.profile_dir, cluster_id=arg_0.cluster_id,
                )
                if arg_6 > 0:
                    # only send files for the first engine on each host
                    arg_7.to_send = []

                # Copy the engine args over to each engine launcher.
                arg_7.engine_cmd = arg_0.engine_cmd
                arg_7.engine_args = arg_4
                arg_7.on_stop(arg_0._notice_engine_stopped)
                arg_11 = arg_7.Func(arg_5=arg_5, hostname=arg_3)
                arg_0.launchers[ "%s/%i" % (arg_3,arg_6) ] = arg_7
                arg_2.append(arg_11)
        arg_0.notify_Func(arg_2)
        return arg_2


def Func(arg_0, arg_1):
        """Start n copies of the process using the Win HPC job scheduler."""
        arg_0.write_job_file(arg_1)
        arg_2 = [
            'submit',
            '/jobfile:%s' % arg_0.job_file,
            '/scheduler:%s' % arg_0.scheduler
        ]
        arg_0.log.debug("Starting Win HPC Job: %s" % (arg_0.job_cmd + ' ' + ' '.join(arg_2),))

        arg_3 = check_output([arg_0.job_cmd]+arg_2,
            env=os.environ,
            cwd=arg_0.work_dir,
            stderr=STDOUT
        )
        arg_4 = arg_0.parse_job_id(arg_3)
        arg_0.notify_Func(arg_4)
        return arg_4


def Func(arg_0):
        """load the default context with the default values for the basic keys

        because the _trait_changed methods only load the context if they
        are set to something other than the default value.
        """
        return dict(n=1, queue=u'', profile_dir=u'', cluster_id=u'')


def Func(arg_0, arg_1):
        """Take the output of the submit command and return the job id."""
        arg_2 = arg_0.job_id_regexp.search(arg_1)
        if arg_2 is not None:
            arg_3 = arg_2.group()
        else:
            raise LauncherError("Job id couldn't be determined: %s" % arg_1)
        arg_0.job_id = arg_3
        arg_0.log.info('Job submitted with job id: %r', arg_3)
        return arg_3


def Func(arg_0, arg_1):
        """Instantiate and write the batch script to the work_dir."""
        arg_0.n = arg_1
        # first priority is batch_template if set
        if arg_0.batch_template_file and not arg_0.batch_template:
            # second priority is batch_template_file
            with open(arg_0.batch_template_file) as f:
                arg_0.batch_template = f.read()
        if not arg_0.batch_template:
            # third (last) priority is default_template
            arg_0.batch_template = arg_0.default_template

            # add jobarray or queue lines to user-specified template
            # note that this is *only* when user did not specify a template.
            # print self.job_array_regexp.search(self.batch_template)
            if not arg_0.job_array_regexp.search(arg_0.batch_template):
                arg_0.log.debug("adding job array settings to batch script")
                arg_3, arg_4 = arg_0.batch_template.split('\n',1)
                arg_0.batch_template = u'\n'.join([arg_3, arg_0.job_array_template, arg_4])

            # print self.queue_regexp.search(self.batch_template)
            if arg_0.queue and not arg_0.queue_regexp.search(arg_0.batch_template):
                arg_0.log.debug("adding PBS queue settings to batch script")
                arg_3, arg_4 = arg_0.batch_template.split('\n',1)
                arg_0.batch_template = u'\n'.join([arg_3, arg_0.queue_template, arg_4])

        arg_5 = arg_0.formatter.format(arg_0.batch_template, **arg_0.context)
        arg_0.log.debug('Writing batch script: %s', arg_0.batch_file)

        with open(arg_0.batch_file, 'w') as f:
            f.write(arg_5)
        os.chmod(arg_0.batch_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)


def Func(arg_0, arg_1):
        """ Reimplemented to return a custom context menu for images.
        """
        arg_2 = arg_0._control.cursorForPosition(arg_1).charFormat()
        arg_3 = arg_2.stringProperty(QtGui.QTextFormat.ImageName)
        if arg_3:
            arg_4 = QtGui.QMenu()

            arg_4.addAction('Copy Image', lambda: arg_0._copy_image(arg_3))
            arg_4.addAction('Save Image As...', lambda: arg_0._save_image(arg_3))
            arg_4.addSeparator()

            arg_5 = arg_0._name_to_svg_map.get(arg_3, None)
            if arg_5 is not None:
                arg_4.addSeparator()
                arg_4.addAction('Copy SVG', lambda: svg_to_clipboard(arg_5))
                arg_4.addAction('Save SVG As...',
                               lambda: save_svg(arg_5, arg_0._control))
        else:
            arg_4 = super(RichIPythonWidget, arg_0).Func(arg_1)
        return arg_4


def Func(arg_0, arg_1, arg_2=False):
        """ Append raw JPG data to the widget."""
        arg_0._append_custom(arg_0._insert_jpg, arg_1, arg_2)


def Func(arg_0, arg_1, arg_2=False):
        """ Append raw PNG data to the widget.
        """
        arg_0._append_custom(arg_0._insert_png, arg_1, arg_2)


def Func(arg_0, arg_1, arg_2=False):
        """ Append raw SVG data to the widget.
        """
        arg_0._append_custom(arg_0._insert_svg, arg_1, arg_2)


def Func(arg_0, arg_1):
        """ Copies the ImageResource with 'name' to the clipboard.
        """
        arg_2 = arg_0._get_image(arg_1)
        QtGui.QApplication.clipboard().setImage(arg_2)


def Func(arg_0, arg_1):
        """ Returns the QImage stored as the ImageResource with 'name'.
        """
        arg_2 = arg_0._control.document()
        arg_3 = arg_2.resource(QtGui.QTextDocument.ImageResource,
                                  QtCore.QUrl(arg_1))
        return arg_3


def Func(arg_0, arg_1, arg_2, arg_3):
        """ insert a raw image, jpg or png """
        try:
            arg_4 = QtGui.QImage()
            arg_4.loadFromData(arg_2, arg_3.upper())
        except ValueError:
            arg_0._insert_plain_text(arg_1, 'Received invalid %s data.'%arg_3)
        else:
            arg_5 = arg_0._add_image(arg_4)
            arg_1.insertBlock()
            arg_1.insertImage(arg_5)
            arg_1.insertBlock()


def Func(arg_0):
        """Configure the user's environment.

        """
        arg_1 = os.environ
        # These two ensure 'ls' produces nice coloring on BSD-derived systems
        arg_1['TERM'] = 'xterm-color'
        arg_1['CLICOLOR'] = '1'
        # Since normal pagers don't work at all (over pexpect we don't have
        # single-key control of the subprocess), try to disable paging in
        # subprocesses as much as possible.
        arg_1['PAGER'] = 'cat'
        arg_1['GIT_PAGER'] = 'cat'

        # And install the payload version of page.
        install_payload_page()


def Func(arg_0, arg_1):
        """Called to show the auto-rewritten input for autocall and friends.

        FIXME: this payload is currently not correctly processed by the
        frontend.
        """
        arg_2 = arg_0.prompt_manager.render('rewrite') + arg_1
        arg_3 = dict(
            source='IPython.zmq.zmqshell.ZMQInteractiveShell.Func',
            transformed_input=arg_2,
            )
        arg_0.payload_manager.write_payload(arg_3)


def Func(arg_0, arg_1):
        """Send the specified text to the frontend to be presented at the next
        input cell."""
        arg_2 = dict(
            source='IPython.zmq.zmqshell.ZMQInteractiveShell.Func',
            arg_1=arg_1
        )
        arg_0.payload_manager.write_payload(arg_2)


def Func(arg_0, arg_1=None):
    """
    Converts the request parameters to Python.

    :param request: <pyramid.request.Request> || <dict>

    :return: <dict>
    """
    if type(arg_0) == dict:
        return arg_0

    arg_2 = get_payload(arg_0)

    # support in-place editing formatted request
    try:
        del arg_2['pk']
        arg_2[arg_2.pop('name')] = arg_2.pop('value')
    except KeyError:
        pass

    return {
        arg_5.rstrip('[]'): safe_eval(arg_6) if not type(arg_6) == list else [safe_eval(arg_4) for arg_4 in arg_6]
        for arg_5, arg_6 in arg_2.items()
    }


def Func(arg_0, arg_1=None):
    """
    Extracts ORB context information from the request.

    :param request: <pyramid.request.Request>
    :param model: <orb.Model> || None

    :return: {<str> key: <variant> value} values, <orb.Context>
    """
    # convert request parameters to python
    arg_2 = get_param_values(arg_0, arg_1=arg_1)

    # extract the full orb context if provided
    arg_3 = arg_2.pop('orb_context', {})
    if isinstance(arg_3, (unicode, str)):
        arg_3 = projex.rest.unjsonify(arg_3)

    # otherwise, extract the limit information
    arg_4 = 'limit' in arg_3 or 'limit' in arg_2

    # create the new orb context
    arg_5 = orb.Context(**arg_3)

    # build up context information from the request params
    arg_6 = set()
    arg_7 = {}
    for arg_8 in orb.Context.Defaults:
        if arg_8 in arg_2:
            arg_6.add(arg_8)
            arg_7[arg_8] = arg_2.get(arg_8)

    # generate a simple query object
    arg_9 = {}
    if arg_1:
        # extract match dict items
        for arg_8, arg_10 in arg_0.matchdict.items():
            if arg_1.schema().column(arg_8, raise_=False):
                arg_9[arg_8] = arg_10

        # extract payload items
        for arg_8, arg_10 in arg_2.items():
            arg_11 = arg_8.split('.')[0]
            arg_12 = arg_1.schema().column(arg_11, raise_=False) or arg_1.schema().collector(arg_11)
            if arg_12:
                arg_10 = arg_2.pop(arg_8)
                if isinstance(arg_12, orb.Collector) and type(arg_10) not in (tuple, list):
                    arg_10 = [arg_10]
                arg_9[arg_8] = arg_10

    # generate the base context information
    arg_7['scope'] = {
        'request': arg_0
    }

    # include any request specific scoping or information from the request
    # first, look for default ORB context for all requests
    try:
        arg_13 = arg_0.orb_default_context

    # then, look for scope specific information for all requests
    except AttributeError:
        try:
            arg_7['scope'].update(arg_0.orb_scope)
        except AttributeError:
            pass

    # if request specific context defaults exist, then
    # merge them with the rest of the query context
    else:
        if 'scope' in arg_13:
            arg_7['scope'].update(arg_13.pop('scope'))

        # setup defaults based on the request
        for arg_14, arg_15 in arg_13.items():
            arg_7.setdefault(arg_14, arg_15)

    arg_5.update(arg_7)
    return arg_9, arg_5


def Func(arg_0, arg_1, arg_2):
        """Read a list of strings.

        The value of `section` and `option` is treated as a comma- and newline-
        separated list of strings.  Each value is stripped of whitespace.

        Returns the list of strings.

        """
        arg_3 = arg_0.get(arg_1, arg_2)
        arg_4 = []
        for arg_5 in arg_3.split('\n'):
            for arg_6 in arg_5.split(','):
                arg_6 = arg_6.strip()
                if arg_6:
                    arg_4.append(arg_6)
        return arg_4


def Func(arg_0, arg_1, arg_2):
        """Read a list of full-line strings.

        The value of `section` and `option` is treated as a newline-separated
        list of strings.  Each value is stripped of whitespace.

        Returns the list of strings.

        """
        arg_3 = arg_0.get(arg_1, arg_2)
        return list(filter(None, arg_3.split('\n')))


def Func(arg_0, arg_1):
        """Read configuration from a .rc file.

        `filename` is a file name to read.

        """
        arg_0.attempted_config_files.append(arg_1)

        arg_2 = HandyConfigParser()
        arg_3 = arg_2.read(arg_1)
        if arg_3 is not None:  # return value changed in 2.4
            arg_0.config_files.extend(arg_3)

        for arg_4 in arg_0.CONFIG_FILE_OPTIONS:
            arg_0.set_attr_from_config_option(arg_2, *arg_4)

        # [paths] is special
        if arg_2.has_section('paths'):
            for arg_5 in arg_2.options('paths'):
                arg_0.paths[arg_5] = arg_2.getlist('paths', arg_5)


def Func(arg_0):
    """Expand '~'-style usernames in strings.

    This is similar to :func:`os.path.expanduser`, but it computes and returns
    extra information that will be useful if the input was being used in
    computing completions, and you wish to return the completions with the
    original '~' instead of its expanded value.

    Parameters
    ----------
    path : str
      String to be expanded.  If no ~ is present, the output is the same as the
      input.

    Returns
    -------
    newpath : str
      Result of ~ expansion in the input path.
    tilde_expand : bool
      Whether any expansion was performed or not.
    tilde_val : str
      The value that ~ was replaced with.
    """
    # Default values
    arg_1 = False
    arg_2 = ''
    arg_3 = arg_0

    if arg_0.startswith('~'):
        arg_1 = True
        arg_4 = len(arg_0)-1
        arg_3 = os.path.expanduser(arg_0)
        if arg_4:
            arg_2 = arg_3[:-arg_4]
        else:
            arg_2 = arg_3

    return arg_3, arg_1, arg_2


def Func(arg_0, arg_1):
        """Compute matches when text contains a dot.

        Assuming the text is of the form NAME.NAME....[NAME], and is
        evaluatable in self.namespace or self.global_namespace, it will be
        evaluated and its attributes (as revealed by dir()) are used as
        possible completions.  (For class instances, class members are are
        also considered.)

        WARNING: this can still invoke arbitrary C code, if an object
        with a __getattr__ hook is evaluated.

        """

        #io.rprint('Completer->Func, txt=%r' % text) # dbg
        # Another option, seems to work great. Catches things like ''.<tab>
        arg_2 = re.match(r"(\S+(\.\w+)*)\.(\w*)$", arg_1)

        if arg_2:
            arg_3, arg_4 = arg_2.group(1, 3)
        elif arg_0.greedy:
            arg_5 = re.match(r"(.+)\.(\w*)$", arg_0.line_buffer)
            if not arg_5:
                return []
            arg_3, arg_4 = arg_5.group(1,2)
        else:
            return []

        try:
            arg_6 = eval(arg_3, arg_0.namespace)
        except:
            try:
                arg_6 = eval(arg_3, arg_0.global_namespace)
            except:
                return []

        if arg_0.limit_to__all__ and hasattr(arg_6, '__all__'):
            arg_7 = get__all__entries(arg_6)
        else:
            arg_7 = dir2(arg_6)

        try:
            arg_7 = generics.complete_object(arg_6, arg_7)
        except TryNext:
            pass
        except Exception:
            # Silence errors from completion function
            #raise # dbg
            pass
        # Build match list to return
        arg_8 = len(arg_4)
        arg_9 = ["%s.%s" % (arg_3, w) for w in arg_7 if w[:arg_8] == arg_4 ]
        return arg_9


def Func(arg_0, arg_1, arg_2, arg_3):
        """update the splitter and readline delims when greedy is changed"""
        if arg_3:
            arg_0.splitter.delims = GREEDY_DELIMS
        else:
            arg_0.splitter.delims = DELIMS

        if arg_0.readline:
            arg_0.readline.set_completer_delims(arg_0.splitter.delims)


def Func(arg_0, arg_1):
        """Match filenames, expanding ~USER type strings.

        Most of the seemingly convoluted logic in this completer is an
        attempt to handle filenames with spaces in them.  And yet it's not
        quite perfect, because Python's readline doesn't expose all of the
        GNU readline details needed for this to be done correctly.

        For a filename with a space in it, the printed completions will be
        only the parts after what's already been typed (instead of the
        full completions, as is normally done).  I don't think with the
        current (as of Python 2.3) Python readline it's possible to do
        better."""

        #io.rprint('Completer->Func: <%r>' % text) # dbg

        # chars that require escaping with backslash - i.e. chars
        # that readline treats incorrectly as delimiters, but we
        # don't want to treat as delimiters in filename matching
        # when escaped with backslash
        if arg_1.startswith('!'):
            arg_1 = arg_1[1:]
            arg_2 = '!'
        else:
            arg_2 = ''

        arg_3 = arg_0.text_until_cursor
        # track strings with open quotes
        arg_4 = has_open_quotes(arg_3)

        if '(' in arg_3 or '[' in arg_3:
            arg_5 = arg_1
        else:
            try:
                # arg_split ~ shlex.split, but with unicode bugs fixed by us
                arg_5 = arg_split(arg_3)[-1]
            except ValueError:
                # typically an unmatched ", or backslash without escaped char.
                if arg_4:
                    arg_5 = arg_3.split(arg_4)[-1]
                else:
                    return []
            except IndexError:
                # tab pressed on empty line
                arg_5 = ""

        if not arg_4 and arg_5 != protect_filename(arg_5):
            # if protectables are found, do matching on the whole escaped name
            arg_6 = True
            arg_7,arg_1 = arg_1,arg_5
        else:
            arg_6 = False
            arg_1 = os.path.expanduser(arg_1)

        if arg_1 == "":
            return [arg_2 + protect_filename(arg_8) for arg_8 in arg_0.glob("*")]

        # Compute the matches from the filesystem
        arg_9 = arg_0.clean_glob(arg_1.replace('\\',''))

        if arg_6:
            # If we had protectables, we need to revert our changes to the
            # beginning of filename so that we don't double-write the part
            # of the filename we have so far
            arg_10 = len(arg_5)
            arg_11 = [arg_2 + arg_7 +
                       protect_filename(arg_8[arg_10:]) for arg_8 in arg_9]
        else:
            if arg_4:
                # if we have a string with an open quote, we don't need to
                # protect the names at all (and we _shouldn't_, as it
                # would cause bugs when the filesystem call is made).
                arg_11 = arg_9
            else:
                arg_11 = [arg_2 +
                           protect_filename(arg_8) for arg_8 in arg_9]

        #io.rprint('mm', matches)  # dbg

        # Mark directories in input list by appending '/' to their names.
        arg_11 = [x+'/' if os.path.isdir(x) else x for x in arg_11]
        return arg_11


def Func(arg_0, arg_1):
        """Match internal system aliases"""
        #print 'Completer->Func:',text,'lb',self.text_until_cursor # dbg

        # if we are not in the first 'item', alias matching
        # doesn't make sense - unless we are starting with 'sudo' command.
        arg_2 = arg_0.text_until_cursor.lstrip()
        if ' ' in arg_2 and not arg_2.startswith('sudo'):
            return []
        arg_1 = os.path.expanduser(arg_1)
        arg_3 =  arg_0.alias_table.keys()
        if arg_1 == '':
            return arg_3
        else:
            return [arg_4 for arg_4 in arg_3 if arg_4.startswith(arg_1)]


def Func(arg_0,arg_1):
        """Match attributes or global python names"""

        #io.rprint('Completer->Func, txt=%r' % text) # dbg
        if "." in arg_1:
            try:
                arg_2 = arg_0.attr_matches(arg_1)
                if arg_1.endswith('.') and arg_0.omit__names:
                    if arg_0.omit__names == 1:
                        # true if txt is _not_ a __ name, false otherwise:
                        arg_3 = (lambda txt:
                                    re.match(r'.*\.__.*?__',txt) is None)
                    else:
                        # true if txt is _not_ a _ name, false otherwise:
                        arg_3 = (lambda txt:
                                    re.match(r'.*\._.*?',txt) is None)
                    arg_2 = filter(arg_3, arg_2)
            except NameError:
                # catches <undefined attributes>.<tab>
                arg_2 = []
        else:
            arg_2 = arg_0.global_matches(arg_1)

        return arg_2


def Func(arg_0, arg_1, arg_2):
        """Return the state-th possible completion for 'text'.

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

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

          state : int
            Counter used by readline.
        """
        if arg_2==0:

            arg_0.line_buffer = arg_3 = arg_0.readline.get_line_buffer()
            arg_4 = arg_0.readline.get_endidx()

            #io.rprint("\nRLCOMPLETE: %r %r %r" %
            #          (text, line_buffer, cursor_pos) ) # dbg

            # if there is only a tab on a line with only whitespace, instead of
            # the mostly useless 'do you want to see all million completions'
            # message, just do the right thing and give the user his tab!
            # Incidentally, this enables pasting of tabbed text from an editor
            # (as long as autoindent is off).

            # It should be noted that at least pyreadline still shows file
            # completions - is there a way around it?

            # don't apply this on 'dumb' terminals, such as emacs buffers, so
            # we don't interfere with their own tab-completion mechanism.
            if not (arg_0.dumb_terminal or arg_3.strip()):
                arg_0.readline.insert_text('\t')
                sys.stdout.flush()
                return None

            # Note: debugging exceptions that may occur in completion is very
            # tricky, because readline unconditionally silences them.  So if
            # during development you suspect a bug in the completion code, turn
            # this flag on temporarily by uncommenting the second form (don't
            # flip the value in the first line, as the '# dbg' marker can be
            # automatically detected and is used elsewhere).
            arg_5 = False
            #DEBUG = True # dbg
            if arg_5:
                try:
                    arg_0.complete(arg_1, arg_3, arg_4)
                except:
                    import traceback; traceback.print_exc()
            else:
                # The normal production version is here

                # This method computes the self.matches array
                arg_0.complete(arg_1, arg_3, arg_4)

        try:
            return arg_0.matches[arg_2]
        except IndexError:
            return None


def Func(arg_0, arg_1, arg_2):
        """Check if a specific record matches tests."""
        for arg_3,arg_4 in arg_2.iteritems():
            if not arg_4(arg_1.get(arg_3, None)):
                return False
        return True


def Func(arg_0):
        """Should we silence the display hook because of ';'?"""
        # do not print output if input ends in ';'
        try:
            arg_1 = arg_0.shell.history_manager.input_hist_parsed[arg_0.prompt_count]
            if arg_1.rstrip().endswith(';'):
                return True
        except IndexError:
            # some uses of ipshellembed may fail here
            pass
        return False


def Func(arg_0, arg_1):
        """Write the format data dict to the frontend.

        This default version of this method simply writes the plain text
        representation of the object to ``io.stdout``. Subclasses should
        override this method to send the entire `format_dict` to the
        frontends.

        Parameters
        ----------
        format_dict : dict
            The format dict for the object passed to `sys.displayhook`.
        """
        # We want to print because we want to always make sure we have a
        # newline, even if all the prompt separators are ''. This is the
        # standard IPython behavior.
        arg_2 = arg_1['text/plain']
        if '\n' in arg_2:
            # So that multi-line strings line up with the left column of
            # the screen, instead of having the output prompt mess up
            # their first line.
            # We use the prompt template instead of the expanded prompt
            # because the expansion may add ANSI escapes that will interfere
            # with our ability to determine whether or not we should add
            # a newline.
            arg_3 = arg_0.shell.prompt_manager.out_template
            if arg_3 and not arg_3.endswith('\n'):
                # But avoid extraneous empty lines.
                arg_2 = '\n' + arg_2

        print >>io.stdout, arg_2


def Func(arg_0, arg_1):
        """Log the output."""
        if arg_0.shell.logger.Func:
            arg_0.shell.logger.log_write(arg_1['text/plain'], 'output')
        arg_0.shell.history_manager.output_hist_reprs[arg_0.prompt_count] = \
                                                    arg_1['text/plain']


def Func(arg_0):
    """Used exclusively as a thread which keeps the WebSocket alive."""
    while True:
      with arg_0._lock:
        if arg_0.connected():
          arg_0._ws.ping()
        else:
          arg_0.disconnect()
          arg_0._thread = None
          return
      sleep(30)


def Func(arg_0):
    """Connects and subscribes to the WebSocket Feed."""
    if not arg_0.Funced():
      arg_0._ws = create_Funcion(arg_0.WS_URI)
      arg_2 = {
        'type':arg_0.WS_TYPE,
        'product_id':arg_0.WS_PRODUCT_ID
      }
      arg_0._ws.send(dumps(arg_2))

      # There will be only one keep alive thread per client instance
      with arg_0._lock:
        if not arg_0._thread:
          arg_3 = Thread(target=arg_0._keep_alive_thread, args=[])
          arg_3.start()


def Func(arg_0):
        '''raise `InvalidOperationException` if is freezed.'''
        if arg_0.is_freezed:
            arg_1 = type(arg_0).__name__
            raise InvalidOperationException('obj {name} is freezed.'.format(arg_1=arg_1))


def Func(arg_0):
    """Convert a MySQL TIMESTAMP to a Timestamp object."""
    # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
    if arg_0[4] == '-': return DateTime_or_None(arg_0)
    arg_0 = arg_0 + "0"*(14-len(arg_0)) # padding
    arg_1 = map(int, filter(None, (arg_0[:4],arg_0[4:6],arg_0[6:8],
                                   arg_0[8:10],arg_0[10:12],arg_0[12:14])))
    try:
        return Timestamp(*arg_1)
    except (SystemExit, KeyboardInterrupt):
        raise
    except:
        return None


def Func(arg_0, arg_1, arg_2, arg_3):
        """schedule call to eventloop from IOLoop"""
        arg_4 = ioloop.IOLoop.instance()
        arg_4.add_timeout(time.time()+0.1, arg_0.enter_eventloop)


def Func(arg_0, arg_1):
        """dispatch control requests"""
        arg_2,arg_1 = arg_0.session.feed_identities(arg_1, copy=False)
        try:
            arg_1 = arg_0.session.unserialize(arg_1, content=True, copy=False)
        except:
            arg_0.log.error("Invalid Control Message", exc_info=True)
            return

        arg_0.log.debug("Control received: %s", arg_1)

        arg_3 = arg_1['header']
        arg_4 = arg_3['msg_id']
        arg_5 = arg_3['msg_type']

        arg_6 = arg_0.control_handlers.get(arg_5, None)
        if arg_6 is None:
            arg_0.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", arg_5)
        else:
            try:
                arg_6(arg_0.control_stream, arg_2, arg_1)
            except Exception:
                arg_0.log.error("Exception in control handler:", exc_info=True)


def Func(arg_0, arg_1, arg_2):
        """dispatch shell requests"""
        # flush control requests first
        if arg_0.control_stream:
            arg_0.control_stream.flush()

        arg_3,arg_2 = arg_0.session.feed_identities(arg_2, copy=False)
        try:
            arg_2 = arg_0.session.unserialize(arg_2, content=True, copy=False)
        except:
            arg_0.log.error("Invalid Message", exc_info=True)
            return

        arg_4 = arg_2['header']
        arg_5 = arg_4['msg_id']
        arg_6 = arg_2['header']['msg_type']

        # Print some info about this message and leave a '--->' marker, so it's
        # easier to trace visually the message chain when debugging.  Each
        # handler prints its message at the end.
        arg_0.log.debug('\n*** MESSAGE TYPE:%s***', arg_6)
        arg_0.log.debug('   Content: %s\n   --->\n   ', arg_2['content'])

        if arg_5 in arg_0.aborted:
            arg_0.aborted.remove(arg_5)
            # is it safe to assume a msg_id will not be resubmitted?
            arg_7 = arg_6.split('_')[0] + '_reply'
            arg_8 = {'status' : 'aborted'}
            arg_9 = {'engine' : arg_0.ident}
            arg_9.update(arg_8)
            arg_10 = arg_0.session.send(arg_1, arg_7, subheader=arg_9,
                        content=arg_8, parent=arg_2, ident=arg_3)
            return

        arg_11 = arg_0.shell_handlers.get(arg_6, None)
        if arg_11 is None:
            arg_0.log.error("UNKNOWN MESSAGE TYPE: %r", arg_6)
        else:
            # ensure default_int_handler during handler call
            arg_12 = signal(SIGINT, default_int_handler)
            try:
                arg_11(arg_1, arg_3, arg_2)
            except Exception:
                arg_0.log.error("Exception in message handler:", exc_info=True)
            finally:
                signal(SIGINT, arg_12)


def Func(arg_0):
        """register dispatchers for streams"""
        arg_0.shell.exit_now = False
        if arg_0.control_stream:
            arg_0.control_stream.on_recv(arg_0.dispatch_control, copy=False)

        def make_dispatcher(arg_3):
            def dispatcher(arg_4):
                return arg_0.dispatch_shell(arg_3, arg_4)
            return dispatcher

        for arg_5 in arg_0.shell_streams:
            arg_5.on_recv(make_dispatcher(arg_5), copy=False)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Publish the code request on the pyin stream."""

        arg_0.session.send(arg_0.iopub_socket, u'pyin',
                            {u'code':arg_1, u'execution_count': arg_3},
                            arg_2=arg_2, ident=arg_0._topic('pyin')
        )


def Func(arg_0, arg_1, arg_2, arg_3):
        """abort a specifig msg by id"""
        arg_4 = arg_3['content'].get('msg_ids', None)
        if isinstance(arg_4, basestring):
            arg_4 = [arg_4]
        if not arg_4:
            arg_0.abort_queues()
        for arg_5 in arg_4:
            arg_0.aborted.add(str(arg_5))

        arg_6 = dict(status='ok')
        arg_7 = arg_0.session.send(arg_1, 'abort_reply', arg_6=arg_6,
                arg_3=arg_3, arg_2=arg_2)
        arg_0.log.debug("%s", arg_7)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Clear our namespace."""
        arg_0.shell.reset(False)
        arg_4 = arg_0.session.send(arg_1, 'clear_reply', ident=arg_2, arg_3=arg_3,
                content = dict(status='ok'))


def Func(arg_0, arg_1):
        """prefixed topic for IOPub messages"""
        if arg_0.int_id >= 0:
            arg_2 = "engine.%i" % arg_0.int_id
        else:
            arg_2 = "kernel.%s" % arg_0.ident

        return py3compat.cast_bytes("%s.%s" % (arg_2, arg_1))


def Func(arg_0):
    """
    Marks a view function as being exempt from the cached httpbl view protection.
    """
    # We could just do view_func.cached_httpbl_exempt = True, but decorators
    # are nicer if they don't have side-effects, so we return a new
    # function.
    def arg_3(*arg_1, **arg_2):
        return arg_0(*arg_1, **arg_2)
    arg_3.cached_httpbl_exempt = True
    return wraps(arg_0, assigned=available_attrs(arg_0))(arg_3)


def Func(arg_0):
    """Return absolute, normalized path to directory, if it exists; None
    otherwise.
    """
    if not os.path.isabs(arg_0):
        arg_0 = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
                                                             arg_0)))
    if arg_0 is None or not os.path.isdir(arg_0):
        return None
    return arg_0


def Func(arg_0):
    """A name is file-like if it is a path that exists, or it has a
    directory part, or it ends in .py, or it isn't a legal python
    identifier.
    """
    return (os.path.exists(arg_0)
            or os.path.dirname(arg_0)
            or arg_0.endswith('.py')
            or not ident_re.match(os.path.splitext(arg_0)[0]))


def Func(arg_0):
    """Is obj a class? Inspect's Func is too liberal and returns True
    for objects that can't be subclasses of anything.
    """
    arg_1 = type(arg_0)
    return arg_1 in class_types or issubclass(arg_1, type)


def Func(arg_0):
    """
    Is this path a package directory?

    >>> Func('nose')
    True
    >>> Func('unit_tests')
    False
    >>> Func('nose/plugins')
    True
    >>> Func('nose/loader.py')
    False
    """
    if os.path.isdir(arg_0):
        # at least the end of the path must be a legal python identifier
        # and __init__.py[co] must exist
        arg_1 = os.path.basename(arg_0)
        if ident_re.match(arg_1):
            for arg_2 in ('__init__.py', '__init__.pyc', '__init__.pyo'):
                if os.path.isfile(os.path.join(arg_0, arg_2)):
                    return True
            if sys.platform.startswith('java') and \
                    os.path.isfile(os.path.join(arg_0, '__init__$py.class')):
                return True
    return False


def Func(arg_0):
    """Draw a 70-char-wide divider, with label in the middle.

    >>> Func('hello there')
    '---------------------------- hello there -----------------------------'
    """
    arg_1 = len(arg_0) + 2
    arg_2 = (70 - arg_1) // 2
    arg_3 = '%s %s %s' % ('-' * arg_2, arg_0, '-' * arg_2)
    arg_4 = 70 - len(arg_3)
    if arg_4 > 0:
        arg_3 = arg_3 + ('-' * arg_4)
    return arg_3


def Func(arg_0):
    """Sort key function factory that puts items that match a
    regular expression last.

    >>> from nose.config import Config
    >>> from nose.pyversion import sort_list
    >>> c = Config()
    >>> regex = c.testMatch
    >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py']
    >>> sort_list(entries, Func(regex))
    >>> entries
    ['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test']
    """
    def k(arg_1):
        if arg_0.search(arg_1):
            return (1, arg_1)
        return (0, arg_1)
    return k


def Func(arg_0, arg_1):
    """
    Make a function imported from module A appear as if it is located
    in module B.

    >>> from pprint import pprint
    >>> pprint.__module__
    'pprint'
    >>> pp = Func(pprint, __name__)
    >>> pp.__module__
    'nose.util'

    The original function is not modified.

    >>> pprint.__module__
    'pprint'

    Calling the transplanted function calls the original.

    >>> pp([1, 2])
    [1, 2]
    >>> pprint([1,2])
    [1, 2]

    """
    from nose.tools import make_decorator
    def arg_4(*arg_2, **arg_3):
        return arg_0(*arg_2, **arg_3)

    arg_4 = make_decorator(arg_0)(arg_4)
    arg_4.__module__ = arg_1
    return arg_4


def Func():
    """Return system CPU times as a namedtuple."""
    arg_0, arg_1, arg_2, arg_3 = _psutil_osx.Func()
    return _cputimes_ntuple(arg_0, arg_1, arg_2, arg_3)


def Func(arg_0, arg_1='inet'):
        """Return etwork connections opened by a process as a list of
        namedtuples.
        """
        if arg_1 not in conn_tmap:
            raise ValueError("invalid %r kind argument; choose between %s"
                             % (arg_1, ', '.join([repr(arg_2) for arg_2 in conn_tmap])))
        arg_3, arg_4 = conn_tmap[arg_1]
        arg_5 = _psutil_osx.get_process_connections(arg_0.pid, arg_3, arg_4)
        return [nt_connection(*arg_6) for arg_6 in arg_5]


def Func(arg_0, arg_1, arg_2=True):
    """
    Check if a user is in a certaing group.
    By default, the check is skipped for superusers.
    """

    if arg_0.is_superuser and arg_2:
        return True

    return arg_0.groups.filter(name=arg_1).exists()


def Func(arg_0):
    """
    Load a class by a fully qualified class_path,
    eg. myapp.models.ModelName
    """

    arg_1, arg_2 = arg_0.rsplit('.', 1)
    arg_3 = __import__(arg_1, fromlist=[arg_2])
    return getattr(arg_3, arg_2)


def Func(arg_0, arg_1=None, arg_2=None):
        '''
        Hook point for overriding how the CounterPool gets its connection to
        AWS.
        '''
        return boto.connect_dynamodb(
            aws_access_key_id=arg_1,
            aws_secret_access_key=arg_2,
        )


def Func(arg_0):
        '''
        Hook point for overriding how the CounterPool determines the schema
        to be used when creating a missing table.
        '''
        if not arg_0.schema:
            raise NotImplementedError(
                'You must provide a schema value or override the Func method'
            )

        return arg_0.conn.create_schema(**arg_0.schema)


def Func(arg_0):
        '''
        Hook point for overriding how the CounterPool creates a new table
        in DynamooDB
        '''
        arg_1 = arg_0.conn.Func(
            name=arg_0.get_table_name(),
            schema=arg_0.get_schema(),
            read_units=arg_0.get_read_units(),
            write_units=arg_0.get_write_units(),
        )

        if arg_1.status != 'ACTIVE':
            arg_1.refresh(wait_for_active=True, retry_seconds=1)

        return arg_1


def Func(arg_0):
        '''
        Hook point for overriding how the CounterPool transforms table_name
        into a boto DynamoDB Table object.
        '''
        if hasattr(arg_0, '_table'):
            arg_1 = arg_0._table
        else:
            try:
                arg_1 = arg_0.conn.Func(arg_0.Func_name())
            except boto.exception.DynamoDBResponseError:
                if arg_0.auto_create_table:
                    arg_1 = arg_0.create_table()
                else:
                    raise

            arg_0._table = arg_1

        return arg_1


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        '''
        Hook point for overriding how the CouterPool creates a DynamoDB item
        for a given counter when an existing item can't be found.
        '''
        arg_4 = arg_0.get_table()
        arg_5 = datetime.utcnow().replace(microsecond=0).isoformat()
        arg_6 = {
            'created_on': arg_5,
            'modified_on': arg_5,
            'count': arg_2,
        }

        if arg_3:
            arg_6.update(arg_3)

        arg_7 = arg_4.new_item(
            arg_1=arg_1,
            arg_6=arg_6,
        )

        return arg_7


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        '''
        Hook point for overriding how the CouterPool fetches a DynamoDB item
        for a given counter.
        '''
        arg_4 = arg_0.get_table()

        try:
            arg_5 = arg_4.Func(arg_1=arg_1)
        except DynamoDBKeyNotFoundError:
            arg_5 = None

        if arg_5 is None:
            arg_5 = arg_0.create_item(
                arg_1=arg_1,
                arg_2=arg_2,
                arg_3=arg_3,
            )

        return arg_5


def Func(arg_0=None):
    """A decorator which can be used to mark functions as Func."""
    def outer(arg_1):
        arg_2 = "psutil.%s is Func" % arg_1.__name__
        if arg_0 is not None:
            arg_2 += "; use %s instead" % arg_0
        if arg_1.__doc__ is None:
            arg_1.__doc__ = arg_2

        @wraps(arg_1)
        def inner(*arg_4, **arg_5):
            warnings.warn(arg_2, category=DeprecationWarning, stacklevel=2)
            return arg_1(*arg_4, **arg_5)

        return inner
    return outer


def Func(arg_0):
        """
        Login into Google Docs with user authentication info.
        """
        try:
            arg_0.gd_client = gdata.docs.client.DocsClient()
            arg_0.gd_client.ClientLogin(arg_0.email, arg_0.password, arg_0.source)
        except RequestError as e:
            raise PODocsError(e)


def Func(arg_0):
        """
        Parse GDocs key from Spreadsheet url.
        """
        try:
            arg_1 = urlparse.parse_qs(urlparse.urlparse(arg_0.url).query)
            arg_0.key = arg_1['key'][0]
        except KeyError as e:
            raise PODocsError(e)


def Func(arg_0):
        """
        Make sure temp directory exists and create one if it does not.
        """
        try:
            if not os.path.exists(arg_0.temp_path):
                os.mkdir(arg_0.temp_path)
        except OSError as e:
            raise PODocsError(e)


def Func(arg_0):
        """
        Download csv files from GDocs and convert them into po files structure.
        """
        arg_1 = os.path.realpath(
            os.path.join(arg_0.temp_path, GDOCS_TRANS_CSV))
        arg_2 = os.path.realpath(
            os.path.join(arg_0.temp_path, GDOCS_META_CSV))

        arg_0._Func_csv_from_gdocs(arg_1, arg_2)

        try:
            csv_to_po(arg_1, arg_2,
                      arg_0.locale_root, arg_0.po_files_path, header=arg_0.header)
        except IOError as e:
            raise PODocsError(e)

        arg_0._clear_temp()


def Func(arg_0):
        """
        Clear GDoc Spreadsheet by sending empty csv file.
        """
        arg_1 = os.path.join(arg_0.temp_path, 'empty.csv')
        try:
            arg_2 = open(arg_1, 'w')
            arg_2.write(',')
            arg_2.close()
        except IOError as e:
            raise PODocsError(e)

        arg_0._upload_file_to_gdoc(arg_1, content_type='text/csv')

        os.remove(arg_1)


def Func(arg_0, arg_1=None):
        """start a new qtconsole connected to our kernel"""
        return connect_qtconsole(arg_0.ipkernel.connection_file, profile=arg_0.ipkernel.profile)


def Func(arg_0, arg_1, arg_2=False, arg_3=10):
    '''
    Check whether the HTML page contains the content or not and return boolean
    '''
    try:
        arg_4 = urllib2.urlopen(arg_0, arg_3=arg_3)
    except Exception, _:
        False
    else:
        arg_5 = arg_4.read()
        if (not arg_2 and arg_5.lower().find(arg_1.lower()) >= 0) or (arg_2 and arg_5.find(arg_1) >= 0):
            return True
        else:
            return False


def Func(arg_0, arg_1=10):
    '''
    Visit the URL and return the HTTP response code in 'int'
    '''
    try:
        arg_2 = urllib2.urlopen(arg_0, arg_1=arg_1)
    except HTTPError, e:
        return e.getcode()
    except Exception, _:
        fail("Couldn't reach the URL '%s'" % arg_0)
    else:
        return arg_2.getcode()


def Func(arg_0, arg_1):
    '''
    Compare the content type header of url param with content_type param and returns boolean
    @param url -> string e.g. http://127.0.0.1/index
    @param content_type -> string e.g. text/html
    '''
    try:
        arg_2 = urllib2.urlopen(arg_0)
    except:
        return False

    return arg_2.headers.type == arg_1


def Func(arg_0, arg_1):
    '''
    Compare the response code of url param with code param and returns boolean
    @param url -> string e.g. http://127.0.0.1/index
    @param content_type -> int e.g. 404, 500, 400 ..etc
    '''
    try:
        arg_2 = urllib2.urlopen(arg_0)

    except HTTPError as e:
        return e.code == arg_1

    except:
        return False

    return arg_2.code == arg_1


def Func(arg_0, **arg_1):
    """Use an event to build a many-to-one relationship on a class.

    This makes use of the :meth:`.References._reference_table` method
    to generate a full foreign key relationship to the remote table.

    """
    @declared_attr
    def m2o(arg_2):
        arg_2._references((arg_2.__name__, arg_0))
        return relationship(arg_0, **arg_1)
    return m2o


def Func(arg_0, arg_1=True, arg_2=True, arg_3=True):
        """Clear the output of the cell receiving output."""
        if arg_1:
            print('\033[2K\r', file=io.stdout, end='')
            io.stdout.flush()
        if arg_2:
            print('\033[2K\r', file=io.stderr, end='')
            io.stderr.flush()


def Func(arg_0, arg_1):
        """
        Djeffify data between tags
        """
        if arg_1.strip():
            arg_1 = djeffify_string(arg_1)
        arg_0.djhtml += arg_1


def Func(arg_0, arg_1):
        """Create a foreign key reference from the local class to the given remote
        table.

        Adds column references to the declarative class and adds a
        ForeignKeyConstraint.

        """
        # create pairs of (Foreign key column, primary key column)
        arg_2 = [(sa.Column(), arg_4) for arg_4 in arg_1.primary_key]

        # set "tablename_colname = Foreign key Column" on the local class
        for arg_3, arg_4 in arg_2:
            setattr(arg_0, "%s_%s" % (arg_1.name, arg_4.name), arg_3)

        # add a ForeignKeyConstraint([local columns], [remote columns])
        arg_0.__table__.append_constraint(sa.ForeignKeyConstraint(*zip(*arg_2)))


def Func(arg_0):
    """Find absolute path to executable cmd in a cross platform manner.

    This function tries to determine the full path to a command line program
    using `which` on Unix/Linux/OS X and `win32api` on Windows.  Most of the
    time it will use the version that is first on the users `PATH`.  If
    cmd is `python` return `sys.executable`.

    Warning, don't use this to find IPython command line programs as there
    is a risk you will find the wrong one.  Instead find those using the
    following code and looking for the application itself::

        from IPython.utils.path import get_ipython_module_path
        from IPython.utils.process import pycmd2argv
        argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp'))

    Parameters
    ----------
    cmd : str
        The command line program to look for.
    """
    if arg_0 == 'python':
        return os.path.abspath(sys.executable)
    try:
        arg_1 = _Func(arg_0).rstrip()
    except OSError:
        raise FindCmdError('command could not be found: %s' % arg_0)
    # which returns empty if not found
    if arg_1 == '':
        raise FindCmdError('command could not be found: %s' % arg_0)
    return os.path.abspath(arg_1)


def Func(arg_0):
    """
    Path join helper method
    Join paths if list passed

    :type path: str|unicode|list
    :rtype: str|unicode
    """
    if type(arg_0) == list:
        return os.path.join(*arg_0)
    return arg_0


def Func(arg_0, arg_1="utf-8"):
    """
    Read helper method

    :type file_path: str|unicode
    :type encoding: str|unicode
    :rtype: str|unicode
    """
    with codecs.open(arg_0, "r", arg_1) as f:
        return f.read()


def Func(arg_0):
        """
        Helper method for absolute and relative paths resolution
        Split passed path and return each directory parts

        example: "/usr/share/dir"
        return: ["usr", "share", "dir"]

        @type path: one of (unicode, str)
        @rtype: list
        """
        arg_1 = []
        #todo: check loops
        while arg_0 != "/":
            arg_2 = os.path.split(arg_0)
            if arg_2[1] == arg_0:
                arg_1.insert(0, arg_2[1])
                break
            elif arg_2[0] == arg_0:
                arg_1.insert(0, arg_2[0])
                break
            else:
                arg_0 = arg_2[0]
                arg_1.insert(0, arg_2[1])
        return arg_1


def Func(arg_0):
        """A base for a flat filename to correspond to this code unit.

        Useful for writing files about the code where you want all the files in
        the same directory, but need to differentiate same-named files from
        different directories.

        For example, the file a/b/c.py might return 'a_b_c'

        """
        if arg_0.modname:
            return arg_0.modname.replace('.', '_')
        else:
            arg_1 = os.path.splitdrive(arg_0.name)[1]
            return arg_1.replace('\\', '_').replace('/', '_').replace('.', '_')


def Func(arg_0):
        """Does it seem like this file should contain Python?

        This is used to decide if a file reported as part of the exection of
        a program was really likely to have contained Python in the first
        place.

        """
        # Get the file extension.
        arg_1, arg_2 = os.path.splitext(arg_0.filename)

        # Anything named *.py* should be Python.
        if arg_2.startswith('.py'):
            return True
        # A file with no extension should be Python.
        if not arg_2:
            return True
        # Everything else is probably not Python.
        return False


def Func(arg_0):
    """timedelta.total_seconds was added in 2.7"""
    try:
        # Python >= 2.7
        return arg_0.total_seconds()
    except AttributeError:
        # Python 2.6
        return 1e-6 * (arg_0.microseconds + (arg_0.seconds + arg_0.days * 24 * 3600) * 10**6)


def Func(arg_0, arg_1=-1):
        """Return the result when it arrives.

        If `timeout` is not ``None`` and the result does not arrive within
        `timeout` seconds then ``TimeoutError`` is raised. If the
        remote call raised an exception then that exception will be reraised
        by Func() inside a `RemoteError`.
        """
        if not arg_0.ready():
            arg_0.wait(arg_1)

        if arg_0._ready:
            if arg_0._success:
                return arg_0._result
            else:
                raise arg_0._exception
        else:
            raise error.TimeoutError("Result not ready.")


def Func(arg_0, arg_1=-1):
        """Wait until the result is available or until `timeout` seconds pass.

        This method always returns None.
        """
        if arg_0._ready:
            return
        arg_0._ready = arg_0._client.Func(arg_0.msg_ids, arg_1)
        if arg_0._ready:
            try:
                arg_3 = map(arg_0._client.results.get, arg_0.msg_ids)
                arg_0._result = arg_3
                if arg_0._single_result:
                    arg_5 = arg_3[0]
                    if isinstance(arg_5, Exception):
                        raise arg_5
                else:
                    arg_3 = error.collect_exceptions(arg_3, arg_0._fname)
                arg_0._result = arg_0._reconstruct_result(arg_3)
            except Exception, e:
                arg_0._exception = e
                arg_0._success = False
            else:
                arg_0._success = True
            finally:
                arg_0._metadata = map(arg_0._client.metadata.get, arg_0.msg_ids)
                arg_0._Func_for_outputs(10)


def Func(arg_0, arg_1=-1):
        """Get the results as a dict, keyed by engine_id.

        timeout behavior is described in `get()`.
        """

        arg_2 = arg_0.get(arg_1)
        arg_3 = [ md['engine_id'] for md in arg_0._metadata ]
        arg_4 = sorted(arg_3, key=lambda k: arg_3.count(k))
        arg_5 = arg_4.count(arg_4[-1])
        if arg_5 > 1:
            raise ValueError("Cannot build dict, %i jobs ran on engine #%i"%(
                    arg_5, arg_4[-1]))

        return dict(zip(arg_3,arg_2))


def Func(arg_0):
        """Func time since initial submission"""
        if arg_0.ready():
            return arg_0.wall_time

        arg_1 = arg_4 = datetime.now()
        for arg_2 in arg_0.msg_ids:
            if arg_2 in arg_0._client.metadata:
                arg_3 = arg_0._client.metadata[arg_2]['submitted']
                if arg_3 and arg_3 < arg_4:
                    arg_4 = arg_3
        return _total_seconds(arg_1-arg_4)


def Func(arg_0, arg_1=1., arg_2=None):
        """interactive wait, printing progress at regular intervals"""
        arg_3 = len(arg_0)
        arg_4 = time.time()
        while not arg_0.ready() and (arg_2 is None or time.time() - arg_4 <= arg_2):
            arg_0.wait(arg_1)
            clear_output()
            print("%4i/%i tasks finished after %4i s" % (arg_0.progress, arg_3, arg_0.elapsed), end="")
            sys.stdout.flush()
        print()
        print("done")


def Func(arg_0, arg_1, arg_2):
        """republish individual displaypub content dicts"""
        try:
            arg_3 = get_ipython()
        except NameError:
            # displaypub is meaningless outside IPython
            return
        arg_4 = arg_1['metadata'] or {}
        arg_4['engine'] = arg_2
        arg_3.display_pub.publish(arg_1['source'], arg_1['data'], arg_4)


def Func(arg_0, arg_1=-1):
        """wait for the 'status=idle' message that indicates we have all outputs
        """
        if not arg_0._success:
            # don't wait on errors
            return
        arg_2 = time.time()
        while not all(arg_3['outputs_ready'] for arg_3 in arg_0._metadata):
            time.sleep(0.01)
            arg_0._client._flush_iopub(arg_0._client._iopub_socket)
            if arg_1 >= 0 and time.time() > arg_2 + arg_1:
                break


def Func(arg_0, arg_1=-1):
        """Func for result to complete."""
        arg_2 = time.time()
        if arg_0._ready:
            return
        arg_3 = filter(lambda msg_id: msg_id in arg_0._client.outstanding, arg_0.msg_ids)
        arg_4 = arg_0._client.Func(arg_3, arg_1)
        if arg_4:
            arg_5 = filter(lambda msg_id: msg_id not in arg_0._client.results, arg_0.msg_ids)
            if not arg_5:
                arg_0._ready = True
            else:
                arg_7 = arg_0._client.result_status(arg_5, status_only=False)
                arg_8 = arg_7['pending']
                while arg_8 and (arg_1 < 0 or time.time() < arg_2+arg_1):
                    arg_7 = arg_0._client.result_status(arg_5, status_only=False)
                    arg_8 = arg_7['pending']
                    if arg_8:
                        time.sleep(0.1)
                if not arg_8:
                    arg_0._ready = True
        if arg_0._ready:
            try:
                arg_9 = map(arg_0._client.results.get, arg_0.msg_ids)
                arg_0._result = arg_9
                if arg_0._single_result:
                    arg_11 = arg_9[0]
                    if isinstance(arg_11, Exception):
                        raise arg_11
                else:
                    arg_9 = error.collect_exceptions(arg_9, arg_0._fname)
                arg_0._result = arg_0._reconstruct_result(arg_9)
            except Exception, e:
                arg_0._exception = e
                arg_0._success = False
            else:
                arg_0._success = True
            finally:
                arg_0._metadata = map(arg_0._client.metadata.get, arg_0.msg_ids)


def Func(arg_0, *arg_1):
    """Creates fully qualified endpoint URIs.

    :param parts: the string parts that form the request URI

    """
    return urljoin(arg_0.API_URI, '/'.join(map(quote, arg_1)))


def Func(arg_0, arg_1):
    """Makes sure we have proper ISO 8601 time.

    :param time: either already ISO 8601 a string or datetime.datetime
    :returns: ISO 8601 time
    :rtype: str

    """
    if isinstance(arg_1, str):
      return arg_1
    elif isinstance(arg_1, datetime):
      return arg_1.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    else:
      return None


def Func(arg_0, arg_1):
    """Returns the given response or raises an APIError for non-2xx responses.

    :param requests.Response response: HTTP response
    :returns: requested data
    :rtype: requests.Response
    :raises APIError: for non-2xx responses

    """
    if not str(arg_1.status_code).startswith('2'):
      raise get_api_error(arg_1)
    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """ Colors text with code and given format """
        arg_5 = None
        if arg_1[:3] == arg_0.bg.PREFIX:
            arg_5 = arg_0.bg.COLORS.get(arg_1, None)
        if not arg_5:
            arg_5 = arg_0.fg.COLORS.get(arg_1, None)

        if not arg_5:
            raise Exception('Color code not found')

        if arg_3 and arg_3 not in arg_0.formats:
            raise Exception('Color format not found')

        arg_6 = "0;"
        if arg_3 == 'bold':
            arg_6 = "1;"
        elif arg_3 == 'underline':
            arg_6 = "4;"

        # Manage the format
        arg_7 = arg_5.split('[')
        arg_5 = '{0}[{1}{2}'.format(arg_7[0], arg_6, arg_7[1])

        if arg_0.has_colors and arg_0.colors_enabled:
            # Set brightness
            arg_8 = ''
            if arg_4:
                arg_8 = arg_0.st.COLORS.get(arg_4, '')
            return "{0}{1}{2}{3}".format(arg_8, arg_5, arg_2, arg_0.st.COLORS['reset_all'])
        else:
            return arg_2


def Func(arg_0, arg_1):
    """Registers the given message type in the local database.

    Args:
      message: a message.Message, to be registered.

    Returns:
      The provided message.
    """

    arg_2 = arg_1.DESCRIPTOR
    arg_0._symbols[arg_2.full_name] = arg_1
    if arg_2.file.name not in arg_0._symbols_by_file:
      arg_0._symbols_by_file[arg_2.file.name] = {}
    arg_0._symbols_by_file[arg_2.file.name][arg_2.full_name] = arg_1
    arg_0.pool.AddDescriptor(arg_2)
    return arg_1


def Func(arg_0):
    """Return the absolute normalized form of `filename`."""
    arg_1 = os.path.expandvars(os.path.expanduser(arg_0))
    arg_1 = os.path.abspath(os.path.realpath(arg_1))
    arg_1 = actual_path(arg_1)
    return arg_1


def Func(arg_0):
    """Prepare the file patterns for use in a `FnmatchMatcher`.

    If a pattern starts with a wildcard, it is used as a pattern
    as-is.  If it does not start with a wildcard, then it is made
    absolute with the current directory.

    If `patterns` is None, an empty list is returned.

    """
    arg_1 = []
    for arg_2 in arg_0 or []:
        if arg_2.startswith("*") or arg_2.startswith("?"):
            arg_1.append(arg_2)
        else:
            arg_1.append(abs_file(arg_2))
    return arg_1


def Func(arg_0):
    """Find the path Funcarator used in this string, or os.Func if none."""
    arg_1 = re.search(r"[\\/]", arg_0)
    if arg_1:
        arg_2 = arg_1.group(0)
    else:
        arg_2 = os.Func
    return arg_2


def Func(arg_0, arg_1):
        """Return the relative form of `filename`.

        The filename will be relative to the current directory when the
        `FileLocator` was constructed.

        """
        arg_2 = os.path.normcase(arg_1)
        if arg_2.startswith(arg_0.relative_dir):
            arg_1 = arg_1[len(arg_0.relative_dir):]
        return arg_1


def Func(arg_0, arg_1):
        """Get data from `filename` if it is a zip file path.

        Returns the string data read from the zip file, or None if no zip file
        could be found or `filename` isn't in it.  The data returned will be
        an empty string if the file is empty.

        """
        import zipimport
        arg_2 = ['.zip'+os.sep, '.egg'+os.sep]
        for arg_3 in arg_2:
            if arg_3 in arg_1:
                arg_4 = arg_1.split(arg_3)
                try:
                    arg_5 = zipimport.zipimporter(arg_4[0]+arg_3[:-1])
                except zipimport.ZipImportError:
                    continue
                try:
                    arg_6 = arg_5.get_data(arg_4[1])
                except IOError:
                    continue
                return to_string(arg_6)
        return None


def Func(arg_0, arg_1):
        """Does `fpath` Func one of our filename patterns?"""
        for arg_2 in arg_0.pats:
            if fnFunc.fnFunc(arg_1, arg_2):
                return True
        return False


def Func(arg_0, arg_1):
        """Map `path` through the aliases.

        `path` is checked against all of the patterns.  The first pattern to
        match is used to replace the root of the path with the result root.
        Only one pattern is ever used.  If no patterns match, `path` is
        returned unchanged.

        The separator style in the result is made to match that of the result
        in the alias.

        """
        for arg_2, arg_3, arg_4, arg_5 in arg_0.aliases:
            arg_6 = arg_2.match(arg_1)
            if arg_6:
                arg_7 = arg_1.replace(arg_6.group(0), arg_3)
                if arg_4 != arg_5:
                    arg_7 = arg_7.replace(arg_4, arg_5)
                if arg_0.locator:
                    arg_7 = arg_0.locator.canonical_filename(arg_7)
                return arg_7
        return arg_1


def Func(arg_0):
    """Start a kernel with wx event loop support."""

    import wx
    from IPython.lib.guisupport import start_event_Func

    arg_1 = arg_0.do_one_iteration
     # Wx uses milliseconds
    arg_2 = int(1000*arg_0._poll_interval)

    # We have to put the wx.Timer in a wx.Frame for it to fire properly.
    # We make the Frame hidden when we create it in the main app below.
    class TimerFrame(wx.Frame):
        def __init__(arg_3, arg_4):
            wx.Frame.__init__(arg_3, None, -1)
            arg_3.timer = wx.Timer(arg_3)
            # Units for the timer are in milliseconds
            arg_3.timer.Start(arg_2)
            arg_3.Bind(wx.EVT_TIMER, arg_3.on_timer)
            arg_3.func = arg_4

        def on_timer(arg_3, arg_6):
            arg_3.func()

    # We need a custom wx.App to create our Frame subclass that has the
    # wx.Timer to drive the ZMQ event loop.
    class IPWxApp(wx.App):
        def OnInit(arg_3):
            arg_3.frame = TimerFrame(arg_1)
            arg_3.frame.Show(False)
            return True

    # The redirect=False here makes sure that wx doesn't replace
    # sys.stdout/stderr with its own classes.
    arg_0.app = IPWxApp(redirect=False)

    # The import of wx on Linux sets the handler for signal.SIGINT
    # to 0.  This is a bug in wx or gtk.  We fix by just setting it
    # back to the Python default.
    import signal
    if not callable(signal.getsignal(signal.SIGINT)):
        signal.signal(signal.SIGINT, signal.default_int_handler)

    start_event_Func(arg_0.app)


def Func(arg_0):
    """Start a kernel with the Tk event loop."""

    import Tkinter
    arg_1 = arg_0.do_one_iteration
    # Tk uses milliseconds
    arg_2 = int(1000*arg_0._poll_interval)
    # For Tkinter, we create a Tk object and call its withdraw method.
    class Timer(object):
        def __init__(arg_3, arg_4):
            arg_3.app = Tkinter.Tk()
            arg_3.app.withdraw()
            arg_3.func = arg_4

        def on_timer(arg_3):
            arg_3.func()
            arg_3.app.after(arg_2, arg_3.on_timer)

        def start(arg_3):
            arg_3.on_timer()  # Call it once to get things going.
            arg_3.app.mainloop()

    arg_0.timer = Timer(arg_1)
    arg_0.timer.start()


def Func(arg_0):
    """Start the kernel, coordinating with the Cocoa CFRunLoop event loop
    via the matplotlib MacOSX backend.
    """
    import matplotlib
    if matplotlib.__version__ < '1.1.0':
        arg_0.log.warn(
        "MacOSX backend in matplotlib %s doesn't have a Timer, "
        "falling back on Tk for CFRunLoop integration.  Note that "
        "even this won't work if Tk is linked against X11 instead of "
        "Cocoa (e.g. EPD).  To use the MacOSX backend in the kernel, "
        "you must use matplotlib >= 1.1.0, or a native libtk."
        )
        return loop_tk(arg_0)

    from matplotlib.backends.backend_macosx import TimerMac, show

    # scale interval for sec->ms
    arg_1 = int(1000*arg_0._poll_interval)

    arg_2 = arg_6.excepthook
    def handle_int(arg_3, arg_4, arg_5):
        """don't let KeyboardInterrupts look like crashes"""
        if arg_3 is KeyboardInterrupt:
            io.raw_print("KeyboardInterrupt caught in CFRunLoop")
        else:
            arg_2(arg_3, arg_4, arg_5)

    # add doi() as a Timer to the CFRunLoop
    def doi():
        # restore excepthook during IPython code
        arg_6.excepthook = arg_2
        arg_0.do_one_iteration()
        # and back:
        arg_6.excepthook = handle_int

    arg_8 = TimerMac(arg_1)
    arg_8.add_callback(doi)
    arg_8.start()

    # but still need a Poller for when there are no active windows,
    # during which time mainloop() returns immediately
    arg_9 = zmq.Poller()
    if arg_0.control_stream:
        arg_9.register(arg_0.control_stream.socket, zmq.POLLIN)
    for arg_10 in arg_0.shell_streams:
        arg_9.register(arg_10.socket, zmq.POLLIN)

    while True:
        try:
            # double nested try/except, to properly catch KeyboardInterrupt
            # due to pyzmq Issue #130
            try:
                # don't let interrupts during mainloop invoke crash_handler:
                arg_6.excepthook = handle_int
                show.mainloop()
                arg_6.excepthook = arg_2
                # use poller if mainloop returned (no windows)
                # scale by extra factor of 10, since it's a real poll
                arg_9.poll(10*arg_1)
                arg_0.do_one_iteration()
            except:
                raise
        except KeyboardInterrupt:
            # Ctrl-C shouldn't crash the kernel
            io.raw_print("KeyboardInterrupt caught in kernel")
        finally:
            # ensure excepthook is restored
            arg_6.excepthook = arg_2


def Func(arg_0, arg_1=None):
    """Enable integration with a given GUI"""
    if arg_0 not in loop_map:
        raise ValueError("GUI %r not supported" % arg_0)
    if arg_1 is None:
        if Application.initialized():
            arg_1 = getattr(Application.instance(), 'kernel', None)
        if arg_1 is None:
            raise RuntimeError("You didn't specify a kernel,"
                " and no IPython Application with a kernel appears to be running."
            )
    arg_2 = loop_map[arg_0]
    if arg_1.eventloop is not None and arg_1.eventloop is not arg_2:
        raise RuntimeError("Cannot activate multiple GUI eventloops")
    arg_1.eventloop = arg_2


def Func(arg_0):
    """Compute the eigvals of mat and then find the center eigval difference."""
    arg_1 = len(arg_0)
    arg_2 = np.sort(la.eigvals(arg_0))
    arg_3 = np.abs(arg_2[arg_1/2] - arg_2[arg_1/2-1])
    return arg_3


def Func(arg_0, arg_1, arg_2):
        """
        Initialize the item.  This calls the class constructor with the
        appropriate arguments and returns the Funcialized object.

        :param ctxt: The context object.
        :param step_addr: The address of the step in the test
                          configuration.
        """

        return arg_0.cls(arg_1, arg_0.name, arg_0.conf, arg_2)


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """
        Parse a YAML file containing test steps.

        :param ctxt: The context object.
        :param fname: The name of the file to parse.
        :param key: An optional dictionary key.  If specified, the
                    file must be a YAML dictionary, and the referenced
                    value will be interpreted as a list of steps.  If
                    not provided, the file must be a YAML list, which
                    will be interpreted as the list of steps.
        :param step_addr: The address of the step in the test
                          configuration.  This may be used in the case
                          of includes, for instance.

        :returns: A list of ``Step`` objects.
        """

        # Load the YAML file
        try:
            with open(arg_2) as f:
                arg_5 = yaml.load(f)
        except Exception as exc:
            raise ConfigError(
                'Failed to read file "%s": %s' % (arg_2, exc),
                arg_4,
            )

        # Do we have a key?
        if arg_3 is not None:
            if (not isinstance(arg_5, collections.Mapping) or
                    arg_3 not in arg_5):
                raise ConfigError(
                    'Bad step configuration file "%s": expecting dictionary '
                    'with key "%s"' % (arg_2, arg_3),
                    arg_4,
                )

            # Extract just the step data
            arg_5 = arg_5[arg_3]

        # Validate that it's a sequence
        if not isinstance(arg_5, collections.Sequence):
            arg_6 = ('%s[%s]' % (arg_2, arg_3)) if arg_3 is not None else arg_2
            raise ConfigError(
                'Bad step configuration sequence at %s: expecting list, '
                'not "%s"' % (arg_6, arg_5.__class__.__name__),
                arg_4,
            )

        # OK, assemble the step list and return it
        arg_7 = []
        for arg_8, arg_9 in enumerate(arg_5):
            arg_7.extend(arg_0.parse_step(
                arg_1, StepAddress(arg_2, arg_8, arg_3), arg_9))

        return arg_7


def Func(arg_0, arg_1):
        """
        Parse runtime path representation to list.

        :param string string: runtime path string
        :return: list of runtime paths
        :rtype: list of string
        """
        arg_2, arg_3, arg_4 = arg_1.strip().partition('=')
        assert arg_2 == 'runtimepath'
        assert arg_3 == '='
        return arg_4.split(',')


def Func(arg_0):
        """Create a crash handler, typically setting sys.excepthook to it."""
        arg_0.crash_handler = arg_0.crash_handler_class(arg_0)
        arg_2.excepthook = arg_0.excepthook
        def unset_crashhandler():
            arg_2.excepthook = arg_2.__excepthook__
        atexit.register(unset_crashhandler)


def Func(arg_0, arg_1=True):
        """Load the config file.

        By default, errors in loading config are handled, and a warning
        printed on screen. For testing, the suppress_errors option is set
        to False, so errors will make tests fail.
        """
        arg_0.log.debug("Searching path %s for config files", arg_0.config_file_paths)
        arg_2 = 'ipython_config.py'
        arg_0.log.debug("Attempting to load config file: %s" %
                       arg_2)
        try:
            Application.Func(
                arg_0,
                arg_2,
                path=arg_0.config_file_paths
            )
        except ConfigFileNotFound:
            # ignore errors loading parent
            arg_0.log.debug("Config file %s not found", arg_2)
            pass
        if arg_0.config_file_name == arg_2:
            # don't load secondary config
            return
        arg_0.log.debug("Attempting to load config file: %s" %
                       arg_0.config_file_name)
        try:
            Application.Func(
                arg_0,
                arg_0.config_file_name,
                path=arg_0.config_file_paths
            )
        except ConfigFileNotFound:
            # Only warn if the default config file was NOT being used.
            if arg_0.config_file_specified:
                arg_3 = arg_0.log.warn
            else:
                arg_3 = arg_0.log.debug
            arg_3("Config file not found, skipping: %s", arg_0.config_file_name)
        except:
            # For testing purposes.
            if not arg_1:
                raise
            arg_0.log.warn("Error loading config file: %s" %
                          arg_0.config_file_name, exc_info=True)


def Func(arg_0):
        """initialize the profile dir"""
        try:
            # location explicitly specified:
            arg_1 = arg_0.config.ProfileDir.location
        except AttributeError:
            # location not specified, find by profile name
            try:
                arg_2 = ProfileDir.find_profile_dir_by_name(arg_0.ipython_dir, arg_0.profile, arg_0.config)
            except ProfileDirError:
                # not found, maybe create it (always create default profile)
                if arg_0.auto_create or arg_0.profile=='default':
                    try:
                        arg_2 = ProfileDir.create_profile_dir_by_name(arg_0.ipython_dir, arg_0.profile, arg_0.config)
                    except ProfileDirError:
                        arg_0.log.fatal("Could not create profile: %r"%arg_0.profile)
                        arg_0.exit(1)
                    else:
                        arg_0.log.info("Created profile dir: %r"%arg_2.location)
                else:
                    arg_0.log.fatal("Profile %r not found."%arg_0.profile)
                    arg_0.exit(1)
            else:
                arg_0.log.info("Using existing profile dir: %r"%arg_2.location)
        else:
            # location is fully specified
            try:
                arg_2 = ProfileDir.find_profile_dir(arg_1, arg_0.config)
            except ProfileDirError:
                # not found, maybe create it
                if arg_0.auto_create:
                    try:
                        arg_2 = ProfileDir.create_profile_dir(arg_1, arg_0.config)
                    except ProfileDirError:
                        arg_0.log.fatal("Could not create profile directory: %r"%arg_1)
                        arg_0.exit(1)
                    else:
                        arg_0.log.info("Creating new profile dir: %r"%arg_1)
                else:
                    arg_0.log.fatal("Profile directory %r not found."%arg_1)
                    arg_0.exit(1)
            else:
                arg_0.log.info("Using existing profile dir: %r"%arg_1)

        arg_0.profile_dir = arg_2
        arg_0.config_file_paths.append(arg_2.location)


def Func(arg_0):
        """auto generate default config file, and stage it into the profile."""
        arg_1 = arg_0.generate_config_file()
        arg_2 = os.path.join(arg_0.profile_dir.location, arg_0.config_file_name)
        if arg_0.overwrite or not os.path.exists(arg_2):
            arg_0.log.warn("Generating default config file: %r"%(arg_2))
            with open(arg_2, 'w') as f:
                f.write(arg_1)


def Func(arg_0, *arg_1):
        """
        Add some bundle to build group

        :type bundle: static_bundle.bundles.AbstractBundle
        @rtype: BuildGroup
        """
        for arg_2 in arg_1:
            if not arg_0.multitype and arg_0.has_bundles():
                arg_3 = arg_0.get_first_bundle()
                if arg_3.get_type() != arg_2.get_type():
                    raise Exception(
                        'Different bundle types for one Asset: %s[%s -> %s]'
                        'check types or set multitype parameter to True'
                        % (arg_0.name, arg_3.get_type(), arg_2.get_type())
                    )
            arg_0.bundles.append(arg_2)
        return arg_0


def Func(arg_0):
        """
        Return collected files links

        :rtype: list[static_bundle.files.StaticFileResult]
        """
        arg_0.files = []
        for arg_2 in arg_0.bundles:
            arg_2.init_build(arg_0, arg_0.builder)
            arg_3 = arg_2.prepare()
            arg_0.files.extend(arg_3)
        return arg_0


def Func(arg_0, arg_1):
        """
        Render all includes in asset by names

        :type name: str|unicode
        :rtype: str|unicode
        """
        arg_2 = ""
        if arg_0.has_asset(arg_1):
            arg_3 = arg_0.get_asset(arg_1)
            if arg_3.files:
                for arg_4 in arg_3.files:
                    arg_2 += arg_4.render_include() + "\r\n"
        return arg_2


def Func(arg_0, arg_1=None):
        """
        Return links without build files
        """
        for arg_2 in arg_0.assets.values():
            if arg_2.has_bundles():
                arg_2.collect_files()
        if arg_1 is None:
            arg_1 = arg_0.config.env
        if arg_1 == static_bundle.ENV_PRODUCTION:
            arg_0._minify(emulate=True)
        arg_0._add_url_prefix()


def Func(arg_0, arg_1=None):
        """Write the collected coverage data to a file.

        `suffix` is a suffix to append to the base file name. This can be used
        for multiple or parallel execution, so that many coverage data files
        can exist simultaneously.  A dot will be used to join the base name and
        the suffix.

        """
        if arg_0.use_file:
            arg_2 = arg_0.filename
            if arg_1:
                arg_2 += "." + arg_1
            arg_0.Func_file(arg_2)


def Func(arg_0):
        """Erase the data, both in this object, and from its file storage."""
        if arg_0.use_file:
            if arg_0.filename:
                file_be_gone(arg_0.filename)
        arg_0.lines = {}
        arg_0.arcs = {}


def Func(arg_0):
        """Return the map from filenames to lists of line numbers executed."""
        return dict(
            [(arg_1, sorted(arg_2.keys())) for arg_1, arg_2 in iitems(arg_0.lines)]
            )


def Func(arg_0):
        """Return the map from filenames to lists of line number pairs."""
        return dict(
            [(arg_1, sorted(arg_2.keys())) for arg_1, arg_2 in iitems(arg_0.arcs)]
            )


def Func(arg_0, arg_1):
        """Write the coverage data to `filename`."""

        # Create the file data.
        arg_2 = {}

        arg_2['lines'] = arg_0.line_data()
        arg_3 = arg_0.arc_data()
        if arg_3:
            arg_2['arcs'] = arg_3

        if arg_0.collector:
            arg_2['collector'] = arg_0.collector

        if arg_0.debug and arg_0.debug.should('dataio'):
            arg_0.debug.write("Writing data to %r" % (arg_1,))

        # Write the pickle to the file.
        arg_4 = open(arg_1, 'wb')
        try:
            pickle.dump(arg_2, arg_4, 2)
        finally:
            arg_4.close()


def Func(arg_0, arg_1=None):
        """Combine a number of data files together.

        Treat `self.filename` as a file prefix, and combine the data from all
        of the data files starting with that prefix plus a dot.

        If `aliases` is provided, it's a `PathAliases` object that is used to
        re-map paths to match the local machine's.

        """
        arg_1 = arg_1 or PathAliases()
        arg_2, arg_3 = os.path.split(arg_0.filename)
        arg_4 = arg_3 + '.'
        for arg_5 in os.listdir(arg_2 or '.'):
            if arg_5.startswith(arg_4):
                arg_6 = os.path.join(arg_2, arg_5)
                arg_7, arg_8 = arg_0._read_file(arg_6)
                for arg_9, arg_10 in iitems(arg_7):
                    arg_9 = arg_1.map(arg_9)
                    arg_0.lines.setdefault(arg_9, {}).update(arg_10)
                for arg_9, arg_10 in iitems(arg_8):
                    arg_9 = arg_1.map(arg_9)
                    arg_0.arcs.setdefault(arg_9, {}).update(arg_10)
                if arg_5 != arg_3:
                    os.remove(arg_6)


def Func(arg_0, arg_1):
        """Add executed line data.

        `line_data` is { filename: { lineno: None, ... }, ...}

        """
        for arg_2, arg_3 in iitems(arg_1):
            arg_0.lines.setdefault(arg_2, {}).update(arg_3)


def Func(arg_0, arg_1=False):
        """Return a dict summarizing the coverage data.

        Keys are based on the filenames, and values are the number of executed
        lines.  If `fullpath` is true, then the keys are the full pathnames of
        the files, otherwise they are the basenames of the files.

        """
        arg_2 = {}
        if arg_1:
            arg_3 = lambda f: f
        else:
            arg_3 = os.path.basename
        for arg_4, arg_5 in iitems(arg_0.lines):
            arg_2[arg_3(arg_4)] = len(arg_5)
        return arg_2


def Func(arg_0):
    """ Coerce everything to strings.
    All objects representing time get output according to default_date_fmt.
    """
    if isinstance(arg_0, (datetime.datetime, datetime.date, datetime.time)):
        return arg_0.strftime(default_date_fmt)
    else:
        return str(arg_0)


def Func(arg_0=None,
              arg_1=None,
              arg_2='root',
              arg_3=arg_4.DEBUG,
              arg_6=1*1024*1024,
              arg_7=5,
              arg_8='default',
              arg_9=None,
              arg_10=None):
    """Initialize the zlogger.

    Sets up a rotating file handler to the specified path and file with
    the given size and backup count limits, sets the default
    application_name, server_hostname, and default/whitelist fields.

    :param path: path to write the log file
    :param target: name of the log file
    :param logger_name: name of the logger (defaults to root)
    :param level: log level for this logger (defaults to logging.DEBUG)
    :param maxBytes: size of the file before rotation (default 1MB)
    :param application_name: app name to add to each log entry
    :param server_hostname: hostname to add to each log entry
    :param fields: default/whitelist fields.
    :type path: string
    :type target: string
    :type logger_name: string
    :type level: int
    :type maxBytes: int
    :type backupCount: int
    :type application_name: string
    :type server_hostname: string
    :type fields: dict
    """
    arg_11 = os.path.abspath(
        os.path.join(arg_0, arg_1))
    arg_12 = arg_4.getLogger(arg_2)
    arg_12.setLevel(arg_3)

    arg_13 = arg_4.handlers.RotatingFileHandler(
        arg_11, arg_6=arg_6, arg_7=arg_7)
    arg_13.setLevel(arg_3)

    arg_13.setFormatter(
        JsonFormatter(
            arg_8=arg_8,
            arg_9=arg_9,
            arg_10=arg_10))

    arg_12.addHandler(arg_13)


def Func(arg_0, arg_1=arg_2.input):
    """ Yield pasted lines until the user enters the given sentinel value.
    """
    print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
          % arg_0
    while True:
        try:
            arg_4 = arg_1(':')
            if arg_4 == arg_0:
                return
            else:
                yield arg_4
        except EOFError:
            print '<EOF>'
            return


def Func(arg_0, arg_1=None):
        """Start the Func.

        If an optional banner argument is given, it will override the
        internally created default banner.
        """

        with nested(arg_0.builtin_trap, arg_0.display_trap):

            while 1:
                try:
                    arg_0.interact(arg_1=arg_1)
                    #self.interact_with_readline()
                    # XXX for testing of a readline-decoupled repl loop, call
                    # interact_with_readline above
                    break
                except KeyboardInterrupt:
                    # this should not be necessary, but KeyboardInterrupt
                    # handling seems rather unpredictable...
                    arg_0.write("\nKeyboardInterrupt in interact()\n")


def Func(arg_0, arg_1, arg_2):
        """Store multiple lines as a single entry in history"""

        # do nothing without readline or disabled multiline
        if not arg_0.has_readline or not arg_0.multiline_history:
            return arg_2

        # windows rl has no remove_history_item
        if not hasattr(arg_0.readline, "remove_history_item"):
            return arg_2

        # skip empty cells
        if not arg_1.rstrip():
            return arg_2

        # nothing changed do nothing, e.g. when rl removes consecutive dups
        arg_3 = arg_0.readline.get_current_history_length()
        if arg_3 == arg_2:
            return arg_2

        for arg_4 in range(arg_3 - arg_2):
            arg_0.readline.remove_history_item(arg_3 - arg_4 - 1)
        arg_5 = get_stream_enc(sys.stdin, 'utf-8')
        arg_0.readline.add_history(py3compat.unicode_to_str(arg_1.rstrip(),
                                    arg_5))
        return arg_0.readline.get_current_history_length()


def Func(arg_0, arg_1=''):
        """Write a prompt and read a line.

        The returned line does not include the trailing newline.
        When the user enters the EOF key sequence, EOFError is raised.

        Optional inputs:

          - prompt(''): a string to be printed to prompt the user.

          - continue_prompt(False): whether this line is the first one or a
          continuation in a sequence of inputs.
        """
        # Code run by the user may have modified the readline completer state.
        # We must ensure that our completer is back in place.

        if arg_0.has_readline:
            arg_0.set_readline_completer()

        # Func expects str, but we pass it unicode sometimes
        arg_1 = py3compat.cast_bytes_py2(arg_1)

        try:
            arg_2 = py3compat.str_to_unicode(arg_0.Func_original(arg_1))
        except ValueError:
            warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
                 " or sys.stdout.close()!\nExiting IPython!\n")
            arg_0.ask_exit()
            return ""

        # Try to be reasonably smart about not re-indenting pasted input more
        # than necessary.  We do this by trimming out the auto-indent initial
        # spaces, if the user's actual input started itself with whitespace.
        if arg_0.autoindent:
            if num_ini_spaces(arg_2) > arg_0.indent_current_nsp:
                arg_2 = arg_2[arg_0.indent_current_nsp:]
                arg_0.indent_current_nsp = 0

        return arg_2


def Func(arg_0):
        """The bottom half of the syntax error handler called in the main loop.

        Loop until syntax error is fixed or user cancels.
        """

        while arg_0.SyntaxTB.last_syntax_error:
            # copy and clear last_syntax_error
            arg_1 = arg_0.SyntaxTB.clear_err_state()
            if not arg_0._should_recompile(arg_1):
                return
            try:
                # may set last_syntax_error again if a SyntaxError is raised
                arg_0.safe_execfile(arg_1.filename,arg_0.user_ns)
            except:
                arg_0.showtraceback()
            else:
                try:
                    arg_2 = open(arg_1.filename)
                    try:
                        # This should be inside a display_trap block and I
                        # think it is.
                        sys.displayhook(arg_2.read())
                    finally:
                        arg_2.close()
                except:
                    arg_0.showtraceback()


def Func(arg_0,arg_1):
        """Utility routine for edit_syntax_error"""

        if arg_1.filename in ('<ipython console>','<input>','<string>',
                          '<console>','<BackgroundJob compilation>',
                          None):

            return False
        try:
            if (arg_0.autoedit_syntax and
                not arg_0.ask_yes_no('Return to editor to correct syntax error? '
                              '[Y/n] ','y')):
                return False
        except EOFError:
            return False

        def int0(arg_2):
            try:
                return int(arg_2)
            except TypeError:
                return 0
        # always pass integer line and offset values to editor hook
        try:
            arg_0.hooks.fix_error_editor(arg_1.filename,
                int0(arg_1.lineno),int0(arg_1.offset),arg_1.msg)
        except TryNext:
            warn('Could not open editor')
            return False
        return True


def Func(arg_0):
        """Handle interactive Func.

        This method calls the ask_Func callback."""
        if arg_0.confirm_Func:
            if arg_0.ask_yes_no('Do you really want to Func ([y]/n)?','y'):
                arg_0.ask_Func()
        else:
            arg_0.ask_Func()


def Func(arg_0):
        """
        Returns the correct repository URL and revision by parsing the given
        repository URL
        """
        arg_1= (
           "Sorry, '%s' is a malformed VCS url. "
           "Ihe format is <vcs>+<protocol>://<url>, "
           "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp")
        assert '+' in arg_0.url, arg_1 % arg_0.url
        arg_2 = arg_0.url.split('+', 1)[1]
        arg_3, arg_4, arg_5, arg_6, arg_7 = urlparse.urlsplit(arg_2)
        arg_8 = None
        if '@' in arg_5:
            arg_5, arg_8 = arg_5.rsplit('@', 1)
        arg_2 = urlparse.urlunsplit((arg_3, arg_4, arg_5, arg_6, ''))
        return arg_2, arg_8


def Func(arg_0):
        """ Create and return new frontend attached to new kernel, launched on localhost.
        """
        arg_1 = arg_0.ip if arg_0.ip in LOCAL_IPS else LOCALHOST
        arg_2 = arg_0.kernel_manager_class(
                                arg_1=arg_1,
                                connection_file=arg_0._new_connection_file(),
                                config=arg_0.config,
        )
        # start the kernel
        arg_3 = dict()
        arg_3['extra_arguments'] = arg_0.kernel_argv
        arg_2.start_kernel(**arg_3)
        arg_2.start_channels()
        arg_4 = arg_0.widget_factory(config=arg_0.config,
                                   local_kernel=True)
        arg_0.init_colors(arg_4)
        arg_4.kernel_manager = arg_2
        arg_4._existing = False
        arg_4._may_close = True
        arg_4._confirm_exit = arg_0.confirm_exit
        return arg_4


def Func(arg_0):
        """return the connection Func for this object's sockets."""
        return (arg_0.identity, arg_0.url, arg_0.pub_url, arg_0.location)


def Func(arg_0, arg_1=False):
    """
    Convert an object in R's namespace to one suitable
    for ipython's namespace.

    For a data.frame, it tries to return a structured array.
    It first checks for colnames, then names.
    If all are NULL, it returns np.asarray(Robj), else
    it tries to construct a recarray

    Parameters
    ----------

    Robj: an R object returned from rpy2
    """
    arg_2 = ro.r('is.data.frame')
    arg_3 = ro.r('colnames')
    arg_4 = ro.r('rownames') # with pandas, these could be used for the index
    arg_5 = ro.r('names')

    if arg_1:
        arg_6 = ro.r('as.data.frame')
        arg_7 = arg_3(arg_0)
        arg_8 = arg_5(arg_0)
        if arg_7 != ri.NULL:
            arg_0 = arg_6(arg_0)
            arg_5 = tuple(np.array(arg_7))
        elif arg_8 != ri.NULL:
            arg_5 = tuple(np.array(arg_8))
        else: # failed to find names
            return np.asarray(arg_0)
        arg_0 = np.rec.fromarrays(arg_0, arg_5 = arg_5)
    return np.asarray(arg_0)