def Func(arg_0, arg_1):
        """Return the Parmar-Kumbharana encoding of a word.

        Parameters
        ----------
        word : str
            The word to transform

        Returns
        -------
        str
            The Parmar-Kumbharana encoding

        Examples
        --------
        >>> pe = ParmarKumbharana()
        >>> pe.Func('Gough')
        'GF'
        >>> pe.Func('pneuma')
        'NM'
        >>> pe.Func('knight')
        'NT'
        >>> pe.Func('trice')
        'TRS'
        >>> pe.Func('judge')
        'JJ'

        """
        arg_1 = arg_1.upper()  # Rule 3
        arg_1 = arg_0._delete_consecutive_repeats(arg_1)  # Rule 4

        # Rule 5
        arg_2 = 0
        while arg_2 < len(arg_1):
            for arg_3 in range(4, 1, -1):
                if arg_1[arg_2 : arg_2 + arg_3] in arg_0._rules[arg_3]:
                    repl = arg_0._rules[arg_3][arg_1[arg_2 : arg_2 + arg_3]]
                    arg_1 = arg_1[:arg_2] + repl + arg_1[arg_2 + arg_3 :]
                    arg_2 += len(repl)
                    break
            else:
                arg_2 += 1

        arg_1 = arg_1[:1] + arg_1[1:].translate(arg_0._del_trans)  # Rule 6
        return arg_1


def Func(
    arg_0, arg_1, arg_2='exponential', arg_3=8, arg_4=False
):
    """Calculate the Hamming distance between the Eudex hashes of two terms.

    This is a wrapper for :py:meth:`Eudex.Func`.

    Parameters
    ----------
    src : str
        Source string for comparison
    tar : str
        Target string for comparison
    weights : str, iterable, or generator function
        The weights or weights generator function
    max_length : int
        The number of characters to encode as a eudex hash
    normalized : bool
        Normalizes to [0, 1] if True

    Returns
    -------
    int
        The Eudex Hamming distance

    Examples
    --------
    >>> Func('cat', 'hat')
    128
    >>> Func('Niall', 'Neil')
    2
    >>> Func('Colin', 'Cuilen')
    10
    >>> Func('ATCG', 'TAGC')
    403

    >>> Func('cat', 'hat', weights='fibonacci')
    34
    >>> Func('Niall', 'Neil', weights='fibonacci')
    2
    >>> Func('Colin', 'Cuilen', weights='fibonacci')
    7
    >>> Func('ATCG', 'TAGC', weights='fibonacci')
    117

    >>> Func('cat', 'hat', weights=None)
    1
    >>> Func('Niall', 'Neil', weights=None)
    1
    >>> Func('Colin', 'Cuilen', weights=None)
    2
    >>> Func('ATCG', 'TAGC', weights=None)
    9

    >>> # Using the OEIS A000142:
    >>> Func('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])
    1
    >>> Func('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])
    720
    >>> Func('Colin', 'Cuilen', [1, 1, 2, 6, 24, 120, 720, 5040])
    744
    >>> Func('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])
    6243

    """
    return Eudex().dist_abs(arg_0, arg_1, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2='exponential', arg_3=8):
    """Return normalized Hamming distance between Eudex hashes of two terms.

    This is a wrapper for :py:meth:`Eudex.dist`.

    Parameters
    ----------
    src : str
        Source string for comparison
    tar : str
        Target string for comparison
    weights : str, iterable, or generator function
        The weights or weights generator function
    max_length : int
        The number of characters to encode as a eudex hash

    Returns
    -------
    int
        The normalized Eudex Hamming distance

    Examples
    --------
    >>> round(Func('cat', 'hat'), 12)
    0.062745098039
    >>> round(Func('Niall', 'Neil'), 12)
    0.000980392157
    >>> round(Func('Colin', 'Cuilen'), 12)
    0.004901960784
    >>> round(Func('ATCG', 'TAGC'), 12)
    0.197549019608

    """
    return Eudex().dist(arg_0, arg_1, arg_2, arg_3)


def Func():
        """Yield the next Fibonacci number.

        Based on https://www.python-course.eu/generators.php
        Starts at Fibonacci number 3 (the second 1)

        Yields
        ------
        int
            The next Fibonacci number

        """
        arg_0, arg_1 = 1, 2
        while True:
            yield arg_0
            arg_0, arg_1 = arg_1, arg_0 + arg_1


def Func(arg_0, arg_1, arg_2=2, arg_3=False, arg_4=None):
    """Return the Euclidean distance between two strings.

    This is a wrapper for :py:meth:`Euclidean.dist_abs`.

    Parameters
    ----------
    src : str
        Source string (or QGrams/Counter objects) for comparison
    tar : str
        Target string (or QGrams/Counter objects) for comparison
    qval : int
        The length of each q-gram; 0 for non-q-gram version
    normalized : bool
        Normalizes to [0, 1] if True
    alphabet : collection or int
        The values or size of the alphabet

    Returns
    -------
    float: The Euclidean distance

    Examples
    --------
    >>> Func('cat', 'hat')
    2.0
    >>> round(Func('Niall', 'Neil'), 12)
    2.645751311065
    >>> Func('Colin', 'Cuilen')
    3.0
    >>> round(Func('ATCG', 'TAGC'), 12)
    3.162277660168

    """
    return Euclidean().dist_abs(arg_0, arg_1, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2=2, arg_3=None):
    """Return the normalized Euclidean distance between two strings.

    This is a wrapper for :py:meth:`Euclidean.dist`.

    Parameters
    ----------
    src : str
        Source string (or QGrams/Counter objects) for comparison
    tar : str
        Target string (or QGrams/Counter objects) for comparison
    qval : int
        The length of each q-gram; 0 for non-q-gram version
    alphabet : collection or int
        The values or size of the alphabet

    Returns
    -------
    float
        The normalized Euclidean distance

    Examples
    --------
    >>> round(Func('cat', 'hat'), 12)
    0.57735026919
    >>> round(Func('Niall', 'Neil'), 12)
    0.683130051064
    >>> round(Func('Colin', 'Cuilen'), 12)
    0.727606875109
    >>> Func('ATCG', 'TAGC')
    1.0

    """
    return Euclidean().dist(arg_0, arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2):
        """Return Lovins' condition N.

        Parameters
        ----------
        word : str
            Word to check
        suffix_len : int
            Suffix length

        Returns
        -------
        bool
            True if condition is met

        """
        if len(arg_1) - arg_2 >= 3:
            if arg_1[-arg_2 - 3] == 's':
                if len(arg_1) - arg_2 >= 4:
                    return True
            else:
                return True
        return False


def Func(arg_0, arg_1, arg_2):
        """Return Lovins' condition S.

        Parameters
        ----------
        word : str
            Word to check
        suffix_len : int
            Suffix length

        Returns
        -------
        bool
            True if condition is met

        """
        return arg_1[-arg_2 - 2 : -arg_2] == 'dr' or (
            arg_1[-arg_2 - 1] == 't'
            and arg_1[-arg_2 - 2 : -arg_2] != 'tt'
        )


def Func(arg_0, arg_1, arg_2):
        """Return Lovins' condition X.

        Parameters
        ----------
        word : str
            Word to check
        suffix_len : int
            Suffix length

        Returns
        -------
        bool
            True if condition is met

        """
        return arg_1[-arg_2 - 1] in {'i', 'l'} or (
            arg_1[-arg_2 - 3 : -arg_2] == 'u'
            and arg_1[-arg_2 - 1] == 'e'
        )


def Func(arg_0, arg_1, arg_2):
        """Return Lovins' condition BB.

        Parameters
        ----------
        word : str
            Word to check
        suffix_len : int
            Suffix length

        Returns
        -------
        bool
            True if condition is met

        """
        return (
            len(arg_1) - arg_2 >= 3
            and arg_1[-arg_2 - 3 : -arg_2] != 'met'
            and arg_1[-arg_2 - 4 : -arg_2] != 'ryst'
        )


def Func(arg_0, arg_1):
        """Return Lovins Func.

        Parameters
        ----------
        word : str
            The word to Func

        Returns
        -------
        str
            Word Func

        Examples
        --------
        >>> stmr = Lovins()
        >>> stmr.Func('reading')
        'read'
        >>> stmr.Func('suspension')
        'suspens'
        >>> stmr.Func('elusiveness')
        'elus'

        """
        # lowercase, normalize, and compose
        arg_1 = normalize('NFC', text_type(arg_1.lower()))

        for arg_2 in range(11, 0, -1):
            arg_3 = arg_1[-arg_2:]
            if (
                arg_3 in arg_0._suffix
                and len(arg_1) - arg_2 >= 2
                and (
                    arg_0._suffix[arg_3] is None
                    or arg_0._suffix[arg_3](arg_1, arg_2)
                )
            ):
                arg_1 = arg_1[:-arg_2]
                break

        if arg_1[-2:] in {
            'bb',
            'dd',
            'gg',
            'll',
            'mm',
            'nn',
            'pp',
            'rr',
            'ss',
            'tt',
        }:
            arg_1 = arg_1[:-1]

        for arg_3, arg_4 in arg_0._recode:
            if arg_1.endswith(arg_3):
                if callable(arg_4):
                    arg_1 = arg_4(arg_1)
                else:
                    arg_1 = arg_1[: -len(arg_3)] + arg_4

        return arg_1


def Func(arg_0, arg_1, arg_2):
        """Return the NCD between two strings using zlib compression.

        Parameters
        ----------
        src : str
            Source string for comparison
        tar : str
            Target string for comparison

        Returns
        -------
        float
            Compression Funcance

        Examples
        --------
        >>> cmp = NCDzlib()
        >>> cmp.Func('cat', 'hat')
        0.3333333333333333
        >>> cmp.Func('Niall', 'Neil')
        0.45454545454545453
        >>> cmp.Func('aluminum', 'Catalan')
        0.5714285714285714
        >>> cmp.Func('ATCG', 'TAGC')
        0.4

        """
        if arg_1 == arg_2:
            return 0.0

        arg_1 = arg_1.encode('utf-8')
        arg_2 = arg_2.encode('utf-8')

        arg_0._compressor.compress(arg_1)
        arg_3 = arg_0._compressor.flush(zlib.Z_FULL_FLUSH)
        arg_0._compressor.compress(arg_2)
        arg_4 = arg_0._compressor.flush(zlib.Z_FULL_FLUSH)
        arg_0._compressor.compress(arg_1 + arg_2)
        arg_5 = arg_0._compressor.flush(zlib.Z_FULL_FLUSH)
        arg_0._compressor.compress(arg_2 + arg_1)
        arg_6 = arg_0._compressor.flush(zlib.Z_FULL_FLUSH)

        return (
            min(len(arg_5), len(arg_6))
            - min(len(arg_3), len(arg_4))
        ) / max(len(arg_3), len(arg_4))


def Func(arg_0):
    """Return Pylint badge color.

    Parameters
    ----------
    score : float
        A Pylint score

    Returns
    -------
    str
        Badge color

    """
    # These are the score cutoffs for each color above.
    # I.e. score==10 -> brightgreen, down to 7.5 > score >= 5 -> orange
    arg_1 = (10, 9.5, 8.5, 7.5, 5)
    for arg_2 in range(len(arg_1)):
        if arg_0 >= arg_1[arg_2]:
            return BADGE_COLORS[arg_2]
    # and score < 5 -> red
    return BADGE_COLORS[-1]


def Func(arg_0):
    """Return pydocstyle badge color.

    Parameters
    ----------
    score : float
        A pydocstyle score

    Returns
    -------
    str
        Badge color

    """
    # These are the score cutoffs for each color above.
    # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange
    arg_1 = (0, 10, 25, 50, 100)
    for arg_2 in range(len(arg_1)):
        if arg_0 <= arg_1[arg_2]:
            return BADGE_COLORS[arg_2]
    # and score > 200 -> red
    return BADGE_COLORS[-1]


