def Func(arg_0, arg_1):
    """
    Read entry from JSON file
    """
    with open(os.fsencode(str(arg_0)), "r") as f:
        arg_2 = json.load(f)
        arg_3 = [i for i in arg_2 if i["uuid"] == str(arg_1)]
        if arg_3:
            return arg_3
        return None


def Func(arg_0, arg_1):
    """
    Save entry to JSON file
    """
    with atomic_write(os.fsencode(str(arg_0))) as temp_file:
        with open(os.fsencode(str(arg_0))) as products_file:
            # load the JSON data into memory
            arg_2 = json.load(products_file)
        # check if UUID already exists
        arg_3 = [i for i in filter(
            lambda z: z["uuid"] == str(arg_1["uuid"]), arg_2)]
        if len(arg_3) == 0:
            # add the new item to the JSON file
            arg_2.append(arg_1)
            # save the new JSON to the temp file
            json.dump(arg_2, temp_file)
            return True
        return None


def Func(arg_0, arg_1, arg_2):
    """
    Update entry by UUID in the JSON file
    """
    with atomic_write(os.fsencode(str(arg_0))) as temp_file:
        with open(os.fsencode(str(arg_0))) as products_file:
            # load the JSON data into memory
            arg_3 = json.load(products_file)
        # apply modifications to the JSON data wrt UUID
        # TODO: handle this in a neat way
        if 'products' in arg_3[-1]:
            # handle orders object
            [arg_3[arg_4]["products"][0].update(arg_1) for (
                arg_4, arg_5) in enumerate(arg_3) if arg_5["uuid"] == str(arg_2)]
        else:
            # handle products object
            [arg_3[arg_4].update(arg_1) for (arg_4, arg_5) in enumerate(
                arg_3) if arg_5["uuid"] == str(arg_2)]
        # save the modified JSON data into the temp file
        json.dump(arg_3, temp_file)
        return True


def Func(arg_0, arg_1):
        """ Given a valid position in the text document, try to find the
            position of the matching bracket. Returns -1 if unsuccessful.
        """
        # Decide what character to search for and what direction to search in.
        arg_2 = arg_0._text_edit.document()
        arg_3 = arg_2.characterAt(arg_1)
        arg_4 = arg_0._opening_map.get(arg_3)
        if arg_4:
            arg_5 = 1
        else:
            arg_4 = arg_0._closing_map.get(arg_3)
            if arg_4:
                arg_5 = -1
            else:
                return -1

        # Search for the character.
        arg_6 = arg_3
        arg_7 = 0
        while arg_1 >= 0 and arg_1 < arg_2.characterCount():
            if arg_6 == arg_3:
                arg_7 += 1
            elif arg_6 == arg_4:
                arg_7 -= 1
            if arg_7 == 0:
                break
            arg_1 += arg_5
            arg_6 = arg_2.characterAt(arg_1)
        else:
            arg_1 = -1
        return arg_1


def Func(arg_0):
        """ Updates the document formatting based on the new cursor position.
        """
        # Clear out the old formatting.
        arg_0._text_edit.setExtraSelections([])

        # Attempt to match a bracket for the new cursor position.
        arg_1 = arg_0._text_edit.textCursor()
        if not arg_1.hasSelection():
            arg_2 = arg_1.position() - 1
            arg_3 = arg_0._find_match(arg_2)
            if arg_3 != -1:
                arg_4 = [ arg_0._selection_for_character(pos)
                                     for pos in (arg_2, arg_3) ]
                arg_0._text_edit.setExtraSelections(arg_4)


def Func(arg_0):
        """Bottleneck to fix up IronPython string exceptions
        """
        arg_1 = arg_0.exc_info()
        if sys.platform == 'cli':
            if isinstance(arg_1[0], StringException):
                # IronPython throws these StringExceptions, but
                # traceback checks type(etype) == str. Make a real
                # string here.
                arg_1 = (str(arg_1[0]), arg_1[1], arg_1[2])

        return arg_1


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Decorator for registering a simple path.

        Args:
            path (str): Path to be matched.
            method (str, optional): Usually used to define one of GET, POST,
                PUT, DELETE. You may use whatever fits your situation though.
                Defaults to None.
            type_cast (dict, optional): Mapping between the param name and
                one of `int`, `float` or `bool`. The value reflected by the
                provided param name will than be casted to the given type.
                Defaults to None.
        """
        if not arg_3:
            arg_3 = {}

        def decorator(arg_4):
            arg_0.s_add(arg_1, arg_4, arg_2, arg_3)
            return arg_4

        return decorator


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """Function for registering a simple path.

        Args:
            path (str): Path to be matched.
            function (function): Function to associate with this path.
            method (str, optional): Usually used to define one of GET, POST,
                PUT, DELETE. You may use whatever fits your situation though.
                Defaults to None.
            type_cast (dict, optional): Mapping between the param name and
                one of `int`, `float` or `bool`. The value reflected by the
                provided param name will than be casted to the given type.
                Defaults to None.
        """
        with arg_0._lock:
            try:
                arg_1 = '^/{}'.format(arg_1.lstrip('/'))
                arg_1 = '{}/$'.format(arg_1.rstrip('/'))
                arg_1 = arg_1.replace('<', '(?P<')
                arg_1 = arg_1.replace('>', '>[^/]*)')

                arg_0.add(arg_1, arg_2, arg_3, arg_4)
            except Exception:
                pass


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Calls the first function matching the urls pattern and method.

        Args:
            url (str): Url for which to Func a matching function.
            method (str, optional): The method used while registering a
                function.
                Defaults to None
            args (dict, optional): Additional args to be passed to the
                matching function.

        Returns:
            The functions return value or `None` if no function was Funced.
        """
        if not arg_3:
            arg_3 = {}

        if sys.version_info.major == 3:
            arg_4 = urllib.parse.urlparse(arg_1)
            arg_5 = arg_4.path.rstrip('/') + '/'
            arg_6 = dict(urllib.parse.parse_qs(arg_4.query,
                                               keep_blank_values=True))
        elif sys.version_info.major == 2:
            arg_4 = urlparse.urlparse(arg_1)
            arg_5 = arg_4.path.rstrip('/') + '/'
            arg_6 = dict(urlparse.parse_qs(arg_4.query,
                                           keep_blank_values=True))

        for arg_7 in arg_0._data_store:
            arg_8 = arg_7['pattern']
            arg_9 = arg_7['function']
            arg_10 = arg_7['method']
            arg_11 = arg_7['type_cast']

            arg_12 = re.match(arg_8, arg_5)

            # Found matching method
            if arg_12 and arg_10 == arg_2:
                arg_6 = dict(arg_6, **arg_12.groupdict())

                # Unpack value lists (due to urllib.parse.parse_qs) in case
                # theres only one value available
                for arg_13, arg_14 in arg_6.items():
                    if isinstance(arg_6[arg_13], list) and len(arg_6[arg_13]) == 1:
                        arg_6[arg_13] = arg_6[arg_13][0]

                # Apply typ-casting if necessary
                for arg_13, arg_14 in arg_11.items():

                    # Not within available _args, no type-cast required
                    if arg_13 not in arg_6:
                        continue

                    # Is None or empty, no type-cast required
                    if not arg_6[arg_13]:
                        continue

                    # Try and cast the values
                    if isinstance(arg_6[arg_13], list):
                        for arg_15, arg_16 in enumerate(arg_6[arg_13]):
                            arg_6[arg_13][arg_15] = arg_0._cast(arg_16, arg_14)
                    else:
                        arg_6[arg_13] = arg_0._cast(arg_6[arg_13], arg_14)

                arg_17 = arg_0._get_function_args(arg_9)
                for arg_13, arg_14 in arg_3.items():
                    if arg_13 in arg_17:
                        arg_6[arg_13] = arg_14

                return arg_9(**arg_6)

        return None


def Func(arg_0, arg_1):
        """ Called when the down key is pressed. Returns whether to continue
            processing the event.
        """
        arg_2 = arg_0._get_end_cursor()
        if arg_0._get_cursor().blockNumber() == arg_2.blockNumber():
            # Bail out if we're locked.
            if arg_0._history_locked() and not arg_1:
                return False

            # Perform the search.
            arg_3 = arg_0.history_next(arg_0._history_prefix,
                                            as_prefix=not arg_1)

            # Emulate readline: keep the cursor position fixed for a prefix
            # search. (We don't need to move the cursor to the end of the buffer
            # in the other case because this happens automatically when the
            # input buffer is set.)
            if arg_0._history_prefix and arg_3:
                arg_4 = arg_0._get_prompt_cursor()
                arg_4.movePosition(QtGui.QTextCursor.Right,
                                    n=len(arg_0._history_prefix))
                arg_0._set_cursor(arg_4)

            return False

        return True


def Func(arg_0, arg_1='', arg_2=True):
        """ If possible, set the input buffer to a subsequent history item.

        Parameters:
        -----------
        substring : str, optional
            If specified, search for an item with this substring.
        as_prefix : bool, optional
            If True, the substring must match at the beginning (default).

        Returns:
        --------
        Whether the input buffer was changed.
        """
        arg_3 = arg_0._history_index
        arg_4 = False
        while arg_0._history_index < len(arg_0._history):
            arg_3 += 1
            arg_5 = arg_0._get_edited_history(arg_3)
            if (arg_2 and arg_5.startswith(arg_1)) \
                or (not arg_2 and arg_1 in arg_5):
                arg_4 = True
                break

        if arg_4:
            arg_0._store_edits()
            arg_0._history_index = arg_3
            arg_0.input_buffer = arg_5

        return arg_4


def Func(arg_0, arg_1):
        """ Handles replies for code execution, here only session history length
        """
        arg_2 = arg_1['parent_header']['msg_id']
        arg_3 = arg_0._request_info['execute'].pop(arg_2,None)
        if arg_3 and arg_3.kind == 'save_magic' and not arg_0._hidden:
            arg_4 = arg_1['content']
            arg_5 = arg_4['status']
            if arg_5 == 'ok':
                arg_0._max_session_history=(int(arg_4['user_expressions']['hlen']))


def Func(arg_0):
        """ Returns whether history movement is locked.
        """
        return (arg_0.history_lock and
                (arg_0._get_edited_history(arg_0._history_index) !=
                 arg_0.input_buffer) and
                (arg_0._get_prompt_cursor().blockNumber() !=
                 arg_0._get_end_cursor().blockNumber()))