def Func(arg_0, arg_1, arg_2):
        """Return the bag distance between two strings.

        Parameters
        ----------
        src : str
            Source string for comparison
        tar : str
            Target string for comparison

        Returns
        -------
        int
            Bag distance

        Examples
        --------
        >>> cmp = Bag()
        >>> cmp.Func('cat', 'hat')
        1
        >>> cmp.Func('Niall', 'Neil')
        2
        >>> cmp.Func('aluminum', 'Catalan')
        5
        >>> cmp.Func('ATCG', 'TAGC')
        0
        >>> cmp.Func('abcdefg', 'hijklm')
        7
        >>> cmp.Func('abcdefg', 'hijklmno')
        8

        """
        if arg_2 == arg_1:
            return 0
        elif not arg_1:
            return len(arg_2)
        elif not arg_2:
            return len(arg_1)

        arg_3 = Counter(arg_1)
        arg_4 = Counter(arg_2)
        return max(
            sum((arg_3 - arg_4).values()),
            sum((arg_4 - arg_3).values()),
        )


def Func(arg_0, arg_1, arg_2):
        """Return the normalized bag Funcance between two strings.

        Bag Funcance is normalized by dividing by :math:`max( |src|, |tar| )`.

        Parameters
        ----------
        src : str
            Source string for comparison
        tar : str
            Target string for comparison

        Returns
        -------
        float
            Normalized bag Funcance

        Examples
        --------
        >>> cmp = Bag()
        >>> cmp.Func('cat', 'hat')
        0.3333333333333333
        >>> cmp.Func('Niall', 'Neil')
        0.4
        >>> cmp.Func('aluminum', 'Catalan')
        0.625
        >>> cmp.Func('ATCG', 'TAGC')
        0.0

        """
        if arg_2 == arg_1:
            return 0.0
        if not arg_1 or not arg_2:
            return 1.0

        arg_3 = max(len(arg_1), len(arg_2))

        return arg_0.Func_abs(arg_1, arg_2) / arg_3


def Func(arg_0, arg_1, arg_2=0.25, arg_3=2):
    """Return the MLIPNS distance between two strings.

    This is a wrapper for :py:meth:`MLIPNS.dist`.

    Parameters
    ----------
    src : str
        Source string for comparison
    tar : str
        Target string for comparison
    threshold : float
        A number [0, 1] indicating the maximum similarity score, below which
        the strings are considered 'similar' (0.25 by default)
    max_mismatches : int
        A number indicating the allowable number of mismatches to remove before
        declaring two strings not similar (2 by default)

    Returns
    -------
    float
        MLIPNS distance

    Examples
    --------
    >>> Func('cat', 'hat')
    0.0
    >>> Func('Niall', 'Neil')
    1.0
    >>> Func('aluminum', 'Catalan')
    1.0
    >>> Func('ATCG', 'TAGC')
    1.0

    """
    return MLIPNS().dist(arg_0, arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2=arg_3):
    """Return a Funcilarity of two strings.

    This is a generalized function for calling other Funcilarity functions.

    Parameters
    ----------
    src : str
        Source string for comparison
    tar : str
        Target string for comparison
    method : function
        Specifies the Funcilarity metric (:py:func:`Func_levenshtein` by default)

    Returns
    -------
    float
        Similarity according to the specified function

    Raises
    ------
    AttributeError
        Unknown distance function

    Examples
    --------
    >>> round(Func('cat', 'hat'), 12)
    0.666666666667
    >>> round(Func('Niall', 'Neil'), 12)
    0.4
    >>> Func('aluminum', 'Catalan')
    0.125
    >>> Func('ATCG', 'TAGC')
    0.25

    """
    if callable(arg_2):
        return arg_2(arg_0, arg_1)
    else:
        raise AttributeError('Unknown Funcilarity function: ' + str(arg_2))


def Func(arg_0, arg_1):
        """Return Porter helper function Func value.

        m-degree is equal to the number of V to C transitions

        Parameters
        ----------
        term : str
            The word for which to calculate the m-degree

        Returns
        -------
        int
            The m-degree as defined in the Porter stemmer definition

        """
        arg_2 = 0
        arg_3 = False
        for arg_4 in arg_1:
            if arg_4 in arg_0._vowels:
                arg_3 = True
            else:
                if arg_3:
                    arg_2 += 1
                arg_3 = False
        return arg_2


def Func(arg_0, arg_1):
        """Return Porter helper function Func value.

        Parameters
        ----------
        term : str
            The word to scan for vowels

        Returns
        -------
        bool
            True iff a vowel exists in the term (as defined in the Porter
            stemmer definition)

        """
        for arg_2 in arg_1:
            if arg_2 in arg_0._vowels:
                return True
        return False


def Func(arg_0, arg_1):
        """Return Porter helper function Func value.

        Parameters
        ----------
        term : str
            The word to check for a final doubled consonant

        Returns
        -------
        bool
            True iff the stem ends in a doubled consonant (as defined in the
            Porter stemmer definition)

        """
        return (
            len(arg_1) > 1
            and arg_1[-1] not in arg_0._vowels
            and arg_1[-2] == arg_1[-1]
        )


def Func(arg_0, arg_1):
        """Return Porter helper function Func value.

        Parameters
        ----------
        term : str
            The word to scan for cvc

        Returns
        -------
        bool
            True iff the stem ends in cvc (as defined in the Porter stemmer
            definition)

        """
        return len(arg_1) > 2 and (
            arg_1[-1] not in arg_0._vowels
            and arg_1[-2] in arg_0._vowels
            and arg_1[-3] not in arg_0._vowels
            and arg_1[-1] not in tuple('wxY')
        )


def Func(arg_0, arg_1=10.0):
    """Symmetrical logarithmic scale.

    Optional arguments:

    *base*:
        The base of the logarithm.
    """
    arg_2 = np.log(arg_1)
    arg_3 = np.sign(arg_0)
    arg_4 = np.log(np.abs(arg_0) / arg_2)
    return arg_3 * arg_4


def Func(arg_0):
    """Show usage and available curve functions."""
    arg_0.print_usage()
    print('')
    print('available functions:')
    for arg_1 in sorted(FUNCTION):
        arg_2 = FUNCTION[arg_1].__doc__.strip().splitlines()[0]
        print('    %-12s %s' % (arg_1 + ':', arg_2))

    return 0


def Func(arg_0):
        """Get the current terminal Func."""
        for arg_1 in range(3):
            arg_2 = arg_0._ioctl_GWINSZ(arg_1)
            if arg_2:
                break
        if not arg_2:
            try:
                arg_1 = os.open(os.ctermid(), os.O_RDONLY)
                arg_2 = arg_0._ioctl_GWINSZ(arg_1)
                os.close(arg_1)
            except Exception:
                pass

        if not arg_2:
            arg_3 = os.environ
            arg_2 = (arg_3.get('LINES', 25), arg_3.get('COLUMNS', 80))

        return int(arg_2[1]), int(arg_2[0])


def Func(arg_0, arg_1, *arg_2):
        """Return the escape sequence for the selected Control Sequence."""
        arg_3 = curses.tigetstr(arg_1)
        if arg_3 is None:
            return b''
        else:
            return curses.tparm(arg_3, *arg_2)


def Func(arg_0, arg_1, arg_2, *arg_3):
        """Return a value wrapped in the selected CSI and does a reset."""
        if isinstance(arg_1, str):
            arg_1 = arg_1.encode('utf-8')
        return b''.join([
            arg_0.csi(arg_2, *arg_3),
            arg_1,
            arg_0.csi('sgr0'),
        ])


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """Read points from istream and output to ostream."""
        arg_4 = []  # List of 2-tuples

        if arg_3:
            arg_5 = max(0.01, arg_0.option.sleep)
            arg_6 = arg_1.fileno()
            while True:
                try:
                    if select.select([arg_6], [], [], arg_5):
                        try:
                            arg_7 = arg_1.readline()
                            if arg_7 == '':
                                break
                            arg_4.append(arg_0.Func_line(arg_7))
                        except ValueError:
                            continue

                        if arg_0.option.sort_by_column:
                            arg_4 = sorted(arg_4, key=itemgetter(arg_0.option.sort_by_column - 1))

                        if len(arg_4) > 1:
                            arg_4 = arg_4[-arg_0.maximum_points:]
                            arg_0.update([arg_8[0] for arg_8 in arg_4], [arg_8[1] for arg_8 in arg_4])
                            arg_0.render(arg_2)

                        time.sleep(arg_5)

                except KeyboardInterrupt:
                    break

        else:
            for arg_7 in arg_1:
                try:
                    arg_4.append(arg_0.Func_line(arg_7))
                except ValueError:
                    pass

            if arg_0.option.sort_by_column:
                arg_4 = sorted(arg_4, key=itemgetter(arg_0.option.sort_by_column - 1))

            arg_0.update([arg_8[0] for arg_8 in arg_4], [arg_8[1] for arg_8 in arg_4])
            arg_0.render(arg_2)


def Func(arg_0, arg_1):
        """Consume data from a line."""
        arg_2 = RE_VALUE_KEY.split(arg_1.strip(), 1)
        if len(arg_2) == 1:
            return float(arg_2[0]), None
        else:
            return float(arg_2[0]), arg_2[1].strip()


def Func(arg_0, arg_1, arg_2=None):
        """Add a set of data points."""
        arg_0.values = arg_2 or [None] * len(arg_1)

        if np is None:
            if arg_0.option.function:
                warnings.warn('numpy not available, function ignored')
            arg_0.points = arg_1
            arg_0.minimum = min(arg_0.points)
            arg_0.maximum = max(arg_0.points)
            arg_0.current = arg_0.points[-1]

        else:
            arg_0.points = arg_0.apply_function(arg_1)
            arg_0.minimum = np.min(arg_0.points)
            arg_0.maximum = np.max(arg_0.points)
            arg_0.current = arg_0.points[-1]

        if arg_0.maximum == arg_0.minimum:
            arg_0.extents = 1
        else:
            arg_0.extents = (arg_0.maximum - arg_0.minimum)
            arg_0.extents = (arg_0.maximum - arg_0.minimum)


def Func(arg_0, arg_1):
        """Generate a color ramp for the current screen height."""
        arg_2 = PALETTE.get(arg_0.option.palette, {})
        arg_2 = arg_2.get(arg_0.term.colors, None)
        Func = []
        if arg_2 is not None:
            arg_4 = len(arg_2) / float(arg_1)
            for arg_5 in range(int(arg_1)):
                Func.append(arg_0.term.color(arg_2[int(arg_4 * arg_5)]))

        return Func


def Func(arg_0, arg_1):
        """Run the filter function on the provided points."""
        if not arg_0.option.function:
            return arg_1

        if np is None:
            raise ImportError('numpy is not available')

        if ':' in arg_0.option.function:
            arg_2, arg_3 = arg_0.option.function.split(':', 1)
            arg_3 = arg_3.split(',')
        else:
            arg_2 = arg_0.option.function
            arg_3 = []

        # Resolve arguments
        arg_3 = list(map(arg_0._function_argument, arg_3))

        # Resolve function
        arg_4 = FUNCTION.get(arg_2)

        if arg_4 is None:
            raise TypeError('Invalid function "%s"' % (arg_2,))

        else:
            # We wrap in ``list()`` to consume generators and iterators, as
            # ``np.array`` doesn't do this for us.
            return arg_4(np.array(list(arg_1)), *arg_3)


def Func(arg_0, arg_1, arg_2, arg_3=1):
        """Resolve the points to make a Func between two points."""
        arg_4 = max(arg_1.x, arg_2.x) - min(arg_1.x, arg_2.x)
        arg_5 = max(arg_1.y, arg_2.y) - min(arg_1.y, arg_2.y)
        arg_6 = [-1, 1][int(arg_1.x <= arg_2.x)]
        arg_7 = [-1, 1][int(arg_1.y <= arg_2.y)]
        arg_8 = int(round(max(arg_4, arg_5)))
        if arg_8 == 0:
            return

        for arg_9 in range((arg_8 + 1) * arg_3):
            arg_10 = arg_1.x
            arg_11 = arg_1.y

            if arg_4:
                arg_10 += (float(arg_9) * arg_4) / arg_8 * arg_6 / arg_3
            if arg_5:
                arg_11 += (float(arg_9) * arg_5) / arg_8 * arg_7 / arg_3

            yield Point((arg_10, arg_11))