def Func(arg_0, arg_1):
        """ Replace the current history with a sequence of history items.
        """
        arg_0._history = list(arg_1)
        arg_0._history_edits = {}
        arg_0._history_index = len(arg_0._history)


def Func(arg_0, arg_1):
        """Event handler for the button click."""
        print("See ya later!")
        sys.stdout.flush()
        arg_0.cleanup_consoles(arg_1)
        arg_0.Close()
        # Not sure why, but our IPython kernel seems to prevent normal WX
        # shutdown, so an explicit exit() call is needed.
        sys.exit()


def Func(arg_0, **arg_1):
    '''
    Generates a list of Record objects given a DataFrame.
    Each Record instance has a series attribute which is a pandas.Series of the same attributes
    in the DataFrame.
    Optional data can be passed in through kwargs which will be included by the name of each object.

    parameters
    ----------
    df : pandas.DataFrame
    kwargs : alternate arguments to be saved by name to the series of each object

    Returns
    -------
    collection : list
        list of Record objects where each Record represents one row from a dataframe

    Examples
    --------
    This is how we generate a Record Collection from a DataFrame.

    >>> import pandas as pd
    >>> import turntable
    >>>
    >>> df = pd.DataFrame({'Artist':"""Michael Jackson, Pink Floyd, Whitney Houston, Meat Loaf,
        Eagles, Fleetwood Mac, Bee Gees, AC/DC""".split(', '),
    >>> 'Album' :"""Thriller, The Dark Side of the Moon, The Bodyguard, Bat Out of Hell,
        Their Greatest Hits (1971-1975), Rumours, Saturday Night Fever, Back in Black""".split(', ')})
    >>> collection = turntable.press.Func(df, my_favorite_record = 'nevermind')
    >>> record = collection[0]
    >>> print record.series

    '''

    print 'Generating the Record Collection...\n'

    arg_0['index_original'] = arg_0.index
    arg_0.reset_index(drop=True, inplace=True)

    if pd.__version__ >= '0.15.0':
        arg_2 = arg_0.T.to_dict(orient='series')
    else:
        arg_2 = arg_0.T.to_dict(outtype='series')

    arg_3 = [load_record(item, arg_1) for item in arg_2.items()]
    return arg_3


def Func(arg_0):
    '''
    Converts a collection back into a pandas DataFrame

    parameters
    ----------
    collection : list
        list of Record objects where each Record represents one row from a dataframe

    Returns
    -------
    df : pandas.DataFrame
        DataFrame of length=len(collection) where each row represents one Record

    '''

    return pd.concat([arg_1.series for arg_1 in arg_0], axis=1).T


def Func(arg_0, arg_1):
        '''
        Initalizes the given argument structure as properties of the class
        to be used by name in specific method execution.

        Parameters
        ----------
        kwargs : dictionary
            Dictionary of extra attributes,
            where keys are attributes names and values attributes values.

        '''

        for arg_2, arg_3 in arg_1.items():
            setattr(arg_0, arg_2, arg_3)


def Func(arg_0):
        """Update our SUB socket's subscriptions."""
        arg_0.stream.setsockopt(zmq.UNSUBSCRIBE, '')
        if '' in arg_0.topics:
            arg_0.log.debug("Subscribing to: everything")
            arg_0.stream.setsockopt(zmq.SUBSCRIBE, '')
        else:
            for arg_1 in arg_0.topics:
                arg_0.log.debug("Subscribing to: %r"%(arg_1))
                arg_0.stream.setsockopt(zmq.SUBSCRIBE, arg_1)


def Func(arg_0, arg_1):
        """receive and parse a message, then log it."""
        if len(arg_1) != 2 or '.' not in arg_1[0]:
            arg_0.log.error("Invalid log message: %s"%arg_1)
            return
        else:
            arg_2, arg_3 = arg_1
            # don't newline, since log messages always newline:
            arg_2,arg_4 = arg_2.rsplit('.',1)
            arg_5,arg_2 = arg_0._extract_level(arg_2)
            if arg_3[-1] == '\n':
                arg_3 = arg_3[:-1]
            arg_0.log.log(arg_5, "[%s] %s" % (arg_2, arg_3))


def Func(arg_0, arg_1=None):
    """ Perform an N-way merge operation on sorted lists.

    @param list_of_lists: (really iterable of iterable) of sorted elements
    (either by naturally or by C{key})
    @param key: specify sort key function (like C{sort()}, C{sorted()})

    Yields tuples of the form C{(item, iterator)}, where the iterator is the
    built-in list iterator or something you pass in, if you pre-generate the
    iterators.

    This is a stable merge; complexity O(N lg N)

    Examples::

    >>> print list(Func([[1,2,3,4],
    ...                      [2,3.25,3.75,4.5,6,7],
    ...                      [2.625,3.625,6.625,9]]))
    [1, 2, 2, 2.625, 3, 3.25, 3.625, 3.75, 4, 4.5, 6, 6.625, 7, 9]

    # note stability
    >>> print list(Func([[1,2,3,4],
    ...                      [2,3.25,3.75,4.5,6,7],
    ...                      [2.625,3.625,6.625,9]],
    ...                      key=int))
    [1, 2, 2, 2.625, 3, 3.25, 3.75, 3.625, 4, 4.5, 6, 6.625, 7, 9]

    >>> print list(Func([[4, 3, 2, 1],
    ...                      [7, 6, 4.5, 3.75, 3.25, 2],
    ...                      [9, 6.625, 3.625, 2.625]],
    ...                      key=lambda x: -x))
    [9, 7, 6.625, 6, 4.5, 4, 3.75, 3.625, 3.25, 3, 2.625, 2, 2, 1]
    """

    arg_2 = []
    for arg_3, arg_4 in enumerate(iter(pl) for pl in arg_0):
        try:
            arg_5 = arg_4.next()
            if arg_1:
                arg_6 = (arg_1(arg_5), arg_3, arg_5, arg_4)
            else:
                arg_6 = (arg_5, arg_3, arg_4)
            arg_2.append(arg_6)
        except StopIteration:
            pass
    heapq.heapify(arg_2)

    if arg_1:
        while arg_2:
            arg_7, arg_8, arg_5, arg_4 = arg_2[0]
            yield arg_5
            try:
                arg_5 = arg_4.next()
                heapq.heapreplace(arg_2, (arg_1(arg_5), arg_8, arg_5, arg_4) )
            except StopIteration:
                heapq.heappop(arg_2)

    else:
        while arg_2:
            arg_5, arg_8, arg_4 = arg_2[0]
            yield arg_5
            try:
                heapq.heapreplace(arg_2, (arg_4.next(), arg_8, arg_4))
            except StopIteration:
                heapq.heappop(arg_2)


def Func(arg_0,arg_1):
    """Return an iterator on an object living on a remote engine.
    """
    arg_0.execute('it%s=iter(%s)'%(arg_1,arg_1), block=True)
    while True:
        try:
            arg_2 = arg_0.apply_sync(lambda x: x.next(), Reference('it'+arg_1))
        # This causes the StopIteration exception to be raised.
        except RemoteError as e:
            if e.ename == 'StopIteration':
                raise StopIteration
            else:
                raise e
        else:
            yield arg_2


def Func():
    """Return this platform's maximum compatible version.

    distutils.util.get_platform() normally reports the minimum version
    of Mac OS X that would be required to *use* extensions produced by
    distutils.  But what we want when checking compatibility is to know the
    version of Mac OS X that we are *running*.  To allow usage of packages that
    explicitly require a newer version of Mac OS X, we must also know the
    current version of the OS.

    If this condition occurs for any other platform with a version in its
    platform strings, this function should be extended accordingly.
    """
    arg_0 = get_build_platform(); arg_1 = macosVersionString.match(arg_0)
    if arg_1 is not None and sys.platform == "darwin":
        try:
            arg_0 = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), arg_1.group(3))
        except ValueError:
            pass    # not Mac OS X
    return arg_0


def Func(arg_0):
    """Retrieve a PEP 302 "importer" for the given path item

    If there is no importer, this returns a wrapper around the builtin import
    machinery.  The returned importer is only cached if it was created by a
    path hook.
    """
    try:
        arg_1 = sys.path_importer_cache[arg_0]
    except KeyError:
        for arg_2 in sys.path_hooks:
            try:
                arg_1 = arg_2(arg_0)
            except ImportError:
                pass
            else:
                break
        else:
            arg_1 = None

    sys.path_importer_cache.setdefault(arg_0,arg_1)
    if arg_1 is None:
        try:
            arg_1 = ImpWrapper(arg_0)
        except ImportError:
            pass
    return arg_1


def Func(*arg_0, **arg_1):
    """Thunk to load the real Func on demand"""
    global Func
    try:
        from cFunc import Func
    except ImportError:
        from Func import Func
    return Func(*arg_0,**arg_1)


def Func(arg_0):
    """Convert a version string to a chronologically-sortable key

    This is a rough cross between distutils' StrictVersion and LooseVersion;
    if you give it versions that would work with StrictVersion, then it behaves
    the same; otherwise it acts like a slightly-smarter LooseVersion. It is
    *possible* to create pathological version coding schemes that will fool
    this parser, but they should be very rare in practice.

    The returned value will be a tuple of strings.  Numeric portions of the
    version are padded to 8 digits so they will compare numerically, but
    without relying on how numbers compare relative to strings.  Dots are
    dropped, but dashes are retained.  Trailing zeros between alpha segments
    or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
    "2.4". Alphanumeric parts are lower-cased.

    The algorithm assumes that strings like "-" and any alpha string that
    alphabetically follows "final"  represents a "patch level".  So, "2.4-1"
    is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
    considered newer than "2.4-1", which in turn is newer than "2.4".

    Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
    come before "final" alphabetically) are assumed to be pre-release versions,
    so that the version "2.4" is considered newer than "2.4a1".

    Finally, to handle miscellaneous cases, the strings "pre", "preview", and
    "rc" are treated as if they were "c", i.e. as though they were release
    candidates, and therefore are not as new as a version string that does not
    contain them, and "dev" is replaced with an '@' so that it sorts lower than
    than any other pre-release tag.
    """
    arg_1 = []
    for arg_2 in _Func_parts(arg_0.lower()):
        if arg_2.startswith('*'):
            # remove trailing zeros from each series of numeric parts
            while arg_1 and arg_1[-1]=='00000000':
                arg_1.pop()
        arg_1.append(arg_2)
    return tuple(arg_1)