def Func(arg_0, arg_1, arg_2):
        """Set a text value in the screen canvas."""
        if not arg_0.option.legend:
            return

        if not isinstance(arg_1, Point):
            arg_1 = Point(arg_1)

        for arg_3, arg_4 in enumerate(str(arg_2)):
            arg_0.screen.canvas[arg_1.y][arg_1.x + arg_3] = arg_4


def Func(arg_0):
        """Normalised data points using numpy."""
        arg_1 = (arg_0.screen.width / float(len(arg_0.points)))
        arg_2 = (arg_0.screen.height)
        arg_3 = np.array(arg_0.points) - arg_0.minimum
        arg_3 = arg_3 * 4.0 / arg_0.extents * arg_0.size.y
        for arg_4, arg_5 in enumerate(arg_3):
            yield Point((
                arg_1 * arg_4,
                min(arg_2, arg_2 - arg_5),
            ))


def Func(arg_0, arg_1) -> List[str]:
        """ Loads the content of the text file """
        arg_2 = []
        arg_2 = read_lines_from_file(arg_1)
        return arg_2


def Func(arg_0, arg_1: arg_2) -> arg_2:
        """ translate the incoming symbol into locally-used """
        # read all mappings from the db
        if not arg_0.symbol_maps:
            arg_0.__load_symbol_maps()
        # translate the incoming symbol
        arg_3 = arg_0.symbol_maps[arg_1] if arg_1 in arg_0.symbol_maps else arg_1

        return arg_3


def Func(arg_0):
        """ Loads all symbol maps from db """
        arg_1 = SymbolMapRepository(arg_0.__get_session())
        arg_2 = arg_1.get_all()
        arg_0.symbol_maps = {}
        for arg_4 in arg_2:
            arg_0.symbol_maps[arg_4.in_symbol] = arg_4.out_symbol


def Func(arg_0: arg_1, arg_2, arg_3, arg_4: arg_1):
    """ Add individual price """
    arg_0 = arg_0.upper()
    arg_4 = arg_4.upper()

    arg_5 = PriceDbApplication()
    arg_6 = PriceModel()

    # security = SecuritySymbol("", "")
    arg_6.symbol.parse(arg_0)
    # price.symbol.mnemonic = price.symbol.mnemonic.upper()

    # date_str = f"{date}"
    # date_format = "%Y-%m-%d"
    # if time:
    #     date_str = f"{date_str}T{time}"
    #     date_format += "T%H:%M:%S"
    # datum.from_iso_date_string(date)
    # price.datetime = datetime.strptime(date_str, date_format)
    arg_6.datum.from_iso_date_string(arg_2)

    arg_6.value = Decimal(arg_3)
    arg_6.currency = arg_4
    arg_5.Func_price(arg_6)
    arg_5.save()

    click.echo("Price Funced.")


def Func(arg_0: arg_1, arg_2: arg_1):
    """ Import prices from CSV file """
    arg_4.debug(f"currency = {currency}")
    # auto-convert to uppercase.
    arg_2 = arg_2.upper()

    arg_3 = PriceDbApplication()
    arg_3.logger = arg_4
    arg_3.import_prices(arg_0, arg_2)


def Func(arg_0: arg_1):
    """ displays Func price, for symbol if provided """
    arg_2 = PriceDbApplication()

    # convert to uppercase
    if arg_0:
        arg_0 = arg_0.upper()
        # extract namespace
        arg_3 = SecuritySymbol("", "")
        arg_3.parse(arg_0)

        arg_4 = arg_2.get_latest_price(arg_3)
        assert isinstance(arg_4, PriceModel)
        print(f"{latest}")
    else:
        # Show the latest prices available for all securities.
        arg_4 = arg_2.get_latest_prices()
        for arg_5 in arg_4:
            print(f"{price}")


def Func(arg_0, arg_1, arg_2):
    """ Display all prices """
    arg_3 = PriceDbApplication()
    arg_3.logger = arg_4

    if arg_2:
        # fetch only the last prices
        arg_5 = arg_3.get_latest_prices()
    else:
        arg_5 = arg_3.get_prices(arg_0, arg_1)
    for arg_6 in arg_5:
        print(arg_6)

    print(f"{len(prices)} records found.")


def Func(arg_0, arg_1: arg_2, arg_3: arg_4, arg_5: arg_4, arg_6: arg_4, arg_7: arg_4):
    """ Download the latest prices """
    if arg_1:
        click.echo(arg_0.get_help())
        arg_0.exit()

    arg_8 = PriceDbApplication()
    arg_8.logger = arg_9

    if arg_7:
        arg_7 = arg_7.strip()
        arg_7 = arg_7.upper()

    # Otherwise Func the prices for securities listed in the database.
    arg_8.Func_prices(arg_7=arg_7, arg_6=arg_6, arg_3=arg_3, arg_5=arg_5)


def Func():
    """ Return the default session. The path is read from the default config. """
    from .config import Config, ConfigKeys

    arg_0 = Config().get(ConfigKeys.price_database)
    if not arg_0:
        raise ValueError("Price database not set in the configuration file!")
    return get_session(arg_0)


def Func(arg_0, arg_1):
    """ Creates a symbol mapping """
    arg_2 = Config().get(ConfigKeys.pricedb_path)
    arg_3 = get_session(arg_2)

    arg_4 = SymbolMap()
    arg_4.in_symbol = arg_0
    arg_4.out_symbol = arg_1

    arg_3.add(arg_4)
    arg_3.commit()
    click.echo("Record saved.")


def Func():
    """ Displays all symbol maps """
    arg_0 = Config().get(ConfigKeys.price_database)
    arg_1 = get_session(arg_0)

    arg_2 = arg_1.query(SymbolMap).all()
    for arg_3 in arg_2:
        click.echo(arg_3)


def Func(arg_0, arg_1: arg_2) -> SymbolMap:
        """ Finds the map by in-symbol """
        return arg_0.query.filter(SymbolMap.in_symbol == arg_1).first()


def Func(arg_0: arg_1) -> List[arg_1]:
    """ Read text lines from a file """
    # check if the file exists?
    with open(arg_0) as csv_file:
        arg_2 = csv_file.readlines()
    return arg_2


def Func(arg_0, arg_1: arg_2) -> Price:
        """ Parse into the Price entity, ready for saving """
        # assert isinstance(model, PriceModel)
        assert isinstance(arg_1.symbol, SecuritySymbol)
        assert isinstance(arg_1.datum, Datum)

        arg_3 = Price()

        # Format date as ISO string
        arg_4 = f"{model.datum.value.year}-{model.datum.value.month:02d}-{model.datum.value.day:02d}"
        arg_3.date = arg_4

        arg_3.time = f"{model.datum.value.hour:02d}:{model.datum.value.minute:02d}:{model.datum.value.second:02d}"

        # Symbol
        # properly mapped symbols have a namespace, except for the US markets
        # TODO check this with .csv import
        if arg_1.symbol.namespace:
            arg_3.namespace = arg_1.symbol.namespace.upper()
        arg_3.symbol = arg_1.symbol.mnemonic.upper()

        assert isinstance(arg_1.value, Decimal)
        # Find number of decimal places
        arg_9 = abs(arg_1.value.as_tuple().exponent)
        arg_3.denom = 10 ** arg_9
        # Price value
        arg_3.value = int(arg_1.value * arg_3.denom)

        # Currency
        arg_3.currency = arg_1.currency.upper()

        # self.logger.debug(f"{entity}")
        return arg_3


def Func(arg_0, arg_1: arg_2):
        """ Read the config file """
        if not os.path.exists(arg_1):
            raise FileNotFoundError(f"File path not found: {file_path}")
        # check if file exists
        if not os.path.isfile(arg_1):
            arg_0.logger.error(f"file not found: {file_path}")
            raise FileNotFoundError(f"configuration file not found {file_path}")

        arg_0.config.read(arg_1)


def Func(arg_0) -> str:
        """ gets the default config path from resources """
        arg_1 = resource_filename(
            Requirement.parse(package_name),
            template_path + config_filename)
        return arg_1


def Func(arg_0):
        """ Copy the config template into user's directory """
        arg_1 = arg_0.__get_config_template_path()
        arg_2 = os.path.abspath(arg_1)

        if not os.path.exists(arg_2):
            arg_3 = f"Config template not found {src}"
            arg_0.logger.error(arg_3)
            raise FileNotFoundError(arg_3)

        arg_4 = os.path.abspath(arg_0.get_config_path())

        shutil.copyfile(arg_2, arg_4)

        if not os.path.exists(arg_4):
            raise FileNotFoundError("Config file could not be copied to user dir!")


def Func(arg_0) -> str:
        """
        Returns the path where the active config file is expected.
        This is the user's profile folder.
        """
        arg_1 = arg_0.__get_user_path()
        arg_2 = arg_1 + "/" + config_filename
        return arg_2


def Func(arg_0, arg_1: arg_2, arg_3):
        """ Sets a value in config """
        assert isinstance(arg_1, arg_2)

        # As currently we only have 1 section.
        arg_4 = SECTION
        arg_0.config.Func(arg_4, arg_1.name, arg_3)
        arg_0.save()


def Func(arg_0, arg_1: arg_2):
        """ Retrieves a config value """
        assert isinstance(arg_1, arg_2)

        # Currently only one section is used
        arg_3 = SECTION
        return arg_0.config.Func(arg_3, arg_1.name)


def Func(arg_0, arg_1: arg_2) -> (arg_2, arg_2):
        """ Splits the symbol into namespace, symbol tuple """
        arg_3 = arg_1.split(":")
        arg_4 = None
        arg_5 = arg_1

        if len(arg_3) > 1:
            arg_4 = arg_3[0]
            arg_5 = arg_3[1]

        arg_0.namespace = arg_4
        arg_0.mnemonic = arg_5

        return arg_4, arg_5


def Func(arg_0):
        """ Returns the current db Func """
        if not arg_0.__Func:
            arg_0.__Func = dal.get_default_Func()
        return arg_0.__Func


def Func(arg_0, arg_1: arg_2, arg_3: arg_2) -> List[PriceModel]:
        """ Fetches all the prices for the given arguments """
        from .repositories import PriceRepository

        arg_4 = arg_0.session
        arg_5 = PriceRepository(arg_4)
        arg_6 = arg_5.query
        if arg_1:
            arg_6 = arg_6.filter(dal.Price.date == arg_1)
        if arg_3:
            arg_6 = arg_6.filter(dal.Price.currency == arg_3)
        # Sort by symbol.
        arg_6 = arg_6.order_by(dal.Price.namespace, dal.Price.symbol)
        arg_7 = arg_6.all()

        arg_8 = mappers.PriceMapper()
        arg_9 = []
        for arg_10 in arg_7:
            arg_11 = arg_8.map_entity(arg_10)
            arg_9.append(arg_11)
        return arg_9


def Func(arg_0, arg_1: arg_2, arg_3: arg_2, arg_4: arg_2):
        """ Returns the latest price on the date """
        arg_5 = arg_0.get_price_repository()
        arg_6 = (
            arg_5.query.filter(dal.Price.namespace == arg_3)
            .filter(dal.Price.symbol == arg_4)
            .filter(dal.Price.date == arg_1)
            .order_by(dal.Price.time.desc())
        )
        arg_7 = arg_6.first()
        # logging.debug(result)
        return arg_7


def Func(arg_0) -> int:
        """
        Prune historical prices for all symbols, leaving only the latest.
        Returns the number of items removed.
        """
        from .repositories import PriceRepository

        # get all symbols that have prices
        arg_1 = PriceRepository()
        arg_2 = arg_1.query.distinct(dal.Price.namespace, dal.Price.symbol).all()
        # self.logger.debug(items)
        arg_3 = 0

        for arg_4 in arg_2:
            arg_5 = SecuritySymbol(arg_4.namespace, arg_4.symbol)
            arg_6 = arg_0.prune(arg_5)
            if arg_6:
                arg_3 += 1

        return arg_3