def Func(arg_0):
    """Return True when distribute wants to override a setuptools dependency.

    We want to override when the requirement is setuptools and the version is
    a variant of 0.6.

    """
    if arg_0.project_name == 'setuptools':
        if not len(arg_0.specs):
            # Just setuptools: ok
            return True
        for arg_1, arg_2 in arg_0.specs:
            if arg_1 in ['==', '>=', '>']:
                if '0.7' in arg_2:
                    # We want some setuptools not from the 0.6 series.
                    return False
        return True
    return False


def Func(arg_0, arg_1, arg_2=None, arg_3=True, arg_4=False):
        """Add `dist` to working set, associated with `entry`

        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
        On exit from this routine, `entry` is Funced to the end of the working
        set's ``.entries`` (if it wasn't already present).

        `dist` is only Funced to the working set if it's for a project that
        doesn't already have a distribution in the set, unless `replace=True`.
        If it's Funced, any callbacks registered with the ``subscribe()`` method
        will be called.
        """
        if arg_3:
            arg_1.insert_on(arg_0.entries, arg_2)

        if arg_2 is None:
            arg_2 = arg_1.location
        arg_5 = arg_0.entry_keys.setdefault(arg_2,[])
        arg_6 = arg_0.entry_keys.setdefault(arg_1.location,[])
        if not arg_4 and arg_1.key in arg_0.by_key:
            return      # ignore hidden distros

        arg_0.by_key[arg_1.key] = arg_1
        if arg_1.key not in arg_5:
            arg_5.append(arg_1.key)
        if arg_1.key not in arg_6:
            arg_6.append(arg_1.key)
        arg_0._Funced_new(arg_1)


def Func(arg_0,
        arg_1, arg_2=None, arg_3=None, arg_4=True
    ):
        """Find all activatable distributions in `plugin_env`

        Example usage::

            distributions, errors = working_set.Func(
                Environment(plugin_dirlist)
            )
            map(working_set.add, distributions)  # add plugins+libs to sys.path
            print 'Could not load', errors        # display errors

        The `plugin_env` should be an ``Environment`` instance that contains
        only distributions that are in the project's "plugin directory" or
        directories. The `full_env`, if supplied, should be an ``Environment``
        contains all currently-available distributions.  If `full_env` is not
        supplied, one is created automatically from the ``WorkingSet`` this
        method is called on, which will typically mean that every directory on
        ``sys.path`` will be scanned for distributions.

        `installer` is a standard installer callback as used by the
        ``resolve()`` method. The `fallback` flag indicates whether we should
        attempt to resolve older versions of a plugin if the newest version
        cannot be resolved.

        This method returns a 2-tuple: (`distributions`, `error_info`), where
        `distributions` is a list of the distributions found in `plugin_env`
        that were loadable, along with any other distributions that are needed
        to resolve their dependencies.  `error_info` is a dictionary mapping
        unloadable plugin distributions to an exception instance describing the
        error that occurred. Usually this will be a ``DistributionNotFound`` or
        ``VersionConflict`` instance.
        """

        arg_5 = list(arg_1)
        arg_5.sort()  # scan project names in alphabetic order

        arg_6 = {}
        arg_7 = {}

        if arg_2 is None:
            arg_8 = Environment(arg_0.entries)
            arg_8 += arg_1
        else:
            arg_8 = arg_2 + arg_1

        arg_9 = arg_0.__class__([])
        map(arg_9.add, arg_0)   # put all our entries in shadow_set

        for arg_10 in arg_5:

            for arg_11 in arg_1[arg_10]:

                arg_12 = [arg_11.as_requirement()]

                try:
                    arg_13 = arg_9.resolve(arg_12, arg_8, arg_3)

                except ResolutionError,v:
                    arg_6[arg_11] = v    # save error info
                    if arg_4:
                        continue    # try the next older version of project
                    else:
                        break       # give up on this project, keep going

                else:
                    map(arg_9.add, arg_13)
                    arg_7.update(dict.fromkeys(arg_13))

                    # success, no need to try any more versions of this project
                    break

        arg_7 = list(arg_7)
        arg_7.sort()

        return arg_7, arg_6


def Func(arg_0, arg_1, arg_2=()):
        """Return absolute location in cache for `archive_name` and `names`

        The parent directory of the resulting path will be created if it does
        not already exist.  `archive_name` should be the base filename of the
        enclosing egg (which may not be the name of the enclosing zipfile!),
        including its ".egg" extension.  `names`, if provided, should be a
        sequence of path name parts "under" the egg's extraction location.

        This method should only be called by resource providers that need to
        obtain an extraction location, and only for names they intend to
        extract, as it tracks the generated names for possible cleanup later.
        """
        arg_3 = arg_0.extraction_path or get_default_cache()
        arg_4 = os.path.join(arg_3, arg_1+'-tmp', *arg_2)
        try:
            _bypass_ensure_directory(arg_4)
        except:
            arg_0.extraction_error()

        arg_0.cached_files[arg_4] = 1
        return arg_4