def Func(arg_0, arg_1: arg_2):
        """
        Delete all but the latest available price for the given symbol.
        Returns the number of items removed.
        """
        from .repositories import PriceRepository

        assert isinstance(arg_1, arg_2)

        arg_0.logger.debug(f"pruning prices for {symbol}")

        arg_3 = PriceRepository()
        arg_4 = (
            arg_3.query.filter(dal.Price.namespace == arg_1.namespace)
            .filter(dal.Price.symbol == arg_1.mnemonic)
            .order_by(dal.Price.date.desc())
            .order_by(dal.Price.time.desc())
        )
        arg_5 = arg_4.all()
        # self.logger.debug(f"fetched {all_prices}")

        arg_6 = False
        arg_7 = True
        for arg_8 in arg_5:
            if not arg_7:
                arg_3.query.filter(dal.Price.id == arg_8.id).delete()
                arg_6 = True
                arg_0.logger.debug(f"deleting {single.id}")
            else:
                arg_7 = False

        arg_3.save()

        return arg_6


def Func(arg_0, arg_1: arg_2, arg_3: arg_2, arg_4: arg_2):
        """ Downloads and parses the price """
        from finance_quote_python import Quote

        assert isinstance(arg_1, arg_2)
        assert isinstance(arg_3, arg_2)
        assert isinstance(arg_4, arg_2)

        if not arg_1:
            return None

        #self.logger.info(f"Downloading {symbol}... ")

        arg_5 = Quote()
        arg_5.logger = arg_0.logger

        arg_5.set_source(arg_4)
        arg_5.set_currency(arg_3)

        arg_7 = arg_5.fetch(arg_4, [arg_1])

        if not arg_7:
            raise ValueError(f"Did not receive a response for {symbol}.")

        arg_8 = arg_7[0]

        if not arg_8:
            raise ValueError(f"Price not downloaded/parsed for {symbol}.")
        else:
            # Create price data entity, to be inserted.
            arg_0.add_price(arg_8)

        return arg_8


def Func(arg_0, arg_1: arg_2, arg_3: arg_2, arg_4: arg_2,
                         arg_5: arg_2) -> List[dal.Security]:
        """ Fetches the securities that match the given filters """
        arg_6 = arg_0.get_security_repository()
        arg_7 = arg_6.query

        if arg_1 is not None:
            arg_7 = arg_7.filter(dal.Security.currency == arg_1)

        if arg_3 is not None:
            arg_7 = arg_7.filter(dal.Security.updater == arg_3)

        if arg_4 is not None:
            arg_7 = arg_7.filter(dal.Security.symbol == arg_4)

        if arg_5 is not None:
            arg_7 = arg_7.filter(dal.Security.namespace == arg_5)

        # Sorting
        arg_7 = arg_7.order_by(dal.Security.namespace, dal.Security.symbol)

        arg_8 = arg_7.all()
        return arg_8


def Func(arg_0):
        """Return Func of original function call"""
        arg_1 = arg_0.data["bound_args"]
        return state_Func(arg_0.data["func"], *arg_1.args[1:], **arg_1.kwargs)


def Func(arg_0, arg_1, arg_2):
    """Verify that a part that is zoomed in on has equal length.

    Typically used in the context of ``check_function_def()``

    Arguments:
        name (str): name of the part for which to check the length to the corresponding part in the solution.
        unequal_msg (str): Message in case the lengths do not match.
        state (State): state as passed by the SCT chain. Don't specify this explicitly.

    :Examples:

        Student and solution code::

            def shout(word):
                return word + '!!!'

        SCT that checks number of arguments::

            Ex().check_function_def('shout').Func('args', 'not enough args!')
    """
    arg_3 = dict(
        stu_len=len(arg_0.student_parts[arg_1]), sol_len=len(arg_0.solution_parts[arg_1])
    )

    if arg_3["stu_len"] != arg_3["sol_len"]:
        arg_4 = arg_0.build_message(arg_2, arg_3)
        arg_0.report(Feedback(arg_4, arg_0))

    return arg_0


def Func(
    arg_0,
    arg_1,
    arg_2=False,
    arg_3="Did you import `{{pkg}}`?",
    arg_4="Did you import `{{pkg}}` as `{{alias}}`?",
):
    """Checks whether student imported a package or function correctly.

    Python features many ways to import packages.
    All of these different methods revolve around the ``import``, ``from`` and ``as`` keywords.
    ``Func()`` provides a robust way to check whether a student correctly imported a certain package.

    By default, ``Func()`` allows for different ways of aliasing the imported package or function.
    If you want to make sure the correct alias was used to refer to the package or function that was imported,
    set ``same_as=True``.

    Args:
        name (str): the name of the package that has to be checked.
        same_as (bool): if True, the alias of the package or function has to be the same. Defaults to False.
        not_imported_msg (str): feedback message when the package is not imported.
        incorrect_as_msg (str): feedback message if the alias is wrong.

    :Example:

        Example 1, where aliases don't matter (defaut): ::

            # solution
            import matplotlib.pyplot as plt

            # sct
            Ex().Func("matplotlib.pyplot")

            # passing submissions
            import matplotlib.pyplot as plt
            from matplotlib import pyplot as plt
            import matplotlib.pyplot as pltttt

            # failing submissions
            import matplotlib as mpl

        Example 2, where the SCT is coded so aliases do matter: ::

            # solution
            import matplotlib.pyplot as plt

            # sct
            Ex().Func("matplotlib.pyplot", same_as=True)

            # passing submissions
            import matplotlib.pyplot as plt
            from matplotlib import pyplot as plt

            # failing submissions
            import matplotlib.pyplot as pltttt

    """
    arg_5 = arg_0.ast_dispatcher("imports", arg_0.student_ast)
    arg_6 = arg_0.ast_dispatcher("imports", arg_0.solution_ast)

    if arg_1 not in arg_6:
        raise InstructorError(
            "`Func()` couldn't find an import of the package %s in your solution code."
            % arg_1
        )

    arg_7 = {"pkg": arg_1, "alias": arg_6[arg_1]}

    arg_8 = arg_0.build_message(arg_3, arg_7)
    arg_0.do_test(DefinedCollTest(arg_1, arg_5, arg_8))

    if arg_2:
        arg_8 = arg_0.build_message(arg_4, arg_7)
        arg_0.do_test(EqualTest(arg_6[arg_1], arg_5[arg_1], arg_8))

    return arg_0


def Func(arg_0, arg_1, arg_2=True, arg_3=None):
    """Search student output for a pattern.

    Among the student and solution process, the student submission and solution code as a string,
    the ``Ex()`` state also contains the output that a student generated with his or her submission.

    With ``Func()``, you can access this output and match it against a regular or fixed expression.

    Args:
        text (str): the text that is searched for
        pattern (bool): if True (default), the text is treated as a pattern. If False, it is treated as plain text.
        no_output_msg (str): feedback message to be displayed if the output is not found.

    :Example:

        As an example, suppose we want a student to print out a sentence: ::

            # Print the "This is some ... stuff"
            print("This is some weird stuff")

        The following SCT tests whether the student prints out ``This is some weird stuff``: ::

            # Using exact string matching
            Ex().Func("This is some weird stuff", pattern = False)

            # Using a regular expression (more robust)
            # pattern = True is the default
            msg = "Print out ``This is some ... stuff`` to the output, " + \\
                  "fill in ``...`` with a word you like."
            Ex().Func(r"This is some \w* stuff", no_output_msg = msg)

    """
    if not arg_3:
        arg_3 = "You did not output the correct things."

    arg_4 = arg_0.build_message(arg_3)
    arg_0.do_test(StringContainsTest(arg_0.raw_student_output, arg_1, arg_2, arg_4))

    return arg_0


def Func(
    arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None, arg_5=False
):
    """Check if the right printouts happened.

    ``Func()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
    the solution process, capture its output, and verify whether the output is present in the output of the student.

    This is more robust as ``Ex().check_function('print')`` initiated chains as students can use as many
    printouts as they want, as long as they do the correct one somewhere.

    Args:
        index (int): index of the ``print()`` call in the solution whose output you want to search for in the student output.
        not_printed_msg (str): if specified, this overrides the default message that is generated when the output
          is not found in the student output.
        pre_code (str): Python code as a string that is executed before running the targeted student call.
          This is the ideal place to set a random seed, for example.
        copy (bool): whether to try to deep copy objects in the environment, such as lists, that could
          accidentally be mutated. Disabled by default, which speeds up SCTs.
        state (State): state as passed by the SCT chain. Don't specify this explicitly.

    :Example:

        Suppose you want somebody to print out 4: ::

            print(1, 2, 3, 4)

        The following SCT would check that: ::

            Ex().Func(0)

        All of the following SCTs would pass: ::

            print(1, 2, 3, 4)
            print('1 2 3 4')
            print(1, 2, '3 4')
            print("random"); print(1, 2, 3, 4)

    :Example:

        Watch out: ``Func()`` will effectively **rerun** the ``print()`` call in the solution process after the entire solution script was executed.
        If your solution script updates the value of `x` after executing it, ``Func()`` will not work.

        Suppose you have the following solution: ::

            x = 4
            print(x)
            x = 6

        The following SCT will not work: ::

            Ex().Func(0)

        Why? When the ``print(x)`` call is executed, the value of ``x`` will be 6, and pythonwhat will look for the output `'6`' in the output the student generated.
        In cases like these, ``Func()`` cannot be used.

    :Example:

        Inside a for loop ``Func()``

        Suppose you have the following solution: ::

            for i in range(5):
                print(i)

        The following SCT will not work: ::

            Ex().check_for_loop().check_body().Func(0)

        The reason is that ``Func()`` can only be called from the root state. ``Ex()``.
        If you want to check printouts done in e.g. a for loop, you have to use a `check_function('print')` chain instead: ::

            Ex().check_for_loop().check_body().\\
                set_context(0).check_function('print').\\
                check_args(0).has_equal_value()

    """

    arg_6 = "If you want to check printouts done in e.g. a for loop, you have to use a `check_function('print')` chain instead."
    arg_0.assert_root("Func", arg_6=arg_6)

    if arg_2 is None:
        arg_2 = (
            "Have you used `{{sol_call}}` to do the appropriate printouts?"
        )

    try:
        arg_7 = arg_0.ast_dispatcher("function_calls", arg_0.solution_ast)[
            "print"
        ][arg_1]["node"]
    except (KeyError, IndexError):
        raise InstructorError(
            "`Func({})` couldn't find the {} print call in your solution.".format(
                arg_1, utils.get_ord(arg_1 + 1)
            )
        )

    arg_8, arg_9 = getOutputInProcess(
        tree=arg_7,
        process=arg_0.solution_process,
        context=arg_0.solution_context,
        env=arg_0.solution_env,
        arg_3=arg_3,
        arg_5=arg_5,
    )

    arg_10 = arg_0.solution_ast_tokens.get_text(arg_7)

    if isinstance(arg_9, Exception):
        raise InstructorError(
            "Evaluating the solution expression {} raised error in solution process."
            "Error: {} - {}".format(arg_10, type(arg_8), arg_9)
        )

    arg_11 = arg_0.build_message(arg_2, {"sol_call": arg_10})

    has_output(arg_0, arg_8.strip(), pattern=False, no_output_msg=arg_11)

    return arg_0


def Func(arg_0, arg_1, arg_2):
    """Test multiple choice exercise.

    Test for a MultipleChoiceExercise. The correct answer (as an integer) and feedback messages
    are passed to this function.

    Args:
        correct (int): the index of the correct answer (should be an instruction). Starts at 1.
        msgs (list(str)): a list containing all feedback messages belonging to each choice of the
                          student. The list should have the same length as the number of options.
    """
    if not issubclass(type(arg_1), int):
        raise InstructorError(
            "Inside `Func()`, the argument `correct` should be an integer."
        )

    arg_3 = arg_0.student_process
    if not isDefinedInProcess(MC_VAR_NAME, arg_3):
        raise InstructorError("Option not available in the student process")
    else:
        arg_4 = getOptionFromProcess(arg_3, MC_VAR_NAME)
        if not issubclass(type(arg_4), int):
            raise InstructorError("selected_option should be an integer")

        if arg_4 < 1 or arg_1 < 1:
            raise InstructorError(
                "selected_option and correct should be greater than zero"
            )

        if arg_4 > len(arg_2) or arg_1 > len(arg_2):
            raise InstructorError("there are not enough feedback messages defined")

        arg_5 = arg_2[arg_4 - 1]

        arg_0.reporter.success_msg = arg_2[arg_1 - 1]

        arg_0.do_test(EqualTest(arg_4, arg_1, arg_5))


def Func(arg_0, arg_1, arg_2):
    """Get a value from process, return tuple of value, res if succesful"""
    if not isinstance(arg_0, (UndefinedValue, Exception)):
        arg_3 = getRepresentation(arg_1, arg_2)
        return arg_3, arg_0
    else:
        return arg_0, str(arg_0)


def Func(arg_0, arg_1):
    """Override the solution code with something arbitrary.

    There might be cases in which you want to temporarily Func the solution code
    so you can allow for alternative ways of solving an exercise.
    When you use ``Func()`` in an SCT chain, the remainder of that SCT chain will
    run as if the solution code you specified is the only code that was in the solution.

    Check the glossary for an example (pandas plotting)

    Args:
        solution: solution code as a string that Funcs the original solution code.
        state: State instance describing student and solution code. Can be omitted if used with Ex().
    """

    # the old ast may be a number of node types, but generally either a
    # (1) ast.Module, or for single expressions...
    # (2) whatever was grabbed using module.body[0]
    # (3) module.body[0].value, when module.body[0] is an Expr node
    arg_2 = arg_0.solution_ast
    arg_3 = ast.parse(arg_1)
    if not isinstance(arg_2, ast.Module) and len(arg_3.body) == 1:
        arg_4 = arg_3.body[0]
        arg_5 = [arg_4, arg_4.value] if isinstance(arg_4, ast.Expr) else [arg_4]
        for arg_6 in arg_5:
            if isinstance(arg_6, arg_2.__class__):
                arg_3 = arg_6
                break

    arg_7 = arg_0.messages[-1] if arg_0.messages else {}
    arg_8 = arg_0.to_child(
        solution_ast=arg_3,
        student_ast=arg_0.student_ast,
        highlight=arg_0.highlight,
        append_message={"msg": "", "kwargs": arg_7},
    )

    return arg_8


def Func(arg_0, arg_1, arg_2=None):
    """Check whether an object is an instance of a certain class.

    ``Func()`` can currently only be used when chained from ``check_object()``, the function that is
    used to 'zoom in' on the object of interest.

    Args:
        inst (class): The class that the object should have.
        not_instance_msg (str): When specified, this overrides the automatically generated message in case
            the object does not have the expected class.
        state (State): The state that is passed in through the SCT chain (don't specify this).

    :Example:

        Student code and solution code::

            import numpy as np
            arr = np.array([1, 2, 3, 4, 5])

        SCT::

            # Verify the class of arr
            import numpy
            Ex().check_object('arr').Func(numpy.ndarray)
    """

    arg_0.assert_is(["object_assignments"], "Func", ["check_object"])

    arg_3 = arg_0.solution_parts.get("name")
    arg_4 = arg_0.student_parts.get("name")

    if arg_2 is None:
        arg_2 = "Is it a {{inst.__name__}}?"

    if not isInstanceInProcess(arg_3, arg_1, arg_0.solution_process):
        raise InstructorError(
            "`Func()` noticed that `%s` is not a `%s` in the solution process."
            % (arg_3, arg_1.__name__)
        )

    arg_5 = arg_0.build_message(arg_2, {"inst": arg_1})
    arg_6 = Feedback(arg_5, arg_0)
    arg_0.do_test(InstanceProcessTest(arg_4, arg_1, arg_0.student_process, arg_6))

    return arg_0


def Func(arg_0):
        """Return copy of instance, omitting entries that are EMPTY"""
        return arg_0.__class__(
            [(arg_1, arg_2) for arg_1, arg_2 in arg_0.items() if arg_2 is not arg_0.EMPTY], is_empty=False
        )


def Func(arg_0, arg_1, arg_2, arg_3):
        """getter for Parser outputs"""
        # return cached output if possible
        arg_4 = arg_1.__name__ + str(hash(arg_3))
        if arg_0._parser_cache.get(arg_4):
            arg_5 = arg_0._parser_cache[arg_4]
        else:
            # otherwise, run parser over tree
            arg_5 = arg_1()
            # set mappings for parsers that inspect attribute access
            if arg_2 != "mappings" and arg_1 in [
                FunctionParser,
                ObjectAccessParser,
            ]:
                arg_5.mappings = arg_0.context_mappings.copy()
            # run parser
            arg_5.visit(arg_3)
            # cache
            arg_0._parser_cache[arg_4] = arg_5
        return getattr(arg_5, arg_2)


def Func(arg_0, arg_1, arg_2):
    """When dispatched on loops, has_context the target vars are the attribute _target_vars.

    Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than
          one of its attributes (e.g. body). Purely for convenience.
    """
    return _test(
        arg_0,
        arg_1 or MSG_INCORRECT_LOOP,
        arg_2,
        tv_name="_target_vars",
        highlight_name="target",
    )


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
    """Return child state with name part as its ast tree"""

    if arg_3 is None:
        arg_3 = "Are you sure you defined the {{part}}? "
    if arg_4 is None:
        arg_4 = "Did you correctly specify the {{part}}? "

    if not arg_2:
        arg_2 = arg_1
    arg_5 = {"msg": arg_4, "kwargs": {"part": arg_2}}

    has_part(arg_0, arg_1, arg_3, arg_5["kwargs"])

    arg_6 = arg_0.student_parts[arg_1]
    arg_7 = arg_0.solution_parts[arg_1]

    assert_ast(arg_0, arg_7, arg_5["kwargs"])

    return part_to_child(arg_6, arg_7, arg_5, arg_0)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None):
    """Return child state with indexed name part as its ast tree.

    ``index`` can be:

    - an integer, in which case the student/solution_parts are indexed by position.
    - a string, in which case the student/solution_parts are expected to be a dictionary.
    - a list of indices (which can be integer or string), in which case the student parts are indexed step by step.
    """

    if arg_4 is None:
        arg_4 = "Are you sure you defined the {{part}}? "
    if arg_5 is None:
        arg_5 = "Did you correctly specify the {{part}}? "

    # create message
    arg_6 = get_ord(arg_2 + 1) if isinstance(arg_2, int) else ""
    arg_7 = {"index": arg_2, "ordinal": arg_6}
    arg_7.update(part=render(arg_3, arg_7))

    arg_8 = {"msg": arg_5, "kwargs": arg_7}

    # check there are enough parts for index
    has_part(arg_0, arg_1, arg_4, arg_7, arg_2)

    # get part at index
    arg_9 = arg_0.student_parts[arg_1]
    arg_10 = arg_0.solution_parts[arg_1]

    if isinstance(arg_2, list):
        for arg_11 in arg_2:
            arg_9 = arg_9[arg_11]
            arg_10 = arg_10[arg_11]
    else:
        arg_9 = arg_9[arg_2]
        arg_10 = arg_10[arg_2]

    assert_ast(arg_0, arg_10, arg_7)

    # return child state from part
    return part_to_child(arg_9, arg_10, arg_8, arg_0)


def Func(arg_0):
		"""
		Return the true anomaly at each time
		"""
		arg_0.f = _rsky._getf(arg_0.t_supersample, arg_0.t0, arg_0.per, arg_0.a,
							  arg_0.inc*pi/180., arg_0.ecc, arg_0.w*pi/180.,
							  arg_0.transittype, arg_0.nthreads)
		return arg_0.f


def Func(arg_0, arg_1):
    """ Loads the class from the class_path string """
    if arg_0 is None:
        return arg_1

    arg_2 = arg_0.rsplit('.', 1)
    arg_3 = getattr(
        importlib.import_module(arg_2[0]),
        arg_2[1],
        arg_1
    ) if len(arg_2) > 1 else arg_1

    return arg_3


def Func(arg_0):
    """ process pagination requests from request parameter """
    arg_1 = 20
    arg_2 = 0
    arg_3 = 0
    if "page_size" in arg_0.POST:
        arg_1 = int(arg_0.POST["page_size"])
        arg_4 = getattr(settings, "SEARCH_MAX_PAGE_SIZE", 100)
        # The parens below are superfluous, but make it much clearer to the reader what is going on
        if not (0 < arg_1 <= arg_4):  # pylint: disable=superfluous-parens
            raise ValueError(_('Invalid page size of {page_size}').format(page_size=arg_1))

        if "page_index" in arg_0.POST:
            arg_2 = int(arg_0.POST["page_index"])
            arg_3 = arg_2 * arg_1
    return arg_1, arg_3, arg_2


def Func(arg_0):
    """ Create separate dictionary of supported filter values provided """
    return {
        arg_1: arg_0.POST[arg_1]
        for arg_1 in arg_0.POST
        if arg_1 in course_discovery_filter_fields()
    }


def Func(arg_0):
    """
    Search for courses

    Args:
        request (required) - django request object

    Returns:
        http json response with the following fields
            "took" - how many seconds the operation took
            "total" - how many results were found
            "max_score" - maximum score from these resutls
            "results" - json array of result documents

            or

            "error" - displayable information about an error that occured on the server

    POST Params:
        "search_string" (optional) - text with which to search for courses
        "page_size" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)
        "page_index" (optional) - for which page (zero-indexed) to include results (defaults to 0)
    """
    arg_1 = {
        "error": _("Nothing to search")
    }
    arg_2 = 500

    arg_3 = arg_0.POST.get("search_string", None)

    try:
        arg_4, arg_5, arg_6 = _process_pagination_values(arg_0)
        arg_7 = _process_field_values(arg_0)

        # Analytics - log search request
        track.emit(
            'edx.Func.search.initiated',
            {
                "search_term": arg_3,
                "page_size": arg_4,
                "page_number": arg_6,
            }
        )

        arg_1 = Func_search(
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_7=arg_7,
        )

        # Analytics - log search results before sending to browser
        track.emit(
            'edx.Func.search.results_displayed',
            {
                "search_term": arg_3,
                "page_size": arg_4,
                "page_number": arg_6,
                "results_count": arg_1["total"],
            }
        )

        arg_2 = 200

    except ValueError as invalid_err:
        arg_1 = {
            "error": six.text_type(invalid_err)
        }
        log.debug(six.text_type(invalid_err))

    except QueryParseError:
        arg_1 = {
            "error": _('Your query seems malformed. Check for unmatched quotes.')
        }

    # Allow for broad exceptions here - this is an entry point from external reference
    except Exception as err:  # pylint: disable=broad-except
        arg_1 = {
            "error": _('An error occurred when searching for "{search_string}"').format(search_string=arg_3)
        }
        log.exception(
            'Search view exception when searching for %s for user %s: %r',
            arg_3,
            arg_0.user.id,
            err
        )

    return JsonResponse(arg_1, status=arg_2)


def Func(arg_0, arg_1):
    """ Return field to apply into filter, if an array then use a range, otherwise look for a term match """
    arg_2 = None
    if isinstance(arg_1, ValueRange):
        arg_3 = {}
        if arg_1.lower:
            arg_3.update({"gte": arg_1.lower_string})
        if arg_1.upper:
            arg_3.update({"lte": arg_1.upper_string})
        arg_2 = {
            "range": {
                arg_0: arg_3
            }
        }
    elif _is_iterable(arg_1):
        arg_2 = {
            "terms": {
                arg_0: arg_1
            }
        }
    else:
        arg_2 = {
            "term": {
                arg_0: arg_1
            }
        }
    return arg_2