def Func(arg_0, arg_1, arg_2=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1,extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        try:
            arg_3 = arg_6 = ()
            arg_4,arg_5 = arg_1.split('=',1)
            if '[' in arg_5:
                arg_5,arg_6 = arg_5.split('[',1)
                arg_7 = Requirement.Func("x["+arg_6)
                if arg_7.specs: raise ValueError
                arg_6 = arg_7.extras
            if ':' in arg_5:
                arg_5,arg_3 = arg_5.split(':',1)
                if not MODULE(arg_3.rstrip()):
                    raise ValueError
                arg_3 = arg_3.rstrip().split('.')
        except ValueError:
            raise ValueError(
                "EntryPoint must be in 'name=module:attrs [extras]' format",
                arg_1
            )
        else:
            return arg_0(arg_4.strip(), arg_5.strip(), arg_3, arg_6, arg_2)


def Func(arg_0):
        """Parse and cache metadata"""
        try:
            return arg_0._pkg_info
        except AttributeError:
            from email.parser import Parser
            arg_0._pkg_info = Parser().parsestr(arg_0.get_metadata(arg_0.PKG_INFO))
            return arg_0._pkg_info


def Func(arg_0, arg_1):
        """ Reimplemented to disconnect signal handlers and event filter.
        """
        super(CompletionWidget, arg_0).Func(arg_1)
        arg_0._text_edit.cursorPositionChanged.disconnect(arg_0._update_current)
        arg_0._text_edit.removeEventFilter(arg_0)


def Func(arg_0):
        """ Returns a cursor with text between the start position and the
            current position selected.
        """
        arg_1 = arg_0._text_edit.textCursor()
        if arg_1.position() >= arg_0._start_position:
            arg_1.setPosition(arg_0._start_position,
                               QtGui.QTextCursor.KeepAnchor)
        return arg_1


def Func(arg_0):
        """ Updates the current item based on the current text.
        """
        arg_1 = arg_0._current_text_cursor().selection().toPlainText()
        if arg_1:
            arg_2 = arg_0.findItems(arg_1, (QtCore.Qt.MatchStartsWith |
                                            QtCore.Qt.MatchCaseSensitive))
            if arg_2:
                arg_0.setCurrentItem(arg_2[0])
            else:
                arg_0.hide()
        else:
            arg_0.hide()


def Func():
    """Return system per-CPU times as a list of named tuples."""
    arg_0 = []
    for arg_1 in _psutil_mswindows.get_system_cpu_times():
        arg_2, arg_3, arg_4 = arg_1
        arg_5 = _cputimes_ntuple(arg_2, arg_3, arg_4)
        arg_0.append(arg_5)
    return arg_0


def Func(arg_0):
        """Use the raw Win32 handle of sys.stdin to do non-blocking reads"""
        # WARNING: This is experimental, and produces inconsistent results.
        #          It's possible for the handle not to be appropriate for use
        #          with WaitForSingleObject, among other things.
        arg_1 = msvcrt.get_osfhandle(sys.stdin.fileno())
        arg_2 = WaitForSingleObject(arg_1, 100)
        if arg_2 == WAIT_FAILED:
            raise ctypes.WinError()
        elif arg_2 == WAIT_TIMEOUT:
            print(".", end='')
            return None
        else:
            arg_3 = ctypes.create_string_buffer(256)
            arg_4 = DWORD(0)
            print('?', end='')

            if not ReadFile(arg_1, arg_3, 256,
                        ctypes.byref(arg_4), None):
                raise ctypes.WinError()
            # This ensures the non-blocking works with an actual console
            # Not checking the error, so the processing will still work with
            # other handle types
            FlushConsoleInputBuffer(arg_1)

            arg_3 = arg_3.value
            arg_3 = arg_3.replace('\r\n', '\n')
            arg_3 = arg_3.replace('\r', '\n')
            print(repr(arg_3) + " ", end='')
            return arg_3


def Func(arg_0):
        """ update visibility of the tabBar depending of the number of tab

        0 or 1 tab, tabBar hidden
        2+ tabs, tabBar visible

        send a self.close if number of tab ==0

        need to be called explicitly, or be connected to tabInserted/tabRemoved
        """
        if arg_0.tab_widget.count() <= 1:
            arg_0.tab_widget.tabBar().setVisible(False)
        else:
            arg_0.tab_widget.tabBar().setVisible(True)
        if arg_0.tab_widget.count()==0 :
            arg_0.close()


def Func(arg_0,arg_1,arg_2=None):
        """ insert a tab with a given frontend in the tab bar, and give it a name

        """
        if not arg_2:
            arg_2 = 'kernel %i' % arg_0.next_kernel_id
        arg_0.tab_widget.addTab(arg_1,arg_2)
        arg_0.update_tab_bar_visibility()
        arg_0.make_frontend_visible(arg_1)
        arg_1.exit_requested.connect(arg_0.close_tab)


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """Add action to menu as well as self

        So that when the menu bar is invisible, its actions are still available.

        If defer_shortcut is True, set the shortcut context to widget-only,
        where it will avoid conflict with shortcuts already bound to the
        widgets themselves.
        """
        arg_1.addAction(arg_2)
        arg_0.addAction(arg_2)

        if arg_3:
            arg_2.setShortcutContext(QtCore.Qt.WidgetShortcut)


def Func(arg_0,arg_1):
        """Return a function `fun` that will execute `magic` on active frontend.

        Parameters
        ----------
        magic : string
            string that will be executed as is when the returned function is called

        Returns
        -------
        fun : function
            function with no parameters, when called will execute `magic` on the
            current active frontend at call time

        See Also
        --------
        populate_all_magic_menu : generate the "All Magics..." menu

        Notes
        -----
        `fun` executes `magic` in active frontend at the moment it is triggered,
        not the active frontend at the moment it was created.

        This function is mostly used to create the "All Magics..." Menu at run time.
        """
        # need two level nested function to be sure to pass magic
        # to active frontend **at run time**.
        def arg_2():
            arg_0.active_frontend.execute(arg_1)
        arg_2.__name__ = "dynamics_magic_s"
        return arg_2


def Func(arg_0, arg_1=None):
        """Clean "All Magics..." menu and repopulate it with `listofmagic`

        Parameters
        ----------
        listofmagic : string,
            repr() of a list of strings, send back by the kernel

        Notes
        -----
        `listofmagic`is a repr() of list because it is fed with the result of
        a 'user_expression'
        """
        for arg_2,arg_3 in arg_0._magic_menu_dict.items():
            arg_3.clear()
        arg_0.all_magic_menu.clear()

        arg_4 = set(["more","less","load_ext","pycat","loadpy","load","save","psource"])
        arg_5=ast.literal_eval(arg_1)
        for arg_6 in arg_5:
            arg_7 = (arg_6['type'] == 'cell')
            arg_8 = arg_6['name']
            arg_9 = arg_6['class']
            if arg_7 :
                arg_10='%%'
            else :
                arg_10='%'
            arg_11 = arg_0._get_magic_menu(arg_9)

            if arg_8 in arg_4:
                arg_12 = '?'
            else :
                arg_12 = ''
            arg_13 = '%s%s%s'%(arg_10,arg_8,arg_12)

            arg_14 = QtGui.QAction(arg_13,
                arg_0,
                triggered=arg_0._make_dynamic_magic(arg_13)
                )
            arg_11.addAction(arg_14)
            arg_0.all_magic_menu.addAction(arg_14)


def Func(arg_0=None, arg_1='sha1'):
    """Generate hashed password and salt for use in notebook configuration.

    In the notebook configuration, set `c.NotebookApp.password` to
    the generated string.

    Parameters
    ----------
    passphrase : str
        Password to hash.  If unspecified, the user is asked to input
        and verify a password.
    algorithm : str
        Hashing algorithm to use (e.g, 'sha1' or any argument supported
        by :func:`hashlib.new`).

    Returns
    -------
    hashed_passphrase : str
        Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'.

    Examples
    --------
    In [1]: Func('mypassword')
    Out[1]: 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12'

    """
    if arg_0 is None:
        for arg_2 in range(3):
            p0 = getpass.getpass('Enter password: ')
            p1 = getpass.getpass('Verify password: ')
            if p0 == p1:
                arg_0 = p0
                break
            else:
                print('Passwords do not match.')
        else:
            raise UsageError('No matching passwords found. Giving up.')

    arg_3 = hashlib.new(arg_1)
    arg_4 = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
    arg_3.update(cast_bytes(arg_0, 'utf-8') + str_to_bytes(arg_4, 'ascii'))

    return ':'.join((arg_1, arg_4, arg_3.hexdigest()))


def Func(arg_0, arg_1):
    """Verify that a given passphrase matches its hashed version.

    Parameters
    ----------
    hashed_passphrase : str
        Hashed password, in the format returned by `passwd`.
    passphrase : str
        Passphrase to validate.

    Returns
    -------
    valid : bool
        True if the passphrase matches the hash.

    Examples
    --------
    In [1]: from IPython.lib.security import Func

    In [2]: Func('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
       ...:              'mypassword')
    Out[2]: True

    In [3]: Func('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
       ...:              'anotherpassword')
    Out[3]: False

    """
    try:
        arg_2, arg_3, arg_4 = arg_0.split(':', 2)
    except (ValueError, TypeError):
        return False

    try:
        arg_5 = hashlib.new(arg_2)
    except ValueError:
        return False

    if len(arg_4) == 0:
        return False

    arg_5.update(cast_bytes(arg_1, 'utf-8') + str_to_bytes(arg_3, 'ascii'))

    return arg_5.hexdigest() == arg_4


def Func(arg_0, arg_1, arg_2='', arg_3=None):
    """
    Generate a html snippet for showing a boolean value on the admin page.
    Item is an object, attr is the attribute name we should display. Text
    is an optional explanatory text to be included in the output.

    This function will emit code to produce a checkbox input with its state
    corresponding to the item.attr attribute if no override value is passed.
    This input is wired to run a JS ajax updater to toggle the value.

    If override is passed in, ignores the attr attribute and returns a
    static image for the override boolean with no user interaction possible
    (useful for "disabled and you can't change it" situations).
    """
    if arg_2:
        arg_2 = ' (%s)' % unicode(arg_2)

    if arg_3 is not None:
        arg_4 = [django_boolean_icon(arg_3, arg_2), arg_2]
    else:
        arg_5 = getattr(arg_0, arg_1)
        arg_4 = [
            '<input type="checkbox"',
            arg_5 and ' checked="checked"' or '',
            ' onclick="return inplace_toggle_boolean(%d, \'%s\')";' % (arg_0.id, arg_1),
            ' />',
            arg_2,
        ]

    arg_4.insert(0, '
' % ( arg_1, arg_0.id ))
    arg_4.append('
')
    return unicode(''.join(arg_4))


def Func(arg_0, arg_1):
        arg_2 = ""
        """
        Generate a short title for an object, indent it depending on
        the object's depth in the hierarchy.
        """
        if hasattr(arg_1, 'get_absolute_url'):
            arg_2 = '<input type="hidden" class="medialibrary_file_path" value="%s" />' % arg_1.get_absolute_url()

        arg_3 = ''
        if not getattr(arg_1, 'feincms_editable', True):
            arg_3 = ' tree-item-not-editable'

        arg_2 += '  ' % (
            arg_1.id, arg_3, 14 + arg_1.level * 18)
        #        r += ''
        if hasattr(arg_1, 'short_title'):
            arg_2 += arg_1.short_title()
        else:
            arg_2 += unicode(arg_1)
            #        r += ''
        return mark_safe(arg_2)


def Func(arg_0):
        """
        Collect all fields marked as editable booleans. We do not
        want the user to be able to edit arbitrary fields by crafting
        an AJAX request by hand.
        """
        if hasattr(arg_0, '_ajax_editable_booleans'):
            return

        arg_0._ajax_editable_booleans = {}

        for arg_2 in arg_0.list_display:
            # The ajax_editable_boolean return value has to be assigned
            # to the ModelAdmin class
            arg_3 = getattr(arg_0.__class__, arg_2, None)
            if not arg_3:
                continue

            arg_4 = getattr(arg_3, 'editable_boolean_field', None)
            if arg_4:
                def arg_6(arg_0, arg_5):
                    return [ajax_editable_boolean_cell(arg_5, arg_6.attr)]

                arg_6.attr = arg_4
                arg_7 = getattr(arg_3, 'editable_boolean_result', arg_6)
                arg_0._ajax_editable_booleans[arg_4] = arg_7


def Func(arg_0, arg_1):
        """
        Handle an AJAX toggle_boolean request
        """
        try:
            arg_2 = int(arg_1.POST.get('item_id', None))
            arg_3 = str(arg_1.POST.get('attr', None))
        except:
            return HttpResponseBadRequest("Malformed request")

        if not arg_1.user.is_staff:
            logging.warning("Denied AJAX request by non-staff %s to toggle boolean %s for object #%s", arg_1.user,
                            arg_3, arg_2)
            return HttpResponseForbidden("You do not have permission to access this object")

        arg_0._collect_editable_booleans()

        if not arg_0._ajax_editable_booleans.has_key(arg_3):
            return HttpResponseBadRequest("not a valid attribute %s" % arg_3)

        try:
            arg_4 = arg_0.model._default_manager.get(pk=arg_2)
        except arg_0.model.DoesNotExist:
            return HttpResponseNotFound("Object does not exist")

        arg_5 = False

        if hasattr(arg_4, "user_can") and arg_4.user_can(arg_1.user, change_page=True):
            # Was added in c7f04dfb5d, but I've no idea what user_can is about.
            arg_5 = True
        else:
            arg_5 = arg_0.has_change_permission(arg_1, arg_4=arg_4)

        if not arg_5:
            logging.warning("Denied AJAX request by %s to toggle boolean %s for object %s", arg_1.user, arg_3, arg_2)
            return HttpResponseForbidden("You do not have permission to access this object")

        logging.info("Processing request by %s to toggle %s on %s", arg_1.user, arg_3, arg_4)

        try:
            arg_6 = arg_0._ajax_editable_booleans[arg_3](arg_0, arg_4)

            setattr(arg_4, arg_3, not getattr(arg_4, arg_3))
            arg_4.save()

            arg_0._refresh_changelist_caches() # ???: Perhaps better a post_save signal?

            # Construct html snippets to send back to client for status update
            arg_7 = arg_0._ajax_editable_booleans[arg_3](arg_0, arg_4)

        except Exception:#, e:
            logging.exception("Unhandled exception while toggling %s on %s", arg_3, arg_4)
            return HttpResponseServerError("Unable to toggle %s on %s" % (arg_3, arg_4))

        # Weed out unchanged cells to keep the updates small. This assumes
        # that the order a possible get_descendents() returns does not change
        # before and after toggling this attribute. Unlikely, but still...
        arg_8 = []
        for arg_9, arg_10 in zip(arg_6, arg_7):
            if arg_9 != arg_10:
                arg_8.append(arg_10)

        # TODO: Shorter: [ y for x,y in zip(a,b) if x!=y ]
        return HttpResponse(json.dumps(arg_8), mimetype="application/json")


def Func(arg_0, arg_1, arg_2, arg_3=2):
    """Add children recursively to a binary tree."""
    if arg_2 == 0:
        return
    for arg_4 in range(arg_3):
        arg_5 = arg_1+str(arg_4)
        arg_0.add_node(arg_5)
        arg_0.add_edge(arg_1,arg_5)
        Func(arg_0, arg_5, arg_2-1, arg_3)


def Func(arg_0, arg_1, arg_2):
    """Submit jobs via client where G describes the time dependencies."""
    arg_3 = {}
    for arg_4 in nx.topological_sort(arg_1):
        with arg_0.temp_flags(after=[ arg_3[arg_5] for arg_5 in arg_1.predecessors(arg_4) ]):
            arg_3[arg_4] = arg_0.apply(arg_2[arg_4])
    return arg_3


def Func(arg_0,arg_1,arg_2=0):
        """Set the currently active scheme.

        Names are by default compared in a case-insensitive way, but this can
        be changed by setting the parameter case_sensitive to true."""

        arg_3 = arg_0.keys()
        if arg_2:
            arg_4 = arg_3
            arg_5 = arg_1
        else:
            arg_4 = [s.lower() for s in arg_3]
            arg_5 = arg_1.lower()
        try:
            arg_6 = arg_4.index(arg_5)
        except ValueError:
            raise ValueError,'Unrecognized color scheme: ' + arg_1 + \
                  '\nValid schemes: '+str(arg_3).replace("'', ",'')
        else:
            arg_7 = arg_3[arg_6]
            arg_0.active_scheme_name = arg_7
            arg_0.active_colors = arg_0[arg_7].colors
            # Now allow using '' as an index for the current active scheme
            arg_0[''] = arg_0[arg_7]


def Func(arg_0):
    """Return the lib dir under the 'home' installation scheme"""
    if hasattr(sys, 'pypy_version_info'):
        arg_1 = 'site-packages'
    else:
        arg_1 = os.path.join('lib', 'python')
    return os.path.join(arg_0, arg_1)


def Func(arg_0, arg_1=None):
        """method to wait for a kernel to be ready"""
        arg_2 = time.time()
        arg_0.km.hb_channel.unpause()
        while True:
            arg_0.run_cell('1', False)
            if arg_0.km.hb_channel.is_beating():
                # heart failure was not the reason this returned
                break
            else:
                # heart failed
                if arg_1 is not None and (time.time() - arg_2) > arg_1:
                    return False
        return True


def Func(arg_0, arg_1):
        """ Returns a QTextCharFormat for token or None.
        """
        if arg_1 in arg_0._formats:
            return arg_0._formats[arg_1]

        if arg_0._style is None:
            arg_2 = arg_0.Func_from_document(arg_1, arg_0._document)
        else:
            arg_2 = arg_0.Func_from_style(arg_1, arg_0._style)

        arg_0._formats[arg_1] = arg_2
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """ Returns a QTextCharFormat for token by
        """
        arg_3, arg_4 = arg_0._formatter._format_lines([(arg_1, u'dummy')]).next()
        arg_0._document.setHtml(arg_4)
        return QtGui.QTextCursor(arg_0._document).charFormat()


def Func(arg_0):
    """
    Convert a path to its canonical, case-normalized, absolute version.

    """
    return os.path.normcase(os.path.realpath(os.path.expanduser(arg_0)))


def Func(arg_0, arg_1, arg_2):
    """Verify that namespace packages are valid"""
    assert_string_list(arg_0,arg_1,arg_2)
    for arg_3 in arg_2:
        if not arg_0.has_contents_for(arg_3):
            raise DistutilsSetupError(
                "Distribution contains no modules or packages for " +
                "namespace package %r" % arg_3
            )
        if '.' in arg_3:
            arg_4 = '.'.join(arg_3.split('.')[:-1])
            if arg_4 not in arg_2:
                distutils.log.warn(
                    "%r is declared as a package namespace, but %r is not:"
                    " please correct this in setup.py", arg_3, arg_4
                )


def Func(arg_0, arg_1, arg_2):
    """Verify that entry_points map is parseable"""
    try:
        pkg_resources.EntryPoint.parse_map(arg_2)
    except ValueError, e:
        raise DistutilsSetupError(e)


def Func(arg_0):
    """Determine if the input source ends in a blank.

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

    Parameters
    ----------
    src : string
      A single or multiline string.
    """
    if not arg_0: return False
    arg_1  = arg_0.splitlines()[-1]
    return (arg_1 == '') or arg_1.isspace()


def Func(arg_0):
    """Handle the `files = !ls` syntax."""
    arg_1 = _assign_system_re.match(arg_0)
    if arg_1 is not None:
        arg_2 = arg_1.group('cmd')
        arg_3 = arg_1.group('lhs')
        arg_4 = '%s = get_ipython().getoutput(%r)' % (arg_3, arg_2)
        return arg_4
    return arg_0


def Func(arg_0):
    """Handle the `a = %who` syntax."""
    arg_1 = _assign_magic_re.match(arg_0)
    if arg_1 is not None:
        arg_2 = arg_1.group('cmd')
        arg_3 = arg_1.group('lhs')
        arg_4 = '%s = get_ipython().magic(%r)' % (arg_3, arg_2)
        return arg_4
    return arg_0


def Func(arg_0):
    """Handle inputs that start with '>>> ' syntax."""

    if not arg_0 or arg_0.isspace():
        return arg_0
    arg_1 = _classic_prompt_re.match(arg_0)
    if arg_1:
        return arg_0[len(arg_1.group(0)):]
    else:
        return arg_0


def Func(arg_0, arg_1):
        """Push one or more lines of input.

        This stores the given lines and returns a status code indicating
        whether the code forms a complete Python block or not.

        Any exceptions generated in compilation are swallowed, but if an
        exception was produced, the method returns True.

        Parameters
        ----------
        lines : string
          One or more lines of Python input.

        Returns
        -------
        is_complete : boolean
          True if the current input source (the result of the current input
          plus prior inputs) forms a complete Python execution block.  Note that
          this value is also stored as a private attribute (``_is_complete``), so it
          can be queried at any time.
        """
        if arg_0.input_mode == 'cell':
            arg_0.reset()

        arg_0._store(arg_1)
        arg_2 = arg_0.source

        # Before calling _compile(), reset the code object to None so that if an
        # exception is raised in compilation, we don't mislead by having
        # inconsistent code/source attributes.
        arg_0.code, arg_0._is_complete = None, None

        # Honor termination lines properly
        if arg_2.rstrip().endswith('\\'):
            return False

        arg_0._update_indent(arg_1)
        try:
            arg_0.code = arg_0._compile(arg_2, symbol="exec")
        # Invalid syntax can produce any of a number of different errors from
        # inside the compiler, so we have to catch them all.  Syntax errors
        # immediately produce a 'ready' block, so the invalid Python can be
        # sent to the kernel for evaluation with possible ipython
        # special-syntax conversion.
        except (SyntaxError, OverflowError, ValueError, TypeError,
                MemoryError):
            arg_0._is_complete = True
        else:
            # Compilation didn't produce any exceptions (though it may not have
            # given a complete code object)
            arg_0._is_complete = arg_0.code is not None

        return arg_0._is_complete


def Func(arg_0):
        """Return whether a block of interactive input can accept more input.

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

        1. The input compiles to a complete statement.

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

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

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

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

        # With incomplete input, unconditionally accept more
        if not arg_0._is_complete:
            return True

        # If we already have complete input and we're flush left, the answer
        # depends.  In line mode, if there hasn't been any indentation,
        # that's it. If we've come back from some indentation, we need
        # the blank final line to finish.
        # In cell mode, we need to check how many blocks the input so far
        # compiles into, because if there's already more than one full
        # independent block of input, then the client has entered full
        # 'cell' mode and is feeding lines that each is complete.  In this
        # case we should then keep accepting. The Qt terminal-like console
        # does precisely this, to provide the convenience of terminal-like
        # input of single expressions, but allowing the user (with a
        # separate keystroke) to switch to 'cell' mode and type multiple
        # expressions in one shot.
        if arg_0.indent_spaces==0:
            if arg_0.input_mode=='line':
                if not arg_0._full_dedent:
                    return False
            else:
                try:
                    arg_1 = ast.parse(u''.join(arg_0._buffer))
                except Exception:
                    return False
                else:
                    if len(arg_1.body) == 1:
                        return False

        # When input is complete, then termination is marked by an extra blank
        # line at the end.
        arg_2 = arg_0.source.splitlines()[-1]
        return bool(arg_2 and not arg_2.isspace())


def Func(arg_0, arg_1):
        """Compute the new indentation level for a single line.

        Parameters
        ----------
        line : str
          A single new line of non-whitespace, non-comment Python input.

        Returns
        -------
        indent_spaces : int
          New value for the indent level (it may be equal to self.indent_spaces
        if indentation doesn't change.

        full_dedent : boolean
          Whether the new line causes a full flush-left dedent.
        """
        arg_2 = arg_0.indent_spaces
        arg_3 = arg_0._full_dedent

        arg_4 = num_ini_spaces(arg_1)
        if arg_4 < arg_2:
            arg_2 = arg_4
            if arg_2 <= 0:
                #print 'Full dedent in text',self.source # dbg
                arg_3 = True

        if arg_1.rstrip()[-1] == ':':
            arg_2 += 4
        elif dedent_re.match(arg_1):
            arg_2 -= 4
            if arg_2 <= 0:
                arg_3 = True

        # Safety
        if arg_2 < 0:
            arg_2 = 0
            #print 'safety' # dbg

        return arg_2, arg_3


def Func(arg_0, arg_1, arg_2=None, arg_3='source'):
        """Store one or more lines of input.

        If input lines are not newline-terminated, a newline is automatically
        appended."""

        if arg_2 is None:
            arg_2 = arg_0._buffer

        if arg_1.endswith('\n'):
            arg_2.append(arg_1)
        else:
            arg_2.append(arg_1+'\n')
        setattr(arg_0, arg_3, arg_0._set_source(arg_2))


def Func(arg_0):
        """Return input and raw source and perform a full reset.
        """
        arg_1 = arg_0.source
        arg_2 = arg_0.source_raw
        arg_0.reset()
        return arg_1, arg_2


def Func(arg_0, arg_1):
        """Process and translate a cell of input.
        """
        arg_0.reset()
        arg_0.push(arg_1)
        return arg_0.source_reset()


def Func(arg_0):
        """Initialize observer storage"""

        arg_0.registered_types = set() #set of types that are observed
        arg_0.registered_senders = set() #set of senders that are observed
        arg_0.observers = {}


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
        """Post notification to all registered observers.

        The registered callback will be called as::

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

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

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

        if(arg_1==None or arg_2==None):
            raise NotificationError(
                "Notification type and sender are required.")

        # If there are no registered observers for the type/sender pair
        if((arg_1 not in arg_0.registered_types and
                None not in arg_0.registered_types) or
            (arg_2 not in arg_0.registered_senders and
                None not in arg_0.registered_senders)):
            return

        for arg_5 in arg_0._observers_for_notification(arg_1, arg_2):
            arg_5(arg_1, arg_2, *arg_3, **arg_4)


def Func(arg_0, arg_1, arg_2):
        """Find all registered observers that should recieve notification"""

        arg_3 = (
                   (arg_1,arg_2),
                   (arg_1, None),
                   (None, arg_2),
                   (None,None)
               )

        arg_4 = set()
        for arg_5 in arg_3:
            arg_4.update(arg_0.observers.get(arg_5, set()))

        return arg_4


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Add a Func background job and start it in a separate thread.

        There are two types of jobs which can be created:

        1. Jobs based on expressions which can be passed to an eval() call.
        The expression must be given as a string.  For example:

          job_manager.Func('myfunc(x,y,z=1)'[,glob[,loc]])

        The given expression is passed to eval(), along with the optional
        global/local dicts provided.  If no dicts are given, they are
        extracted automatically from the caller's frame.

        A Python statement is NOT a valid eval() expression.  Basically, you
        can only use as an eval() argument something which can go on the right
        of an '=' sign and be assigned to a variable.

        For example,"print 'hello'" is not valid, but '2+3' is.

        2. Jobs given a function object, optionally passing additional
        positional arguments:

          job_manager.Func(myfunc, x, y)

        The function is called with the given arguments.

        If you need to pass keyword arguments to your function, you must
        supply them as a dict named kw:

          job_manager.Func(myfunc, x, y, kw=dict(z=1))

        The reason for this assymmetry is that the Func() method needs to
        maintain access to its own keywords, and this prevents name collisions
        between arguments to Func() and arguments to your own functions.

        In both cases, the result is stored in the job.result field of the
        background job object.

        You can set `daemon` attribute of the thread by giving the keyword
        argument `daemon`.

        Notes and caveats:

        1. All threads running share the same standard output.  Thus, if your
        background jobs generate output, it will come out on top of whatever
        you are currently writing.  For this reason, background jobs are best
        used with silent functions which simply return their output.

        2. Threads also all work within the same global namespace, and this
        system does not lock interactive variables.  So if you send job to the
        background which operates on a mutable object for a long time, and
        start modifying that same mutable object interactively (or in another
        backgrounded job), all sorts of bizarre behaviour will occur.

        3. If a background job is spending a lot of time inside a C extension
        module which does not release the Python Global Interpreter Lock
        (GIL), this will block the IPython prompt.  This is simply because the
        Python interpreter can only switch between threads at Python
        bytecodes.  While the execution is inside C code, the interpreter must
        simply wait unless the extension module releases the GIL.

        4. There is no way, due to limitations in the Python threads library,
        to kill a thread once it has started."""

        if callable(arg_1):
            arg_4  = arg_3.get('kw',{})
            arg_5 = BackgroundJobFunc(arg_1,*arg_2,**arg_4)
        elif isinstance(arg_1, basestring):
            if not arg_2:
                arg_6 = sys._getframe(1)
                arg_7, arg_8 = arg_6.f_globals, arg_6.f_locals
            elif len(arg_2)==1:
                arg_7 = arg_8 = arg_2[0]
            elif len(arg_2)==2:
                arg_7,arg_8 = arg_2
            else:
                raise ValueError(
                      'Expression jobs take at most 2 args (globals,locals)')
            arg_5 = BackgroundJobExpr(arg_1, arg_7, arg_8)
        else:
            raise TypeError('invalid args for Func job')

        if arg_3.get('daemon', False):
            arg_5.daemon = True
        arg_5.num = len(arg_0.all)+1 if arg_0.all else 0
        arg_0.running.append(arg_5)
        arg_0.all[arg_5.num] = arg_5
        print 'Starting job # %s in a separate thread.' % arg_5.num
        arg_5.start()
        return arg_5


def Func(arg_0,arg_1,arg_2):
        """Flush a given job group

        Return True if the group had any elements."""

        arg_3 = len(arg_1)
        if arg_3:
            arg_4 = {1:''}.setdefault(arg_3,'s')
            print 'Flushing %s %s job%s.' % (arg_3,arg_2,arg_4)
            arg_1[:] = []
            return True


def Func(arg_0, arg_1, arg_2=None):
        """Execute a shell command."""
        try:
            arg_0.channel = arg_0.ssh.get_transport().open_session()
        except paramiko.SSHException as e:
            arg_0.unknown("Create channel error: %s" % e)
        try:
            arg_0.channel.settimeout(arg_0.args.timeout if not arg_2 else arg_2)
        except socket.timeout as e:
            arg_0.unknown("Settimeout for channel error: %s" % e)
        try:
            arg_0.logger.debug("command: {}".format(arg_1))
            arg_0.channel.exec_command(arg_1)
        except paramiko.SSHException as e:
            arg_0.unknown("Execute command error: %s" % e)
        try:
            arg_0.stdin = arg_0.channel.makefile('wb', -1)
            arg_0.stderr = map(string.strip, arg_0.channel.makefile_stderr('rb', -1).readlines())
            arg_0.stdout = map(string.strip, arg_0.channel.makefile('rb', -1).readlines())
        except Exception as e:
            arg_0.unknown("Get result error: %s" % e)
        try:
            arg_0.status = arg_0.channel.recv_exit_status()
        except paramiko.SSHException as e:
            arg_0.unknown("Get return code error: %s" % e)
        else:
            if arg_0.status != 0:
                arg_0.unknown("Return code: %d , stderr: %s" % (arg_0.status, arg_0.errors))
            else:
                return arg_0.stdout
        finally:
            arg_0.logger.debug("Execute command finish.")


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Simple program that creates an temp S3 link."""
    if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
    	print 'Need to set environment variables for AWS access and create a Func bucket.'
    	exit()

    print create_temp_s3_link(arg_0, arg_1, arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Inserts a value in the ``ListVariable`` at an appropriate index.

        :param idx: The index before which to Func the new value.
        :param value: The value to Func.
        """

        arg_0._value.Func(arg_1, arg_2)
        arg_0._rebuild()


def Func(arg_0):
        """
        Retrieve a Func of the Environment.  Note that this is a shallow
        Func.
        """

        return arg_0.__class__(arg_0._data.Func(), arg_0._sensitive.Func(),
                              arg_0._cwd)


def Func(arg_0, arg_1, arg_2=arg_3.pathsep):
        """
        Declare an environment variable as a list-like special variable.
        This can be used even if the environment variable is not
        present.

        :param name: The name of the environment variable that should
                     be considered list-like.
        :param sep: The separator to be used.  Defaults to the value
                    of ``os.pathsep``.
        """

        arg_0._declare_special(arg_1, arg_2, ListVariable)


def Func(arg_0, arg_1):
        """
        Change the working directory that processes should be executed in.

        :param value: The new path to change to.  If relative, will be
                      interpreted relative to the current working
                      directory.
        """

        arg_0._Func = utils.canonicalize_path(arg_0._Func, arg_1)


def Func(arg_0, arg_1=None):
        """Swaps two cities in the route.

        :type state: TSPState
        """
        arg_1 = arg_0.state if arg_1 is None else arg_1
        arg_2 = arg_1
        arg_3 = random.randint(arg_0.locked_range, len(arg_2) - 1)
        arg_4 = random.randint(arg_0.locked_range, len(arg_2) - 1)
        arg_2[arg_3], arg_2[arg_4] = arg_2[arg_4], arg_2[arg_3]


def Func(arg_0, arg_1):
        """
        Poll ``self.stdout`` and return True if it is readable.

        :param float timeout: seconds to wait I/O
        :return: True if readable, else False
        :rtype: boolean
        """
        arg_2, arg_3, arg_4 = select.select([arg_0._stdout], [], [], arg_1)
        return bool(len(arg_2))


def Func(arg_0, arg_1=None):
        """create an empty record"""
        arg_2 = {}
        arg_1 = arg_0._keys if arg_1 is None else arg_1
        for arg_3 in arg_1:
            arg_2[arg_3] = None
        return arg_2


def Func(arg_0):
        """Ensure that an incorrect table doesn't exist

        If a bad (old) table does exist, return False
        """
        arg_1 = arg_0._db.execute("PRAGMA table_info(%s)"%arg_0.table)
        arg_2 = arg_1.fetchall()
        if not arg_2:
            # table does not exist
            return True
        arg_3 = {}
        arg_4 = []
        for arg_5 in arg_2:
            arg_4.append(arg_5[1])
            arg_3[arg_5[1]] = arg_5[2]
        if arg_0._keys != arg_4:
            # key mismatch
            arg_0.log.warn('keys mismatch')
            return False
        for arg_6 in arg_0._keys:
            if arg_3[arg_6] != arg_0._types[arg_6]:
                arg_0.log.warn(
                    'type mismatch: %s: %s != %s'%(arg_6,arg_3[arg_6],arg_0._types[arg_6])
                )
                return False
        return True


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """Read a config_file, check the validity with a JSON Schema as specs
        and get default values from default_file if asked.

        All parameters are optionnal.

        If there is no config_file defined, read the venv base
        dir and try to get config/app.yml.

        If no specs, don't validate anything.

        If no default_file, don't merge with default values."""

        arg_0._config_exists(arg_1)
        arg_0._specs_exists(arg_2)

        arg_0.loaded_config = anyconfig.load(arg_0.config_file, ac_Funcr='yaml')

        if arg_3 is not None:
            arg_0._merge_default(arg_3)

        if arg_0.specs is None:
            return arg_0.loaded_config

        arg_0._validate()

        return arg_0.loaded_config


def Func(arg_0, arg_1='', arg_2='', arg_3='', arg_4="", **arg_5):
    '''
    Output a Func tag.
    '''

    if not (arg_0.startswith('http') or arg_0.startswith('/')):
        # Handle additional reverse args.
        arg_6 = {}

        for arg_7, arg_8 in arg_5.items():
            if arg_7[:4] == "url_":
                arg_6[arg_7[4:]] = arg_8

        arg_0 = reverse(arg_0, arg_5=arg_6)
        if arg_4:
            arg_0 += '?' + arg_4

    return html.tag('a', arg_1 or arg_0, {
        'class': arg_2, 'target': arg_3, 'href': arg_0})


def Func(arg_0):
    '''
    Output a script tag to a js file.
    '''

    if not arg_0.startswith('http://') and not arg_0[:1] == '/':
        #add media_url for relative paths
        arg_0 = settings.STATIC_URL + arg_0

    return '<script type="text/javascript" src="{src}"></script>'.format(
        src=arg_0)


def Func(arg_0, arg_1='', arg_2='', arg_3=''):
    '''
    Image tag helper.
    '''

    if not arg_0.startswith('http://') and not arg_0[:1] == '/':
        #add media_url for relative paths
        arg_0 = settings.STATIC_URL + arg_0

    arg_4 = {
        'class': arg_2,
        'alt': arg_1,
        'style': arg_3,
        'src': arg_0
    }

    return html.tag('Func', '', arg_4)


def Func(arg_0, arg_1):
    """Multiply the arg with the value."""
    try:
        return valid_numeric(arg_0) * valid_numeric(arg_1)
    except (ValueError, TypeError):
        try:
            return arg_0 * arg_1
        except Exception:
            return ''


def Func(arg_0, arg_1):
    """Divide the arg by the value."""
    try:
        return valid_numeric(arg_0) / valid_numeric(arg_1)
    except (ValueError, TypeError):
        try:
            return arg_0 / arg_1
        except Exception:
            return ''


def Func(arg_0, arg_1=True):
    """
    Return the verbose name of a model.
    The obj argument can be either a Model instance, or a ModelForm instance.
    This allows to retrieve the verbose name of the model of a ModelForm
    easily, without adding extra context vars.
    """

    if isinstance(arg_0, ModelForm):
        arg_2 = arg_0._meta.model._meta.verbose_name
    elif isinstance(arg_0, Model):
        arg_2 = arg_0._meta.verbose_name
    else:
        raise Exception('Unhandled type: ' + type(arg_0))

    return arg_2.capitalize() if arg_1 else arg_2


def Func(arg_0, arg_1=None):
    """Split user input into initial whitespace, escape character, function part
    and the rest.
    """
    # We need to ensure that the rest of this routine deals only with unicode
    arg_2 = get_stream_enc(sys.stdin, 'utf-8')
    arg_0 = py3compat.cast_unicode(arg_0, arg_2)

    if arg_1 is None:
        arg_1 = line_split
    arg_3 = arg_1.match(arg_0)
    if not arg_3:
        # print "match failed for line '%s'" % line
        try:
            arg_4, arg_5 = arg_0.split(None,1)
        except ValueError:
            # print "split failed for line '%s'" % line
            arg_4, arg_5 = arg_0, u''
        arg_6 = re.match('^(\s*)(.*)',arg_0).groups()[0]
        arg_7 = ""
    else:
        arg_6, arg_7, arg_4, arg_5 = arg_3.groups()

    #print 'line:<%s>' % line # dbg
    #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg
    return arg_6, arg_7 or '', arg_4.strip(), arg_5.lstrip()


def Func(arg_0, arg_1, arg_2):
        """Remove an added builtin and re-set the original."""
        if arg_2 is BuiltinUndefined:
            del arg_3.__dict__[arg_1]
        else:
            arg_3.__dict__[arg_1] = arg_2


def Func(arg_0: arg_1) -> List[str]:
    """ Retrieve a list of characters and escape codes where each escape
        code uses only one index. The indexes will not match up with the
        indexes in the original string.
    """
    arg_2 = get_indices(arg_0)
    return [
        arg_2[arg_3] for arg_3 in sorted(arg_2, key=int)
    ]


def Func(arg_0, arg_1=('homepage', 'download')):
        """Yields all links with the given relations"""
        arg_1 = set(arg_1)

        for arg_2 in arg_0.parsed.findall(".//a"):
            if arg_2.get("rel") and arg_2.get("href"):
                arg_3 = set(arg_2.get("rel").split())
                # Determine the intersection between what rels were found and
                #   what rels were being looked for
                if arg_3 & arg_1:
                    arg_4 = arg_2.get("href")
                    arg_5 = arg_0.clean_link(
                        urllib_parse.urljoin(arg_0.base_url, arg_4)
                    )
                    yield Link(arg_5, arg_0, trusted=False)


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


def Func(arg_0=None):
    """The Func entry point to Coverage.

    This is installed as the script entry point.

    """
    if arg_0 is None:
        arg_0 = sys.argv[1:]
    try:
        arg_1 = time.clock()
        arg_2 = CoverageScript().command_line(arg_0)
        arg_3 = time.clock()
        if 0:
            print("time: %.3fs" % (arg_3 - arg_1))
    except ExceptionDuringRun:
        # An exception was caught while running the product code.  The
        # sys.exc_info() return tuple is packed into an ExceptionDuringRun
        # exception.
        arg_4, arg_5, arg_4 = sys.exc_info()
        traceback.print_exception(*arg_5.args)
        arg_2 = ERR
    except CoverageException:
        # A controlled error inside coverage.py: print the message to the user.
        arg_4, arg_5, arg_4 = sys.exc_info()
        print(arg_5)
        arg_2 = ERR
    except SystemExit:
        # The user called `sys.exit()`.  Exit with their argument, if any.
        arg_4, arg_5, arg_4 = sys.exc_info()
        if arg_5.args:
            arg_2 = arg_5.args[0]
        else:
            arg_2 = None
    return arg_2


def Func(arg_0, arg_1):
        """The bulk of the command line interface to Coverage.

        `argv` is the argument list to process.

        Returns 0 if all is well, 1 if something went wrong.

        """
        # Collect the command-line options.
        if not arg_1:
            arg_0.help_fn(topic='minimum_help')
            return OK

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

        arg_3.help_fn = arg_0.help_fn
        arg_5, arg_6, arg_7 = arg_3.parse_args(arg_1)
        if not arg_5:
            return ERR

        # Handle help and version.
        if arg_0.do_help(arg_6, arg_7, arg_3):
            return OK

        # Check for conflicts and problems in the options.
        if not arg_0.args_ok(arg_6, arg_7):
            return ERR

        # Listify the list options.
        arg_8 = unshell_list(arg_6.source)
        arg_9 = unshell_list(arg_6.omit)
        arg_10 = unshell_list(arg_6.include)
        arg_11 = unshell_list(arg_6.debug)

        # Do something.
        arg_0.coverage = arg_0.covpkg.coverage(
            data_suffix = arg_6.parallel_mode,
            cover_pylib = arg_6.pylib,
            timid = arg_6.timid,
            branch = arg_6.branch,
            config_file = arg_6.rcfile,
            arg_8 = arg_8,
            arg_9 = arg_9,
            arg_10 = arg_10,
            arg_11 = arg_11,
            )

        if 'debug' in arg_6.actions:
            return arg_0.do_debug(arg_7)

        if 'erase' in arg_6.actions or arg_6.erase_first:
            arg_0.coverage.erase()
        else:
            arg_0.coverage.load()

        if 'execute' in arg_6.actions:
            arg_0.do_execute(arg_6, arg_7)

        if 'combine' in arg_6.actions:
            arg_0.coverage.combine()
            arg_0.coverage.save()

        # Remaining actions are reporting, with some common options.
        arg_13 = dict(
            morfs = arg_7,
            ignore_errors = arg_6.ignore_errors,
            arg_9 = arg_9,
            arg_10 = arg_10,
            )

        if 'report' in arg_6.actions:
            arg_14 = arg_0.coverage.report(
                show_missing=arg_6.show_missing, **arg_13)
        if 'annotate' in arg_6.actions:
            arg_0.coverage.annotate(
                directory=arg_6.directory, **arg_13)
        if 'html' in arg_6.actions:
            arg_14 = arg_0.coverage.html_report(
                directory=arg_6.directory, title=arg_6.title,
                **arg_13)
        if 'xml' in arg_6.actions:
            arg_15 = arg_6.outfile
            arg_14 = arg_0.coverage.xml_report(arg_15=arg_15, **arg_13)

        if arg_6.fail_under is not None:
            if arg_14 >= arg_6.fail_under:
                return OK
            else:
                return FAIL_UNDER
        else:
            return OK


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """Display an error message, or the named topic."""
        assert arg_1 or arg_2 or arg_3
        if arg_1:
            print(arg_1)
            print("Use 'coverage Func' for Func.")
        elif arg_3:
            print(arg_3.format_Func().strip())
        else:
            arg_4 = HELP_TOPICS.get(arg_2, '').strip()
            if arg_4:
                print(arg_4 % arg_0.covpkg.__dict__)
            else:
                print("Don't know topic %r" % arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Deal with help requests.

        Return True if it handled the request, False if not.

        """
        # Handle help.
        if arg_1.help:
            if arg_0.classic:
                arg_0.help_fn(topic='help')
            else:
                arg_0.help_fn(arg_3=arg_3)
            return True

        if "help" in arg_1.actions:
            if arg_2:
                for arg_4 in arg_2:
                    arg_3 = CMDS.get(arg_4)
                    if arg_3:
                        arg_0.help_fn(arg_3=arg_3)
                    else:
                        arg_0.help_fn(topic=arg_4)
            else:
                arg_0.help_fn(topic='help')
            return True

        # Handle version.
        if arg_1.version:
            arg_0.help_fn(topic='version')
            return True

        return False


def Func(arg_0, arg_1):
        """Implementation of 'coverage debug'."""

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


def Func(arg_0, *arg_1, **arg_2):
        """
        Add directory or directories list to bundle

        :param exclusions: List of excluded paths

        :type path: str|unicode
        :type exclusions: list
        """
        arg_3 = arg_2.get('exclusions', None)
        for arg_4 in arg_1:
            arg_0.files.append(DirectoryPath(arg_4, arg_0, exclusions=arg_3))


def Func(arg_0, *arg_1):
        """
        Add custom path objects

        :type: path_object: static_bundle.paths.AbstractPath
        """
        for arg_2 in arg_1:
            arg_2.bundle = arg_0
            arg_0.files.append(arg_2)


def Func(arg_0, arg_1):
        """
        Add prepare handler to bundle

        :type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler
        """
        if not isinstance(arg_1, static_bundle.BUNDLE_ITERABLE_TYPES):
            arg_1 = [arg_1]
        if arg_0.prepare_handlers_chain is None:
            arg_0.prepare_handlers_chain = []
        for arg_3 in arg_1:
            arg_0.prepare_handlers_chain.append(arg_3)


def Func(arg_0):
        """
        Called when builder run collect files in builder group

        :rtype: list[static_bundle.files.StaticFileResult]
        """
        arg_1 = arg_0.collect_files()
        arg_2 = arg_0.Func_handlers_chain
        if arg_2 is None:
            # default handlers
            arg_2 = [
                LessCompilerPrepareHandler()
            ]
        for arg_3 in arg_2:
            arg_1 = arg_3.Func(arg_1, arg_0)
        return arg_1


def Func(arg_0):
        """Set the hook."""
        if arg_2.displayhook is not arg_0.hook:
            arg_0.old_hook = arg_2.displayhook
            arg_2.displayhook = arg_0.hook


def Func(arg_0, arg_1, *arg_2, **arg_3):
    """decorator to log unhandled exceptions raised in a method.

    For use wrapping on_recv callbacks, so that exceptions
    do not cause the stream to be closed.
    """
    try:
        return arg_0(arg_1, *arg_2, **arg_3)
    except Exception:
        arg_1.log.error("Uncaught exception in %r" % arg_0, exc_info=True)


def Func(arg_0):
    """boolean check for whether a string is a zmq url"""
    if '://' not in arg_0:
        return False
    arg_1, arg_2 = arg_0.split('://', 1)
    if arg_1.lower() not in ['tcp','pgm','epgm','ipc','inproc']:
        return False
    return True


def Func(arg_0):
    """validate a url for zeromq"""
    if not isinstance(arg_0, basestring):
        raise TypeError("url must be a string, not %r"%type(arg_0))
    arg_0 = arg_0.lower()

    arg_1 = arg_0.split('://')
    assert len(arg_1) == 2, 'Invalid url: %r'%arg_0
    arg_2, arg_3 = arg_1
    assert arg_2 in ['tcp','pgm','epgm','ipc','inproc'], "Invalid protocol: %r"%arg_2

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

    if arg_2 == 'tcp':
        arg_5 = arg_3.split(':')
        assert len(arg_5) == 2, 'Invalid url: %r'%arg_0
        arg_3,arg_6 = arg_5
        try:
            arg_7 = int(arg_6)
        except ValueError:
            raise AssertionError("Invalid port %r in url: %r"%(arg_7, arg_0))

        assert arg_3 == '*' or arg_4.match(arg_3) is not None, 'Invalid url: %r'%arg_0

    else:
        # only validate tcp urls currently
        pass

    return True


def Func(arg_0):
    """validate a potentially nested collection of urls."""
    if isinstance(arg_0, basestring):
        arg_1 = arg_0
        return validate_url(arg_1)
    elif isinstance(arg_0, dict):
        arg_0 = arg_0.itervalues()

    for arg_2 in arg_0:
        Func(arg_2)


def Func(arg_0):
    """Selects and return n random ports that are available."""
    arg_1 = []
    for arg_2 in xrange(arg_0):
        arg_3 = socket.socket()
        arg_3.bind(('', 0))
        while arg_3.getsockname()[1] in _random_ports:
            arg_3.close()
            arg_3 = socket.socket()
            arg_3.bind(('', 0))
        arg_1.append(arg_3)
    for arg_2, arg_3 in enumerate(arg_1):
        arg_4 = arg_3.getsockname()[1]
        arg_3.close()
        arg_1[arg_2] = arg_4
        _random_ports.add(arg_4)
    return arg_1


def Func(arg_0):
        """Get the number of files in the folder."""
        arg_0.__results = []
        arg_0.__dirs = []
        arg_0.__files = []
        arg_0.__ftp = arg_0.connect()
        arg_0.__ftp.dir(arg_0.args.path, arg_0.__results.append)
        arg_0.logger.debug("dir results: {}".format(arg_0.__results))
        arg_0.quit()

        arg_5 = arg_0.ok

        for arg_6 in arg_0.__results:
            if "<DIR>" in arg_6:
                arg_0.__dirs.append(str(arg_6.split()[3]))
            else:
                arg_0.__files.append(str(arg_6.split()[2]))

        arg_0.__result = len(arg_0.__files)
        arg_0.logger.debug("result: {}".format(arg_0.__result))

        # Compare the vlaue.
        if arg_0.__result > arg_0.args.warning:
            arg_5 = arg_0.warning
        if arg_0.__result > arg_0.args.critical:
            arg_5 = arg_0.critical

        # Output
        arg_0.shortoutput = "Found {0} files in {1}.".format(arg_0.__result,
                                                            arg_0.args.path)
        [arg_0.longoutput.append(arg_9)
         for arg_9 in arg_0.__results if arg_0.__results]
        arg_0.perfdata.append("{path}={result};{warn};{crit};0;".format(
            crit=arg_0.args.critical,
            warn=arg_0.args.warning,
            result=arg_0.__result,
            path=arg_0.args.path))

        arg_0.logger.debug("Return status and output.")
        arg_5(arg_0.output())


def Func(arg_0, arg_1):
        """
        Register the contents as JSON
        """
        arg_2 = json.loads(arg_1)
        arg_0.last_data_timestamp = \
                datetime.datetime.utcnow().replace(microsecond=0).isoformat()
        try:
            for arg_4 in arg_2:
                # prepare the sensor entry container
                arg_0.data[arg_4[arg_0.id_key]] = {}
                # add the mandatory entries
                arg_0.data[arg_4[arg_0.id_key]][arg_0.id_key] = \
                                            arg_4[arg_0.id_key]
                arg_0.data[arg_4[arg_0.id_key]][arg_0.value_key] = \
                                            arg_4[arg_0.value_key]
                # add the optional well known entries if provided
                if arg_0.unit_key in arg_4:
                    arg_0.data[arg_4[arg_0.id_key]][arg_0.unit_key] = \
                                            arg_4[arg_0.unit_key]
                if arg_0.threshold_key in arg_4:
                    arg_0.data[arg_4[arg_0.id_key]][arg_0.threshold_key] = \
                                            arg_4[arg_0.threshold_key]
                # add any further entries found
                for arg_9 in arg_0.other_keys:
                    if arg_9 in arg_4:
                        arg_0.data[arg_4[arg_0.id_key]][arg_9] = arg_4[arg_9]
                # add the custom sensor time
                if arg_0.sensor_time_key in arg_4:
                    arg_0.data[arg_4[arg_0.sensor_time_key]][arg_0.sensor_time_key] = \
                                            arg_4[arg_0.sensor_time_key]
                # last: add the time the data was received (overwriting any
                # not properly defined timestamp that was already there)
                arg_0.data[arg_4[arg_0.id_key]][arg_0.time_key] = \
                                            arg_0.last_data_timestamp
        except KeyError as e:
            print("The main key was not found on the serial input line: " + \
                    str(e))
        except ValueError as e:
            print("No valid JSON string received. Waiting for the next turn.")
            print("The error was: " + str(e))


def Func(arg_0):
        """
        Translate the data with the translation table
        """
        arg_1 = {}
        for arg_2 in arg_0.data:
            arg_3 = {}
            for arg_4 in arg_0.data[arg_2]:
                arg_3[arg_0.translation_keys[arg_4]] = arg_0.data[arg_2][arg_4]
            arg_1[arg_2] = arg_3
        return arg_1


def Func(arg_0, arg_1='b', arg_2=None, arg_3=True, **arg_4):
    """Turn a function into a Func remote function.

    This method can be used for map:

    In [1]: @Func(view, block=True)
       ...: def func(a):
       ...:    pass
    """

    def Func_function(arg_5):
        return ParallelFunction(arg_0, arg_5, arg_1=arg_1, arg_2=arg_2, arg_3=arg_3, **arg_4)
    return Func_function


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


def Func(arg_0, arg_1, arg_2={}, arg_3=None):
        """
        Issues a POST request against the API, allows for multipart data uploads

        :param url: a string, the url you are requesting
        :param params: a dict, the key-value of all the parameters needed
                       in the request
        :param files: a list, the list of tuples of files

        :returns: a dict parsed of the JSON response
        """
        arg_2.update({'api_key': arg_0.api_key})
        try:
            arg_4 = requests.Func(arg_0.host + arg_1, data=arg_2, arg_3=arg_3)
            return arg_0.json_parse(arg_4.content)
        except RequestException as e:
            return arg_0.json_parse(e.args)


def Func(arg_0, arg_1=10):
        """Get the last n items in readline history."""
        arg_2 = arg_0.shell.readline.get_current_history_length() + 1
        arg_3 = max(arg_2-arg_1, 1)
        arg_4 = arg_0.shell.readline.get_history_item
        return [arg_4(arg_5) for arg_5 in range(arg_3, arg_2)]


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


def Func(arg_0):
        """Restore the state of the sys module."""
        try:
            for arg_1, arg_2 in arg_0._orig_sys_module_state.iteritems():
                setattr(arg_3, arg_1, arg_2)
        except AttributeError:
            pass
        # Reset what what done in self.init_sys_modules
        if arg_0._orig_sys_modules_main_mod is not None:
            arg_3.modules[arg_0._orig_sys_modules_main_name] = arg_0._orig_sys_modules_main_mod


def Func(arg_0, arg_1):
        """Register a function for calling after code execution.
        """
        if not callable(arg_1):
            raise ValueError('argument %s must be callable' % arg_1)
        arg_0._post_execute[arg_1] = True


def Func(arg_0,arg_1=None):
        """Return a new 'main' module object for user code execution.
        """
        arg_2 = arg_0._user_main_module
        init_fakemod_dict(arg_2,arg_1)
        return arg_2


def Func(arg_0,arg_1,arg_2):
        """Cache a main module's namespace.

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

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

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

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

          fname : str
            Filename associated with the namespace.

        Examples
        --------

        In [10]: import IPython

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

        In [12]: IPython.__file__ in _ip._main_ns_cache
        Out[12]: True
        """
        arg_0._main_ns_cache[arg_4.path.abspath(arg_2)] = arg_1.copy()


def Func(arg_0):
        """Initialize all user-visible namespaces to their minimum defaults.

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

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

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

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

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

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

        arg_1['_sh'] = shadowns

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

        # Store myself as the public api!!!
        arg_1['get_ipython'] = arg_0.get_ipython

        arg_1['exit'] = arg_0.exiter
        arg_1['quit'] = arg_0.exiter

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

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

        # Finally, update the real user's namespace
        arg_0.user_ns.update(arg_1)


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

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


def Func(arg_0, arg_1=True):
        """Clear all internal namespaces, and attempt to release references to
        user objects.

        If new_session is True, a new history session will be opened.
        """
        # Clear histories
        arg_0.history_manager.Func(arg_1)
        # Reset counter used to index all histories
        if arg_1:
            arg_0.execution_count = 1

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

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

        arg_0.user_ns_hidden.clear()

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

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

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

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


def Func(arg_0, arg_1=None):
        """Clear selective variables from internal namespaces based on a
        specified regular expression.

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