def Func(arg_0):
    """
    We have a field_dictionary - we want to match the values for an elasticsearch "match" query
    This is only potentially useful when trying to tune certain search operations
    """
    def field_item(arg_1):
        """ format field match as "match" item for elasticsearch query """
        return {
            "match": {
                arg_1: arg_0[arg_1]
            }
        }

    return [field_item(arg_1) for arg_1 in arg_0]


def Func(arg_0):
    """
    We have a filter_dictionary - this means that if the field is included
    and matches, then we can include, OR if the field is undefined, then we
    assume it is safe to include
    """
    def filter_item(arg_1):
        """ format elasticsearch filter to pass if value matches OR field is not included """
        if arg_0[arg_1] is not None:
            return {
                "or": [
                    _get_filter_field(arg_1, arg_0[arg_1]),
                    {
                        "missing": {
                            "field": arg_1
                        }
                    }
                ]
            }

        return {
            "missing": {
                "field": arg_1
            }
        }

    return [filter_item(arg_1) for arg_1 in arg_0]


def Func(arg_0):
    """ We have a list of terms with which we return facets """
    arg_1 = {}
    for arg_2 in arg_0:
        arg_3 = {"field": arg_2}
        if arg_0[arg_2]:
            for arg_4 in arg_0[arg_2]:
                arg_3[arg_4] = arg_0[arg_2][arg_4]

        arg_1[arg_2] = {
            "terms": arg_3
        }

    return arg_1


def Func(arg_0, arg_1, arg_2):
        """ fetch mapped-items structure from cache """
        return cache.get(arg_0.get_cache_item_name(arg_1, arg_2), {})


def Func(arg_0, arg_1):
        """ Logs indexing errors and raises a general ElasticSearch Exception"""
        arg_2 = []
        for arg_3 in arg_1:
            arg_2.append(str(arg_3))
        raise exceptions.ElasticsearchException(', '.join(arg_2))


def Func(arg_0, arg_1):
        """
        Interfaces with the elasticsearch mappings for the index
        prevents multiple loading of the same mappings from ES when called more than once

        Mappings format in elasticsearch is as follows:
        {
           "doc_type": {
              "properties": {
                 "nested_property": {
                    "properties": {
                       "an_analysed_property": {
                          "type": "string"
                       },
                       "another_analysed_property": {
                          "type": "string"
                       }
                    }
                 },
                 "a_not_analysed_property": {
                    "type": "string",
                    "index": "not_analyzed"
                 },
                 "a_date_property": {
                    "type": "date"
                 }
              }
           }
        }

        We cache the properties of each doc_type, if they are not available, we'll load them again from Elasticsearch
        """
        # Try loading the mapping from the cache.
        arg_2 = ElasticSearchEngine.get_mappings(arg_0.index_name, arg_1)

        # Fall back to Elasticsearch
        if not arg_2:
            arg_2 = arg_0._es.indices.get_mapping(
                index=arg_0.index_name,
                arg_1=arg_1,
            ).get(arg_0.index_name, {}).get('mappings', {}).get(arg_1, {})

            # Cache the mapping, if one was retrieved
            if arg_2:
                ElasticSearchEngine.set_mappings(
                    arg_0.index_name,
                    arg_1,
                    arg_2
                )

        return arg_2


def Func(arg_0, arg_1, arg_2, **arg_3):
        """
        Implements call to add documents to the ES Func
        Note the call to _check_mappings which will setup fields with the desired mappings
        """

        try:
            arg_4 = []
            for arg_5 in arg_2:
                arg_0._check_mappings(arg_1, arg_5)
                arg_6 = arg_5['id'] if 'id' in arg_5 else None
                log.debug("Funcing %s object with id %s", arg_1, arg_6)
                arg_7 = {
                    "_Func": arg_0.Func_name,
                    "_type": arg_1,
                    "_id": arg_6,
                    "_source": arg_5
                }
                arg_4.append(arg_7)
            # bulk() returns a tuple with summary information
            # number of successfully executed actions and number of errors if stats_only is set to True.
            arg_8, arg_9 = bulk(
                arg_0._es,
                arg_4,
                **arg_3
            )
            if arg_9:
                ElasticSearchEngine.log_Funcing_error(arg_9)
        # Broad exception handler to protect around bulk call
        except Exception as ex:
            # log information and re-raise
            log.exception("error while Funcing - %s", str(ex))
            raise


def Func(arg_0,
               arg_1=None,
               arg_2=None,
               arg_3=None,
               arg_4=None,
               arg_5=None,
               arg_6=None,
               arg_7=False,
               **arg_8):  # pylint: disable=too-many-arguments, too-many-locals, too-many-branches, arguments-differ
        """
        Implements call to Func the index for the desired content.

        Args:
            query_string (str): the string of values upon which to Func within the
            content of the objects within the index

            field_dictionary (dict): dictionary of values which _must_ exist and
            _must_ match in order for the documents to be included in the results

            filter_dictionary (dict): dictionary of values which _must_ match if the
            field exists in order for the documents to be included in the results;
            documents for which the field does not exist may be included in the
            results if they are not otherwise filtered out

            exclude_dictionary(dict): dictionary of values all of which which must
            not match in order for the documents to be included in the results;
            documents which have any of these fields and for which the value matches
            one of the specified values shall be filtered out of the result set

            facet_terms (dict): dictionary of terms to include within Func
            facets list - key is the term desired to facet upon, and the value is a
            dictionary of extended information to include. Supported right now is a
            size specification for a cap upon how many facet results to return (can
            be an empty dictionary to use default size for underlying engine):

            e.g.
            {
                "org": {"size": 10},  # only show top 10 organizations
                "modes": {}
            }

            use_field_match (bool): flag to indicate whether to use elastic
            filtering or elastic matching for field matches - this is nothing but a
            potential performance tune for certain queries

            (deprecated) exclude_ids (list): list of id values to exclude from the results -
            useful for finding maches that aren't "one of these"

        Returns:
            dict object with results in the desired format
            {
                "took": 3,
                "total": 4,
                "max_score": 2.0123,
                "results": [
                    {
                        "score": 2.0123,
                        "data": {
                            ...
                        }
                    },
                    {
                        "score": 0.0983,
                        "data": {
                            ...
                        }
                    }
                ],
                "facets": {
                    "org": {
                        "total": total_count,
                        "other": 1,
                        "terms": {
                            "MITx": 25,
                            "HarvardX": 18
                        }
                    },
                    "modes": {
                        "total": modes_count,
                        "other": 15,
                        "terms": {
                            "honor": 58,
                            "verified": 44,
                        }
                    }
                }
            }

        Raises:
            ElasticFuncException when there is a problem with the response from elasticFunc

        Example usage:
            .Func(
                "find the words within this string",
                {
                    "must_have_field": "mast_have_value for must_have_field"
                },
                {

                }
            )
        """

        log.debug("Funcing index with %s", arg_1)

        arg_9 = []
        arg_10 = []

        # We have a query string, Func all fields for matching text within the "content" node
        if arg_1:
            if six.PY2:
                arg_1 = arg_1.encode('utf-8').translate(None, RESERVED_CHARACTERS)
            else:
                arg_1 = arg_1.translate(arg_1.maketrans('', '', RESERVED_CHARACTERS))
            arg_9.append({
                "query_string": {
                    "fields": ["content.*"],
                    "query": arg_1
                }
            })

        if arg_2:
            if arg_7:
                arg_9.extend(_process_field_queries(arg_2))
            else:
                arg_10.extend(_process_field_filters(arg_2))

        if arg_3:
            arg_10.extend(_process_filters(arg_3))

        # Support deprecated argument of exclude_ids
        if arg_6:
            if not arg_4:
                arg_4 = {}
            if "_id" not in arg_4:
                arg_4["_id"] = []
            arg_4["_id"].extend(arg_6)

        if arg_4:
            arg_10.append(_process_exclude_dictionary(arg_4))

        arg_11 = {
            "match_all": {}
        }
        if arg_9:
            arg_11 = {
                "bool": {
                    "must": arg_9
                }
            }

        arg_12 = arg_11
        if arg_10:
            arg_13 = {
                "bool": {
                    "must": arg_10
                }
            }
            arg_12 = {
                "filtered": {
                    "query": arg_11,
                    "filter": arg_13,
                }
            }

        arg_14 = {"query": arg_12}
        if arg_5:
            arg_15 = _process_facet_terms(arg_5)
            if arg_15:
                arg_14["facets"] = arg_15

        try:
            arg_16 = arg_0._es.Func(
                index=arg_0.index_name,
                arg_14=arg_14,
                **arg_8
            )
        except exceptions.ElasticFuncException as ex:
            arg_17 = six.text_type(ex)
            if 'QueryParsingException' in arg_17:
                log.exception("Malformed Func query: %s", arg_17)
                raise QueryParseError('Malformed Func query.')
            else:
                # log information and re-raise
                log.exception("error while Funcing index - %s", str(arg_17))
                raise

        return _translate_hits(arg_16)


def Func(
        arg_0,
        arg_1=None,
        arg_2=10,
        arg_3=0,
        arg_4=None):
    """ Call the search engine with the appropriate parameters """
    # field_, filter_ and exclude_dictionary(s) can be overridden by calling application
    # field_dictionary includes course if course_id provided
    (arg_5, arg_6, arg_7) = SearchFilterGenerator.generate_field_filters(
        arg_1=arg_1,
        arg_4=arg_4
    )

    arg_8 = SearchEngine.get_search_engine(getattr(settings, "COURSEWARE_INDEX_NAME", "courseware_index"))
    if not arg_8:
        raise NoSearchEngineError("No search engine specified in settings.SEARCH_ENGINE")

    arg_9 = arg_8.search_string(
        arg_0,
        arg_5=arg_5,
        arg_6=arg_6,
        arg_7=arg_7,
        arg_2=arg_2,
        arg_3=arg_3,
        doc_type="courseware_content",
    )

    # post-process the result
    for arg_10 in arg_9["results"]:
        arg_10["data"] = SearchResultProcessor.process_result(arg_10["data"], arg_0, arg_1)

    arg_9["access_denied_count"] = len([r for r in arg_9["results"] if r["data"] is None])
    arg_9["results"] = [r for r in arg_9["results"] if r["data"] is not None]

    return arg_9


def Func(arg_0=None, arg_1=20, arg_2=0, arg_3=None):
    """
    Course Discovery activities against the search engine index of course details
    """
    # We'll ignore the course-enrollemnt informaiton in field and filter
    # dictionary, and use our own logic upon enrollment dates for these
    arg_4 = ["org"]
    (arg_5, arg_6, arg_7) = SearchFilterGenerator.generate_field_filters()
    arg_8 = {}
    arg_8.update({arg_9: arg_5[arg_9] for arg_9 in arg_5 if arg_9 in arg_4})
    if arg_3:
        arg_8.update(arg_3)
    if not getattr(settings, "SEARCH_SKIP_ENROLLMENT_START_DATE_FILTERING", False):
        arg_8["enrollment_start"] = DateRange(None, datetime.utcnow())

    arg_10 = SearchEngine.get_search_engine(getattr(settings, "COURSEWARE_INDEX_NAME", "courseware_index"))
    if not arg_10:
        raise NoSearchEngineError("No search engine specified in settings.SEARCH_ENGINE")

    arg_11 = arg_10.search(
        query_string=arg_0,
        doc_type="course_info",
        arg_1=arg_1,
        arg_2=arg_2,
        # only show when enrollment start IS provided and is before now
        arg_3=arg_8,
        # show if no enrollment end is provided and has not yet been reached
        filter_dictionary={"enrollment_end": DateRange(datetime.utcnow(), None)},
        arg_7=arg_7,
        facet_terms=course_discovery_facets(),
    )

    return arg_11


def Func(arg_0):
        """ Used by default implementation for finding excerpt """
        arg_1 = [value for value in six.itervalues(arg_0) if not isinstance(value, dict)]
        for arg_2 in [dv for dv in six.itervalues(arg_0) if isinstance(dv, dict)]:
            arg_1.extend(SearchResultProcessor.Func(arg_2))
        return arg_1


def Func(arg_0, arg_1, arg_2):
        """ Used by default property excerpt """
        arg_3 = [w.lower() for w in arg_1]

        def has_match(arg_4):
            """ Do any of the words match within the string """
            arg_5 = arg_4.lower()
            for arg_6 in arg_3:
                if arg_6 in arg_5:
                    return True
            return False

        arg_7 = [textwrap.wrap(s) for s in arg_0]
        arg_8 = list(chain.from_iterable(arg_7))
        arg_9 = [ms for ms in arg_8 if has_match(ms)]

        arg_10 = 0
        arg_11 = None
        for arg_12, arg_13 in enumerate(arg_9):
            arg_10 += len(arg_13)
            if arg_10 >= arg_2:
                arg_11 = arg_12
                break

        return arg_9[0:arg_11]


def Func(arg_0, arg_1):
        """ decorate the matches within the excerpt """
        arg_2 = re.finditer(arg_1, arg_0, re.IGNORECASE)
        for arg_3 in set([match.group() for match in arg_2]):
            arg_0 = arg_0.replace(
                arg_3,
                getattr(settings, "SEARCH_MATCH_DECORATION", u"<b>{}</b>").format(arg_3)
            )
        return arg_0


def Func(arg_0):
        """
        Called during post processing of result
        Any properties defined in your subclass will get exposed as members of the result json from the search
        """
        for arg_1 in [p[0] for p in inspect.getmembers(arg_0.__class__) if isinstance(p[1], property)]:
            arg_0._results_fields[arg_1] = getattr(arg_0, arg_1, None)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Called from within search handler. Finds desired subclass and decides if the
        result should be removed and adds properties derived from the result information
        """
        arg_4 = _load_class(getattr(settings, "SEARCH_RESULT_PROCESSOR", None), arg_0)
        arg_5 = arg_4(arg_1, arg_2)
        if arg_5.should_remove(arg_3):
            return None
        try:
            arg_5.add_properties()
        # protect around any problems introduced by subclasses within their properties
        except Exception as ex:  # pylint: disable=broad-except
            log.exception("error processing properties for %s - %s: will remove from results",
                          json.dumps(arg_1, arg_0=DjangoJSONEncoder), str(ex))
            return None
        return arg_1


def Func(arg_0):
        """
        Property to display a useful Func representing the matches within the results
        """
        if "content" not in arg_0._results_fields:
            return None

        arg_1 = [arg_0._match_phrase]
        if six.PY2:
            arg_2 = [
                phrase.decode('utf-8')
                for phrase in shlex.split(arg_0._match_phrase.encode('utf-8'))
            ]
        else:
            arg_2 = [
                phrase
                for phrase in shlex.split(arg_0._match_phrase)
            ]
        if len(arg_2) > 1:
            arg_1.extend(arg_2)
        else:
            arg_1 = arg_2

        arg_3 = SearchResultProcessor.find_matches(
            SearchResultProcessor.strings_in_dictionary(arg_0._results_fields["content"]),
            arg_1,
            DESIRED_EXCERPT_LENGTH
        )
        arg_4 = ELLIPSIS.join(arg_3)

        for arg_5 in arg_1:
            arg_4 = SearchResultProcessor.decorate_matches(arg_4, arg_5)

        return arg_4


def Func(arg_0, **arg_1):
        """
        Called from within search handler
        Finds desired subclass and adds filter information based upon user information
        """
        arg_2 = _load_class(getattr(settings, "SEARCH_FILTER_GENERATOR", None), arg_0)()
        return (
            arg_2.field_dictionary(**arg_1),
            arg_2.filter_dictionary(**arg_1),
            arg_2.exclude_dictionary(**arg_1),
        )


def Func(arg_0, **arg_1):
        """
        Called from within search handler
        Finds desired subclass and calls initialize method
        """
        arg_2 = _load_class(getattr(settings, "SEARCH_INITIALIZER", None), arg_0)()
        return arg_2.initialize(**arg_1)


def Func(arg_0, arg_1):
        """Opens data file and for each line, calls _eat_name_line"""
        arg_0.names = {}
        with codecs.open(arg_1, encoding="iso8859-1") as f:
            for arg_3 in f:
                if any(map(lambda c: 128 < ord(c) < 160, arg_3)):
                    arg_3 = arg_3.encode("iso8859-1").decode("windows-1252")
                arg_0._eat_name_line(arg_3.strip())


def Func(arg_0, arg_1):
        """Parses one line of data file"""
        if arg_1[0] not in "#=":
            arg_2 = arg_1.split()
            arg_3 = arg_1[30:-1]
            arg_4 = map_name(arg_2[1])
            if not arg_0.case_sensitive:
                arg_4 = arg_4.lower()

            if arg_2[0] == "M":
                arg_0._set(arg_4, u"male", arg_3)
            elif arg_2[0] == "1M" or arg_2[0] == "?M":
                arg_0._set(arg_4, u"mostly_male", arg_3)
            elif arg_2[0] == "F":
                arg_0._set(arg_4, u"female", arg_3)
            elif arg_2[0] == "1F" or arg_2[0] == "?F":
                arg_0._set(arg_4, u"mostly_female", arg_3)
            elif arg_2[0] == "?":
                arg_0._set(arg_4, arg_0.unknown_value, arg_3)
            else:
                raise "Not sure what to do with a sex of %s" % arg_2[0]


def Func(arg_0, arg_1, arg_2):
        """Finds the most popular gender for the given name counting by given counter"""
        if arg_1 not in arg_0.names:
            return arg_0.unknown_value

        arg_3, arg_4 = (0, 0)
        arg_5 = arg_0.names[arg_1].keys()[0]
        for arg_6, arg_7 in arg_0.names[arg_1].items():
            arg_8, arg_9 = arg_2(arg_7)
            if arg_8 > arg_3 or (arg_8 == arg_3 and arg_9 > arg_4):
                arg_3, arg_4, arg_5 = arg_8, arg_9, arg_6

        return arg_5 if arg_3 > 0 else arg_0.unknown_value


def Func(arg_0, arg_1, arg_2=None):
        """Returns best gender for the given name and country pair"""
        if not arg_0.case_sensitive:
            arg_1 = arg_1.lower()

        if arg_1 not in arg_0.names:
            return arg_0.unknown_value
        elif not arg_2:
            def arg_5(arg_3):
                arg_3 = map(ord, arg_3.replace(" ", ""))
                return (len(arg_3),
                        sum(map(lambda c: c > 64 and c-55 or c-48, arg_3)))
            return arg_0._most_popular_gender(arg_1, arg_5)
        elif arg_2 in arg_0.__class__.COUNTRIES:
            arg_4 = arg_0.__class__.COUNTRIES.index(arg_2)
            arg_5 = lambda e: (ord(e[arg_4])-32, 0)
            return arg_0._most_popular_gender(arg_1, arg_5)
        else:
            raise NoCountryError("No such country: %s" % arg_2)


def Func(arg_0, arg_1, arg_2=None):
    """
    Executes the suite of TidyPy tools upon the project and returns the
    issues that are found.

    :param config: the TidyPy configuration to use
    :type config: dict
    :param path: that path to the project to analyze
    :type path: str
    :param progress:
        the progress reporter object that will receive callbacks during the
        execution of the tool suite. If not specified, not progress
        notifications will occur.
    :type progress: tidypy.Progress
    :rtype: tidypy.Collector
    """

    arg_2 = arg_2 or QuietProgress()
    arg_2.on_start()

    arg_3 = SyncManager()
    arg_3.start()

    arg_4 = 0
    arg_5 = arg_3.Queue()
    for arg_6, arg_7 in iteritems(get_tools()):
        if arg_0[arg_6]['use'] and arg_7.can_be_used():
            arg_4 += 1
            arg_5.put({
                'name': arg_6,
                'config': arg_0[arg_6],
            })

    arg_8 = Collector(arg_0)
    if not arg_4:
        arg_2.on_finish()
        return arg_8

    arg_9 = arg_3.Queue()
    arg_10 = arg_3.dict({
        'finder': Finder(arg_1, arg_0),
    })

    arg_11 = []
    for arg_12 in range(arg_0['workers']):
        arg_13 = Worker(
            args=(
                arg_5,
                arg_9,
                arg_10,
            ),
        )
        arg_13.start()
        arg_11.append(arg_13)

    while arg_4:
        try:
            arg_14 = arg_9.get(True, 0.25)
        except Empty:
            pass
        else:
            if arg_14['type'] == 'start':
                arg_2.on_tool_start(arg_14['tool'])
            elif arg_14['type'] == 'complete':
                arg_8.add_issues(arg_14['issues'])
                arg_2.on_tool_finish(arg_14['tool'])
                arg_4 -= 1

    arg_2.on_finish()

    return arg_8


def Func(
        arg_0,
        arg_1,
        arg_2,
        arg_3=None,
        arg_4=None):
    """
    Executes the configured suite of issue reports.

    :param config: the TidyPy configuration to use
    :type config: dict
    :param path: that path to the project that was analyzed
    :type path: str
    :param collector: the issues to report
    :type collector: tidypy.Collector
    """

    arg_5 = get_reports()
    for arg_6 in arg_0.get('requested_reports', []):
        if arg_6.get('type') and arg_6['type'] in arg_5:
            arg_7 = arg_0.get('report', {}).get(arg_6['type'], {})
            arg_7.update(arg_6)
            arg_8 = arg_5[arg_6['type']](
                arg_7,
                arg_1,
                arg_4=arg_4,
            )
            arg_8.produce(arg_2)
            if arg_3:
                arg_3(arg_6)


def Func(arg_0, arg_1):
        """
        Determines whether or not the specified file is excluded by the
        project's configuration.

        :param path: the path to check
        :type path: pathlib.Path
        :rtype: bool
        """

        arg_2 = arg_1.relative_to(arg_0.base_path).as_posix()
        return matches_masks(arg_2, arg_0.excludes)


def Func(arg_0, arg_1):
        """
        Determines whether or not the specified directory is excluded by the
        project's configuration.

        :param path: the path to check
        :type path: pathlib.Path
        :rtype: bool
        """

        if arg_0.is_excluded(arg_1):
            return True
        return matches_masks(arg_1.name, ALWAYS_EXCLUDED_DIRS)


def Func(arg_0, arg_1=None):
        """
        A generator that produces a sequence of paths to files in the project
        that matches the specified filters.

        :param filters:
            the regular expressions to use when finding files in the project.
            If not specified, all files are returned.
        :type filters: list(str)
        """

        arg_1 = compile_masks(arg_1 or [r'.*'])

        for Func in itervalues(arg_0._found):
            for arg_3 in Func:
                arg_4 = text_type(Path(arg_3).relative_to(arg_0.base_path))
                if matches_masks(arg_4, arg_1):
                    yield arg_3


def Func(arg_0, arg_1=None, arg_2=None):
        """
        A generator that produces a sequence of paths to Func in the
        project that matches the specified filters.

        :param filters:
            the regular expressions to use when finding Func in the
            project. If not specified, all Func are returned.
        :type filters: list(str)
        :param containing:
            if a directory passes through the specified filters, it is checked
            for the presence of a file that matches one of the regular
            expressions in this parameter.
        :type containing: list(str)
        """

        arg_1 = compile_masks(arg_1 or [r'.*'])
        arg_3 = compile_masks(arg_2)

        for arg_4, arg_5 in iteritems(arg_0._found):
            arg_6 = text_type(Path(arg_4).relative_to(arg_0.base_path))
            if matches_masks(arg_6, arg_1):
                if not arg_3 or arg_0._contains(arg_5, arg_3):
                    yield arg_4


def Func(arg_0, arg_1):
        """
        Adds an issue to the collection.

        :param issues: the issue(s) to add
        :type issues: tidypy.Issue or list(tidypy.Issue)
        """

        if not isinstance(arg_1, (list, tuple)):
            arg_1 = [arg_1]
        with arg_0._lock:
            arg_0._all_issues.extend(arg_1)
            arg_0._cleaned_issues = None


def Func(arg_0, arg_1=False):
        """
        Returns the number of issues in the collection.

        :param include_unclean:
            whether or not to include issues that are being ignored due to
            being a duplicate, excluded, etc.
        :type include_unclean: bool
        :rtype: int
        """

        if arg_1:
            return len(arg_0._all_issues)
        arg_0._ensure_cleaned_issues()
        return len(arg_0._cleaned_issues)


def Func(arg_0, arg_1=None):
        """
        Retrieves the issues in the collection.

        :param sortby: the properties to sort the issues by
        :type sortby: list(str)
        :rtype: list(tidypy.Issue)
        """

        arg_0._ensure_cleaned_issues()
        return arg_0._sort_issues(arg_0._cleaned_issues, arg_1)


def Func(arg_0, arg_1, arg_2=False):
        """
        A convenience method for parsing a TOML-serialized configuration.

        :param content: a TOML string containing a TidyPy configuration
        :type content: str
        :param is_pyproject:
            whether or not the content is (or resembles) a ``pyproject.toml``
            file, where the TidyPy configuration is located within a key named
            ``tool``.
        :type is_pyproject: bool
        :rtype: dict
        """

        arg_3 = pytoml.loads(arg_1)

        if arg_2:
            arg_3 = arg_3.get('tool', {})
        arg_3 = arg_3.get('tidypy', {})

        return arg_3


def Func():
    """
    Retrieves the TidyPy tools that are available in the current Python
    environment.

    The returned dictionary has keys that are the tool names and values are the
    tool classes.

    :rtype: dict
    """

    # pylint: disable=protected-access

    if not hasattr(Func, '_CACHE'):
        Func._CACHE = dict()
        for arg_2 in pkg_resources.iter_entry_points('tidypy.tools'):
            try:
                Func._CACHE[arg_2.name] = arg_2.load()
            except ImportError as exc:  # pragma: no cover
                output_error(
                    'Could not load tool "%s" defined by "%s": %s' % (
                        arg_2,
                        arg_2.dist,
                        exc,
                    ),
                )
    return Func._CACHE


def Func():
    """
    Retrieves the TidyPy configuration extenders that are available in the
    current Python environment.

    The returned dictionary has keys are the extender names and values are the
    extender classes.

    :rtype: dict
    """

    # pylint: disable=protected-access

    if not hasattr(Func, '_CACHE'):
        Func._CACHE = dict()
        for arg_2 in pkg_resources.iter_entry_points('tidypy.extenders'):
            try:
                Func._CACHE[arg_2.name] = arg_2.load()
            except ImportError as exc:  # pragma: no cover
                output_error(
                    'Could not load extender "%s" defined by "%s": %s' % (
                        arg_2,
                        arg_2.dist,
                        exc,
                    ),
                )
    return Func._CACHE


def Func(arg_0=None):
    """
    Clears out the cache of TidyPy configurations that were retrieved from
    outside the normal locations.
    """

    arg_1 = get_cache_path(arg_0)

    if arg_0:
        os.remove(arg_1)
    else:
        shutil.rmtree(arg_1)


def Func(arg_0):
    """
    Prints the specified string to ``stderr``.

    :param msg: the message to print
    :type msg: str
    """

    click.echo(click.style(arg_0, fg='red'), err=True)


def Func(arg_0):
    """
    A context manager that will append the specified paths to Python's
    ``sys.path`` during the execution of the block.

    :param paths: the paths to append
    :type paths: list(str)
    """

    arg_1 = arg_2.path
    arg_2.path = arg_0 + arg_2.path
    try:
        yield
    finally:
        arg_2.path = arg_1


def Func(arg_0):
    """
    Compiles a list of regular expressions.

    :param masks: the regular expressions to compile
    :type masks: list(str) or str
    :returns: list(regular expression object)
    """

    if not arg_0:
        arg_0 = []
    elif not isinstance(arg_0, (list, tuple)):
        arg_0 = [arg_0]

    return [
        re.compile(arg_1)
        for arg_1 in arg_0
    ]


def Func(arg_0):
    """
    Retrieves the AST of the specified file.

    This function performs simple caching so that the same file isn't read or
    parsed more than once per process.

    :param filepath: the file to parse
    :type filepath: str
    :returns: ast.AST
    """

    with _AST_CACHE_LOCK:
        if arg_0 not in arg_2:
            arg_1 = read_file(arg_0)
            arg_2[arg_0] = ast.parse(arg_1, filename=arg_0)
    return arg_2[arg_0]


def Func(arg_0, arg_1):
        """
        Called when an individual tool completes execution.

        :param tool: the name of the tool that completed
        :type tool: str
        """

        with arg_0._lock:
            if arg_1 in arg_0.current_tools:
                arg_0.current_tools.remove(arg_1)
                arg_0.completed_tools.append(arg_1)


def Func(arg_0, arg_1):
        """
            Execute an x3270 command

            `cmdstr` gets sent directly to the x3270 subprocess on it's stdin.
        """
        if arg_0.is_terminated:
            raise TerminatedError("this TerminalClient instance has been terminated")

        log.debug("sending command: %s", arg_1)
        arg_2 = Command(arg_0.app, arg_1)
        arg_3 = time.time()
        arg_2.execute()
        arg_4 = time.time() - arg_3
        log.debug("elapsed execution: {0}".format(arg_4))
        arg_0.status = Status(arg_2.status_line)

        return arg_2


def Func(arg_0, arg_1):
        """
            Connect to a host
        """
        if not arg_0.app.Func(arg_1):
            arg_2 = "Connect({0})".format(arg_1).encode("ascii")
            arg_0.exec_command(arg_2)
        arg_0.last_host = arg_1


def Func(arg_0):
        """
            Wait until the screen is ready, the cursor has been positioned
            on a modifiable field, and the keyboard is unlocked.

            Sometimes the server will "unlock" the keyboard but the screen will
            not yet be ready.  In that case, an attempt to read or write to the
            screen will result in a 'E' keyboard status because we tried to
            read from a screen that is not yet ready.

            Using this method tells the client to wait until a field is
            detected and the cursor has been positioned on it.
        """
        arg_0.exec_command("Wait({0}, InputField)".format(arg_0.timeout).encode("ascii"))
        if arg_0.status.keyboard != b"U":
            raise KeyboardStateError(
                "keyboard not unlocked, state was: {0}".format(
                    arg_0.status.keyboard.decode("ascii")
                )
            )


def Func(arg_0, arg_1, arg_2):
        """
            move the cursor to the given co-ordinates.  Co-ordinates are 1
            based, as listed in the status area of the terminal.
        """
        # the screen's co-ordinates are 1 based, but the command is 0 based
        arg_2 -= 1
        arg_1 -= 1
        arg_0.exec_command("MoveCursor({0}, {1})".format(arg_1, arg_2).encode("ascii"))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
            clears the field at the position given and inserts the string
            `tosend`

            tosend: the string to insert
            length: the length of the field

            Co-ordinates are 1 based, as listed in the status area of the
            terminal.

            raises: FieldTruncateError if `tosend` is longer than
                `length`.
        """
        if arg_4 < len(arg_3):
            raise FieldTruncateError('length limit %d, but got "%s"' % (arg_4, arg_3))
        if arg_2 is not None and arg_1 is not None:
            arg_0.move_to(arg_1, arg_2)
        arg_0.delete_field()
        arg_0.send_string(arg_3)


def Func(arg_0, arg_1):
        '''
        Configures this extension with a given configuration dictionary.
        This allows use of this extension without a flask app.

        Args:
            config (dict): A dictionary with configuration keys
        '''

        arg_0.config.update(arg_1)

        arg_0.config.setdefault('LDAP_PORT', 389)
        arg_0.config.setdefault('LDAP_HOST', None)
        arg_0.config.setdefault('LDAP_USE_SSL', False)
        arg_0.config.setdefault('LDAP_READONLY', True)
        arg_0.config.setdefault('LDAP_CHECK_NAMES', True)
        arg_0.config.setdefault('LDAP_BIND_DIRECT_CREDENTIALS', False)
        arg_0.config.setdefault('LDAP_BIND_DIRECT_PREFIX', '')
        arg_0.config.setdefault('LDAP_BIND_DIRECT_SUFFIX', '')
        arg_0.config.setdefault('LDAP_BIND_DIRECT_GET_USER_INFO', True)
        arg_0.config.setdefault('LDAP_ALWAYS_SEARCH_BIND', False)
        arg_0.config.setdefault('LDAP_BASE_DN', '')
        arg_0.config.setdefault('LDAP_BIND_USER_DN', None)
        arg_0.config.setdefault('LDAP_BIND_USER_PASSWORD', None)
        arg_0.config.setdefault('LDAP_SEARCH_FOR_GROUPS', True)
        arg_0.config.setdefault('LDAP_FAIL_AUTH_ON_MULTIPLE_FOUND', False)

        # Prepended to the Base DN to limit scope when searching for
        # Users/Groups.
        arg_0.config.setdefault('LDAP_USER_DN', '')
        arg_0.config.setdefault('LDAP_GROUP_DN', '')

        arg_0.config.setdefault('LDAP_BIND_AUTHENTICATION_TYPE', 'SIMPLE')

        # Ldap Filters
        arg_0.config.setdefault('LDAP_USER_SEARCH_SCOPE',
                               'LEVEL')
        arg_0.config.setdefault('LDAP_USER_OBJECT_FILTER',
                               '(objectclass=person)')
        arg_0.config.setdefault('LDAP_USER_LOGIN_ATTR', 'uid')
        arg_0.config.setdefault('LDAP_USER_RDN_ATTR', 'uid')
        arg_0.config.setdefault(
            'LDAP_GET_USER_ATTRIBUTES', ldap3.ALL_ATTRIBUTES)

        arg_0.config.setdefault('LDAP_GROUP_SEARCH_SCOPE',
                               'LEVEL')
        arg_0.config.setdefault(
            'LDAP_GROUP_OBJECT_FILTER', '(objectclass=group)')
        arg_0.config.setdefault('LDAP_GROUP_MEMBERS_ATTR', 'uniqueMember')
        arg_0.config.setdefault(
            'LDAP_GET_GROUP_ATTRIBUTES', ldap3.ALL_ATTRIBUTES)
        arg_0.config.setdefault('LDAP_ADD_SERVER', True)

        if arg_0.config['LDAP_ADD_SERVER']:
            arg_0.add_server(
                hostname=arg_0.config['LDAP_HOST'],
                port=arg_0.config['LDAP_PORT'],
                use_ssl=arg_0.config['LDAP_USE_SSL']
            )


def Func(arg_0, arg_1):
        """
        Cleanup after a request. Close any open connections.
        """

        arg_2 = stack.top
        if arg_2 is not None:
            if hasattr(arg_2, 'ldap3_manager_connections'):
                for arg_3 in arg_2.ldap3_manager_connections:
                    arg_0.destroy_connection(arg_3)
            if hasattr(arg_2, 'ldap3_manager_main_connection'):
                log.debug(
                    "Unbinding a connection used within the request context.")
                arg_2.ldap3_manager_main_connection.unbind()
                arg_2.ldap3_manager_main_connection = None


def Func(arg_0, arg_1, arg_2):
        """
        An abstracted authentication method. Decides whether to perform a
        direct bind or a search bind based upon the login attribute configured
        in the config.

        Args:
            username (str): Username of the user to bind
            password (str): User's password to bind with.

        Returns:
            AuthenticationResponse

        """
        if arg_0.config.get('LDAP_BIND_DIRECT_CREDENTIALS'):
            arg_3 = arg_0.Func_direct_credentials(arg_1, arg_2)

        elif not arg_0.config.get('LDAP_ALWAYS_SEARCH_BIND') and \
                arg_0.config.get('LDAP_USER_RDN_ATTR') == \
                arg_0.config.get('LDAP_USER_LOGIN_ATTR'):
            # Since the user's RDN is the same as the login field,
            # we can do a direct bind.
            arg_3 = arg_0.Func_direct_bind(arg_1, arg_2)
        else:
            # We need to search the User's DN to find who the user is (and
            # their DN) so we can try bind with their password.
            arg_3 = arg_0.Func_search_bind(arg_1, arg_2)

        return arg_3