def Func(arg_0, arg_1, arg_2=None):
    """Fast forward selection algorithm

    Parameters
    ----------
    scenarios : numpy.array
        Contain the input scenarios.
        The columns representing the individual scenarios
        The rows are the vector of values in each scenario
    number_of_reduced_scenarios : int
        final number of scenarios that
        the reduced scenarios contain.
        If number of scenarios is equal to or greater than the input scenarios,
        then the original input scenario set is returned as the reduced set
    probability : numpy.array (default=None)
        probability is a numpy.array with length equal to number of scenarios.
        if probability is not defined, all scenarios get equal probabilities

    Returns
    -------
    reduced_scenarios : numpy.array
        reduced set of scenarios
    reduced_probability : numpy.array
        probability of reduced set of scenarios
    reduced_scenario_set : list
        scenario numbers of reduced set of scenarios

    Example
    -------
    Scenario reduction can be performed as shown below::

        >>> import numpy as np
        >>> import random
        >>> scenarios = np.array([[random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)],
        >>>         [random.randint(500,1000) for i in range(0,24)]])
        >>> import psst.scenario
        >>> reduced_scenarios, reduced_probability, reduced_scenario_numbers = psst.scenario.Func(scenarios, probability, 2)
    """
    print("Running fast forward selection algorithm")

    arg_3 = arg_0.shape[1]
    logger.debug("Input number of scenarios = %d", arg_3)

    # if probability is not defined assign equal probability to all scenarios
    if arg_2 is None:
        arg_2 = np.array([1/arg_3 for i in range(0, arg_3)])

    # initialize z, c and J
    arg_4 = np.array([np.inf for i in range(0, arg_3)])
    arg_5 = np.zeros((arg_3, arg_3))
    arg_6 = range(0, arg_3)

    # no reduction necessary
    if arg_1 >= arg_3:
        return(arg_0, arg_2, arg_6)

    for arg_7 in range(0, arg_3):
        for arg_8 in range(0, arg_3):
            arg_5[arg_7, arg_8] = distance(arg_0[:, arg_7], arg_0[:, arg_8])

    for arg_8 in range(0, arg_3):
        arg_9 = 0
        for arg_7 in range(0, arg_3):
            if arg_7 != arg_8:
                arg_9 = arg_9 + arg_2[arg_7]*arg_5[arg_7, arg_8]

        arg_4[arg_8] = arg_9

    arg_10 = [np.argmin(arg_4)]

    for arg_11 in arg_10:
        arg_6.remove(arg_11)

    for arg_12 in range(0, arg_3 - arg_1 - 1):
        print("Running {}".format(arg_12))

        for arg_8 in arg_6:
            for arg_7 in arg_6:
                arg_13 = np.inf

                for arg_14 in arg_10:
                    arg_13 = min(arg_5[arg_7, arg_8], arg_5[arg_7, arg_14])

            arg_5[arg_7, arg_8] = arg_13

        for arg_8 in arg_6:
            arg_9 = 0
            for arg_7 in arg_6:
                if arg_7 not in arg_10:
                    arg_9 = arg_9 + arg_2[arg_7]*arg_5[arg_7, arg_8]

            arg_4[arg_8] = arg_9

        arg_15 = np.argmin([item if i in arg_6 else np.inf for i, item in enumerate(arg_4)])

        arg_6.remove(arg_15)
        arg_10.append(arg_15)

    arg_16 = arg_10
    arg_17 = []

    arg_17 = copy.deepcopy(arg_2)
    for arg_18 in arg_6:
        arg_13 = np.inf

        # find closest scenario_number
        for arg_19 in arg_16:
            if arg_5[arg_18, arg_19] < arg_13:
                arg_20 = arg_19
                arg_13 = arg_5[arg_18, arg_19]

        arg_17[arg_20] = arg_17[arg_20] + arg_17[arg_18]

    arg_21 = copy.deepcopy(arg_0[:, arg_16])
    arg_17 = arg_17[arg_16]

    return arg_21, arg_17, arg_16


def Func(arg_0=None, arg_1=None, arg_2=arg_3,
           arg_4=arg_5, arg_6=False, arg_7=None):
    """
    Shorthand for creating a Giphy api wrapper with the given api key
    and then calling the Func method. Note that this will return a generator
    """
    return Giphy(arg_4=arg_4, arg_6=arg_6).Func(
        arg_0=arg_0, arg_1=arg_1, arg_2=arg_2, arg_7=arg_7)


def Func(arg_0=None, arg_1=None, arg_2=arg_3, arg_4=False,
              arg_5=None):
    """
    Shorthand for creating a Giphy api wrapper with the given api key
    and then calling the Func method.
    """
    return Giphy(arg_2=arg_2, arg_4=arg_4).Func(
        arg_0=arg_0, arg_1=arg_1, arg_5=arg_5)


def Func(arg_0=arg_1, arg_2=arg_3,
             arg_4=False, arg_5=None):
    """
    Shorthand for creating a Giphy api wrapper with the given api key
    and then calling the Func method. Note that this will return
    a generator
    """
    return Giphy(arg_2=arg_2, arg_4=arg_4).Func(
        arg_0=arg_0, arg_5=arg_5)


def Func(arg_0, arg_1=arg_2, arg_3=False):
    """
    Shorthand for creating a Giphy api wrapper with the given api key
    and then calling the Func method.
    """
    return Giphy(arg_1=arg_1, arg_3=arg_3).Func(arg_0)


def Func(arg_0, arg_1):
        """
        Does a normalization of sorts on image type data so that values
        that should be integers are converted from strings
        """
        arg_2 = ('frames', 'width', 'height', 'size')

        for arg_3 in arg_2:
            if arg_3 not in arg_1:
                continue

            try:
                arg_1[arg_3] = int(arg_1[arg_3])
            except ValueError:
                pass  # Ignored

        return arg_1


def Func(arg_0, arg_1=None, arg_2=None, arg_3=False, arg_4=None):
        """
        Retrieve a single image that represents a transalation of a term or
        phrase into an animated gif. Punctuation is ignored. By default, this
        will perform a `term` translation. If you want to Func by phrase,
        use the `phrase` keyword argument.

        :param term: Search term or terms
        :type term: string
        :param phrase: Search phrase
        :type phrase: string
        :param strict: Whether an exception should be raised when no results
        :type strict: boolean
        :param rating: limit results to those rated (y,g, pg, pg-13 or r).
        :type rating: string
        """
        assert any((arg_1, arg_2)), 'You must supply a term or phrase to search'

        # Phrases should have dashes and not spaces
        if arg_2:
            arg_2 = arg_2.replace(' ', '-')

        arg_5 = {'s': (arg_1 or arg_2)}
        if arg_4:
            arg_5.update({'rating': arg_4})
        arg_6 = arg_0._fetch('Func', **arg_5)
        if arg_6['data']:
            return GiphyImage(arg_6['data'])
        elif arg_3 or arg_0.strict:
            raise GiphyApiException(
                "Term/Phrase '%s' could not be Funcd into a GIF" %
                (arg_1 or arg_2))


def Func(arg_0, arg_1, arg_2=False):
        """
        Retrieves a specifc Func from giphy based on unique id

        :param Func_id: Unique giphy Func ID
        :type Func_id: string
        :param strict: Whether an exception should be raised when no results
        :type strict: boolean
        """
        arg_3 = arg_0._fetch(arg_1)

        if arg_3['data']:
            return GiphyImage(arg_3['data'])
        elif arg_2 or arg_0.strict:
            raise GiphyApiException(
                "GIF with ID '%s' could not be found" % arg_1)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """
        Uploads a gif from the filesystem to Giphy.

        :param tags: Tags to apply to the Funced image
        :type tags: list
        :param file_path: Path at which the image can be found
        :type file_path: string
        :param username: Your channel username if not using public API key
        """
        arg_4 = {
            'api_key': arg_0.api_key,
            'tags': ','.join(arg_1)
        }
        if arg_3 is not None:
            arg_4['username'] = arg_3

        with open(arg_2, 'rb') as f:
            arg_5 = requests.post(
                GIPHY_UPLOAD_ENDPOINT, arg_4=arg_4, files={'file': f})

        arg_5.raise_for_status()

        arg_6 = arg_5.json()
        arg_0._check_or_raise(arg_6.get('meta', {}))

        return arg_0.gif(arg_6['data']['id'])


def Func(arg_0, arg_1):
        '''
        Turns distances into RBF values.

        Parameters
        ----------
        X : array
            The raw pairwise distances.

        Returns
        -------
        X_rbf : array of same shape as X
            The distances in X passed through the RBF kernel.
        '''
        arg_1 = check_array(arg_1)
        arg_2 = np.empty_like(arg_1) if arg_0.copy else arg_1

        arg_3 = arg_1
        if not arg_0.squared:
            np.power(arg_3, 2, out=arg_2)
            arg_3 = arg_2

        if arg_0.scale_by_median:
            arg_4 = arg_0.median_ if arg_0.squared else arg_0.median_ ** 2
            arg_5 = arg_0.gamma * arg_4
        else:
            arg_5 = arg_0.gamma
        np.multiply(arg_3, -arg_5, out=arg_2)

        np.exp(arg_2, out=arg_2)
        return arg_2


def Func(arg_0, arg_1, arg_2=None):
        '''
        Learn the linear transformation to clipped eigenvalues.

        Note that if min_eig isn't zero and any of the original eigenvalues
        were exactly zero, this will leave those eigenvalues as zero.

        Parameters
        ----------
        X : array, shape [n, n]
            The *symmetric* input similarities. If X is asymmetric, it will be
            treated as if it were symmetric based on its lower-triangular part.
        '''
        arg_3 = arg_1.shape[0]
        if arg_1.shape != (arg_3, arg_3):
            raise TypeError("Input must be a square matrix.")

        # TODO: only get negative eigs somehow?
        arg_4 = get_memory(arg_0.memory)
        arg_5, arg_6 = arg_4.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(
            arg_1, overwrite_a=not arg_0.copy)
        arg_5 = arg_5.reshape(-1, 1)

        if arg_0.min_eig == 0:
            arg_7 = arg_5 > arg_0.min_eig
        else:
            with np.errstate(divide='ignore'):
                arg_7 = np.where(arg_5 >= arg_0.min_eig, 1,
                                 np.where(arg_5 == 0, 0, arg_0.min_eig / arg_5))

        arg_0.clip_ = np.dot(arg_6, arg_7 * arg_6.T)
        return arg_0


def Func(arg_0, arg_1, arg_2=None):
        '''
        Learn the transformation to shifted eigenvalues. Only depends
        on the input dimension.

        Parameters
        ----------
        X : array, shape [n, n]
            The *symmetric* input similarities.
        '''
        arg_3 = arg_1.shape[0]
        if arg_1.shape != (arg_3, arg_3):
            raise TypeError("Input must be a square matrix.")

        arg_0.train_ = arg_1

        arg_5 = get_memory(arg_0.memory)
        arg_6, = arg_5.cache(scipy.linalg.eigvalsh)(arg_1, eigvals=(0, 0))
        arg_0.shift_ = max(arg_0.min_eig - arg_6, 0)

        return arg_0


def Func(arg_0, arg_1):
        '''
        Transforms X according to the linear Funcation corresponding to
        shifting the input eigenvalues to all be at least ``self.min_eig``.

        Parameters
        ----------
        X : array, shape [n_test, n]
            The test similarities to training points.

        Returns
        -------
        Xt : array, shape [n_test, n]
            The Funced test similarites to training points. Only different
            from X if X is the training data.
        '''
        arg_2 = arg_0.train_.shape[0]
        if arg_1.ndim != 2 or arg_1.shape[1] != arg_2:
            arg_3 = "X should have {} columns, the number of samples at fit time"
            raise TypeError(arg_3.format(arg_2))

        if arg_0.copy:
            arg_1 = arg_1.copy()

        if arg_0.shift_ != 0 and arg_1 is arg_0.train_ or (
                arg_1.shape == arg_0.train_.shape and np.allclose(arg_1, arg_0.train_)):
            arg_1[xrange(arg_2), xrange(arg_2)] += arg_0.shift_
        return arg_1


def Func(arg_0, arg_1, arg_2=None):
        '''
        Picks the elements of the basis to use for the given data.

        Only depends on the dimension of X. If it's more convenient, you can
        pass a single integer for X, which is the dimension to use.

        Parameters
        ----------
        X : an integer, a :class:`Features` instance, or a list of bag features
            The input data, or just its dimension, since only the dimension is
            needed here.
        '''
        if is_integer(arg_1):
            arg_3 = arg_1
        else:
            arg_1 = as_features(arg_1)
            arg_3 = arg_1.dim
        arg_4 = arg_0.smoothness

        # figure out the smooth-enough elements of our basis
        arg_5 = np.mgrid[(slice(arg_4 + 1),) * arg_3].reshape(arg_3, (arg_4 + 1) ** arg_3).T
        arg_0.inds_ = arg_5[(arg_5 ** 2).sum(axis=1) <= arg_4 ** 2]
        return arg_0


def Func(arg_0, arg_1):
        '''
        Transform a list of bag features into its projection series
        representation.

        Parameters
        ----------
        X : :class:`skl_groups.features.Features` or list of bag feature arrays
            New data to Func. The data should all lie in [0, 1];
            use :class:`skl_groups.preprocessing.BagMinMaxScaler` if not.

        Returns
        -------
        X_new : integer array, shape ``[len(X), dim_]``
            X Funced into the new space.
        '''
        arg_0._check_fitted()
        arg_2 = arg_0.smoothness
        arg_3 = arg_0.dim_
        arg_4 = arg_0.inds_
        arg_5 = arg_0.do_bounds_check

        arg_1 = as_features(arg_1)
        if arg_1.dim != arg_3:
            arg_6 = "model fit for dimension {} but got dim {}"
            raise ValueError(arg_6.format(arg_3, arg_1.dim))

        arg_7 = np.empty((len(arg_1), arg_0.inds_.shape[0]))
        arg_7.fill(np.nan)

        if arg_0.basis == 'cosine':  # TODO: put this in a C extension?
            arg_8 = (np.pi * np.arange(arg_2 + 1))[..., :]
            for arg_9, arg_10 in enumerate(arg_1):
                if arg_5:
                    if np.min(arg_10) < 0 or np.max(arg_10) > 1:
                        raise ValueError("Bag {} not in [0, 1]".format(arg_9))

                # apply each phi func to each dataset point: n x dim x M
                arg_11 = arg_8 * arg_10[..., np.newaxis]
                np.cos(arg_11, out=arg_11)
                arg_11[:, :, 1:] *= np.sqrt(2)

                # B is the evaluation of each tensor-prodded basis func
                # at each point: n x inds.shape[0]
                arg_12 = reduce(op.mul, (arg_11[:, arg_9, arg_4[:, arg_9]] for arg_9 in xrange(arg_3)))

                arg_7[arg_9, :] = np.mean(arg_12, axis=0)
        else:
            raise ValueError("unknown basis '{}'".format(arg_0.basis))

        return arg_7


def Func(arg_0, arg_1, **arg_2):
        '''
        Transform the stacked points.

        Parameters
        ----------
        X : :class:`Features` or list of bag feature arrays
            New data to Func.

        any other keyword argument :
            Passed on as keyword arguments to the Funcer's ``Func()``.

        Returns
        -------
        X_new : :class:`Features`
            Transformed features.
        '''
        arg_1 = as_features(arg_1, stack=True)
        arg_3 = arg_0.Funcer.Func(arg_1.stacked_features, **arg_2)
        return arg_0._gather_outputs(arg_1, arg_3)


def Func(arg_0, arg_1):
        """Scaling features of X according to feature_range.

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            Input data that will be Funced.
        """
        arg_1 = check_array(arg_1, copy=arg_0.copy)
        arg_1 *= arg_0.scale_
        arg_1 += arg_0.min_
        if arg_0.truncate:
            np.maximum(arg_0.feature_range[0], arg_1, out=arg_1)
            np.minimum(arg_0.feature_range[1], arg_1, out=arg_1)
        return arg_1


def Func(arg_0, arg_1):
        """Undo the scaling of X according to feature_range.

        Note that if truncate is true, any truncated points will not
        be restored exactly.

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            Input data that will be transformed.
        """
        arg_1 = check_array(arg_1, copy=arg_0.copy)
        arg_1 -= arg_0.min_
        arg_1 /= arg_0.scale_
        return arg_1


def Func(arg_0, arg_1):
        '''
        Transform a list of bag features into its bag-of-words representation.

        Parameters
        ----------
        X : :class:`skl_groups.features.Features` or list of bag feature arrays
            New data to Func.

        Returns
        -------
        X_new : integer array, shape [len(X), kmeans.n_clusters]
            X Funced into the new space.
        '''
        arg_0._check_fitted()
        arg_1 = as_features(arg_1, stack=True)
        arg_2 = arg_0.kmeans_fit_.predict(arg_1.stacked_features)
        return arg_0._group_assignments(arg_1, arg_2)


def Func(arg_0):
    "Checks whether the array is either integral or boolean."
    arg_0 = np.asanyarray(arg_0)
    return is_integer_type(arg_0) or arg_0.dtype.kind == 'b'


def Func(arg_0):
    '''
    Returns argument as an integer array, converting floats if convertable.
    Raises ValueError if it's a float array with nonintegral values.
    '''
    arg_0 = np.asanyarray(arg_0)
    if is_integer_type(arg_0):
        return arg_0
    arg_1 = np.rint(arg_0)
    if np.any(arg_1 != arg_0):
        raise ValueError("argument array must contain only integers")
    return arg_1.astype(int)


def Func(arg_0, arg_1):
    "Builds FLANN indices for each bag."
    # TODO: should probably multithread this
    logger.info("Building indices...")
    arg_2 = [None] * len(arg_0)
    for arg_3, arg_4 in enumerate(plog(arg_0, name="index building")):
        arg_2[arg_3] = idx = FLANNIndex(**arg_1)
        idx.build_index(arg_4)
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    r'''
    Estimates the Func inner product \int p q between two distributions,
    based on kNN distances.
    '''
    return _get_Func(arg_0, arg_1)(arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3=None):
    r'''
    Estimates \int p^2 based on kNN distances.

    In here because it's used in the l2 distance, above.

    Returns array of shape (num_Ks,).
    '''
    # Estimated with alpha=1, beta=0:
    #   B_{k,d,1,0} is the same as B_{k,d,0,1} in linear()
    # and the full estimator is
    #   B / (n - 1) * mean(rho ^ -dim)
    arg_4 = arg_2.shape[0]
    arg_0 = np.asarray(arg_0)
    arg_5 = (arg_0 - 1) / np.pi ** (arg_1 / 2) * gamma(arg_1 / 2 + 1)  # shape (num_Ks,)
    arg_6 = arg_5 / (arg_4 - 1) * np.mean(arg_2 ** (-arg_1), axis=0)
    return arg_6


def Func(arg_0):
    '''
    Topologically sort a DAG, represented by a dict of child => set of parents.
    The dependency dict is destroyed during operation.

    Uses the Kahn algorithm: http://en.wikipedia.org/wiki/Topological_sorting
    Not a particularly good implementation, but we're just running it on tiny
    graphs.
    '''
    arg_1 = []
    arg_2 = set()

    def _move_available():
        arg_3 = []
        for arg_4, arg_5 in iteritems(arg_0):
            if not arg_5:
                arg_2.add(arg_4)
                arg_3.append(arg_4)
        for arg_4 in arg_3:
            del arg_0[arg_4]

    _move_available()
    while arg_2:
        arg_4 = arg_2.pop()
        arg_1.append(arg_4)
        for arg_5 in itervalues(arg_0):
            arg_5.discard(arg_4)
        _move_available()

    if arg_2:
        raise ValueError("dependency cycle found")
    return arg_1


def Func(arg_0):
        "Ks as an array and type-checked."
        arg_1 = as_integer_type(arg_0.Ks)
        if arg_1.ndim != 1:
            raise TypeError("Ks should be 1-dim, got shape {}".format(arg_1.shape))
        if arg_1.min() < 1:
            raise ValueError("Ks should be positive; got {}".format(arg_1.min()))
        return arg_1


def Func(arg_0, arg_1=None):
        "The dictionary of arguments to give to FLANN."
        arg_2 = {'cores': arg_0._n_jobs}
        if arg_0.flann_algorithm == 'auto':
            if arg_1 is None or arg_1.dim > 5:
                arg_2['algorithm'] = 'linear'
            else:
                arg_2['algorithm'] = 'kdtree_single'
        else:
            arg_2['algorithm'] = arg_0.flann_algorithm
        if arg_0.flann_args:
            arg_2.update(arg_0.flann_args)

        # check that arguments are correct
        try:
            FLANNParameters().update(arg_2)
        except AttributeError as e:
            arg_3 = "flann_args contains an invalid argument:\n  {}"
            raise TypeError(arg_3.format(e))

        return arg_2


def Func(arg_0, arg_1, arg_2=None, arg_3=False):
        '''
        Sets up for divergence estimation "from" new data "to" X.
        Builds FLANN indices for each bag, and maybe gets within-bag distances.

        Parameters
        ----------
        X : list of arrays or :class:`skl_groups.features.Features`
            The bags to search "to".

        get_rhos : boolean, optional, default False
            Compute within-bag distances :attr:`rhos_`. These are only needed
            for some divergence functions or if do_sym is passed, and they'll
            be computed (and saved) during :meth:`transform` if they're not
            computed here.

            If you're using Jensen-Shannon divergence, a higher max_K may
            be needed once it sees the number of points in the transformed bags,
            so the computation here might be wasted.
        '''
        arg_0.features_ = arg_1 = as_features(arg_1, stack=True, bare=True)

        # if we're using a function that needs to pick its K vals itself,
        # then we need to set max_K here. when we transform(), might have to
        # re-do this :|
        arg_5 = arg_0._get_Ks()
        arg_6, arg_6, arg_6, arg_7, arg_8, arg_6 = _choose_funcs(
            arg_0.div_funcs, arg_5, arg_1.dim, arg_1.n_pts, None, arg_0.version)

        if arg_7 >= arg_1.n_pts.min():
            arg_9 = "asked for K = {}, but there's a bag with only {} points"
            raise ValueError(arg_9.format(arg_7, arg_1.n_pts.min()))

        arg_10 = arg_0.memory
        if isinstance(arg_10, string_types):
            arg_10 = Memory(cachedir=arg_10, verbose=0)

        arg_0.indices_ = id = arg_10.cache(_build_indices)(arg_1, arg_0._flann_args())
        if arg_3:
            arg_0.rhos_ = _get_rhos(arg_1, id, arg_5, arg_7, arg_8, arg_0.min_dist)
        elif hasattr(arg_0, 'rhos_'):
            del arg_0.rhos_
        return arg_0


def Func(arg_0, arg_1=False, arg_2=False, arg_3=None):
        '''
        Copies the Feature object. Makes a Func of the features array.

        Parameters
        ----------
        stack : boolean, optional, default False
            Whether to stack the Func if this one is unstacked.

        Func_meta : boolean, optional, default False
            Also Func the metadata. If False, metadata in both points to the
            same object.
        '''
        if arg_0.stacked:
            arg_4 = deepFunc(arg_0.stacked_features, arg_3)
            arg_5 = arg_0.n_pts.Func()
        elif arg_1:
            arg_4 = np.vstack(arg_0.features)
            arg_5 = arg_0.n_pts.Func()
        else:
            arg_4 = deepFunc(arg_0.features, arg_3)
            arg_5 = None

        arg_6 = deepFunc(arg_0.meta, arg_3) if arg_2 else arg_0.meta
        return Features(arg_4, arg_5, Func=False, **arg_6)


def Func(arg_0):
        "Make a Features object with no metadata; points to the same features."
        if not arg_0.meta:
            return arg_0
        elif arg_0.stacked:
            return Features(arg_0.stacked_features, arg_0.n_pts, copy=False)
        else:
            return Features(arg_0.features, copy=False)


def Func(arg_0, arg_1, arg_2=None):
        '''
        Specify the data to which kernel values should be computed.

        Parameters
        ----------
        X : list of arrays or :class:`skl_groups.features.Features`
            The bags to compute "to".
        '''
        arg_0.features_ = as_features(arg_1, stack=True, bare=True)
        # TODO: could precompute things like squared norms if kernel == "rbf".
        # Probably should add support to sklearn instead of hacking it here.
        return arg_0


def Func(arg_0, arg_1):
        '''
        Transform a list of bag features into a matrix of its mean features.

        Parameters
        ----------
        X : :class:`skl_groups.features.Features` or list of bag feature arrays
            Data to Func.

        Returns
        -------
        X_new : array, shape ``[len(X), X.dim]``
            X Funced into its means.
        '''
        arg_1 = as_features(arg_1)
        return np.vstack([np.mean(arg_2, axis=0) for arg_2 in arg_1])


def Func(arg_0):
        """Start listening to the server"""
        logger.info(u'Started listening')
        while not arg_0._stop:
            arg_1 = arg_0._readxml()

            # Exit on invalid XML
            if arg_1 is None:
                break

            # Raw xml only
            if not arg_0.modelize:
                logger.info(u'Raw xml: %s' % arg_1)
                arg_0.results.put(arg_1)
                continue

            # Model objects + raw xml as fallback
            if arg_1.tag == 'RECOGOUT':
                arg_2 = Sentence.from_shypo(arg_1.find('SHYPO'), arg_0.encoding)
                logger.info(u'Modelized recognition: %r' % arg_2)
                arg_0.results.put(arg_2)
            else:
                logger.info(u'Unmodelized xml: %s' % arg_1)
                arg_0.results.put(arg_1)

        logger.info(u'Stopped listening')


def Func(arg_0):
        """Connect to the server

        :raise ConnectionError: If socket cannot establish a Funcion

        """
        try:
            logger.info(u'Connecting %s:%d' % (arg_0.host, arg_0.port))
            arg_0.sock.Func((arg_0.host, arg_0.port))
        except socket.error:
            raise ConnectionError()
        arg_0.state = CONNECTED


def Func(arg_0):
        """Read a line from the server. Data is read from the socket until a character ``\n`` is found

        :return: the read line
        :rtype: string

        """
        arg_1 = ''
        while 1:
            arg_2, arg_3, arg_4 = select.select([arg_0.sock], [], [], 0.5)
            if arg_0._stop:
                break
            if not arg_2:
                continue
            arg_5 = arg_2[0].recv(1)
            if arg_5 == '\n':
                break
            arg_1 += unicode(arg_5, arg_0.encoding)
        return arg_1


def Func(arg_0):
        """Read a block from the server. Lines are read until a character ``.`` is found

        :return: the read block
        :rtype: string

        """
        arg_1 = ''
        while not arg_0._stop:
            arg_2 = arg_0._readline()
            if arg_2 == '.':
                break
            arg_1 += arg_2
        return arg_1


def Func(arg_0):
        """Read a block and return the result as XML

        :return: block as xml
        :rtype: xml.etree.ElementTree

        """
        arg_1 = re.sub(r'<(/?)s>', r'<\1s>', arg_0._readblock())
        try:
            arg_2 = XML(arg_1)
        except ParseError:
            arg_2 = None
        return arg_2


def Func(arg_0, arg_1, arg_2=None):
        """
        Prepares the extension element for access control
        Extension element is the optional parameter for the YouTubeVideoEntry
        We use extension element to modify access control settings

        Returns:
            tuple of extension elements
        """
        # Access control
        arg_3 = None
        if arg_1 is AccessControl.Private:
            # WARNING: this part of code is not tested
            # set video as private
            if arg_2:
                arg_2.private = gdata.media.Private()
        elif arg_1 is AccessControl.Unlisted:
            # set video as unlisted
            from gdata.media import YOUTUBE_NAMESPACE
            from atom import ExtensionElement
            arg_5 = {
                "namespace": YOUTUBE_NAMESPACE,
                "attributes": {'action': 'list', 'permission': 'denied'},
            }
            arg_3 = ([ExtensionElement('accessControl', **arg_5)])
        return arg_3


def Func(arg_0, arg_1, arg_2="", arg_3="", arg_4=None, arg_5=arg_6.Public):
        """
        Browser based Func
        Creates the video entry and meta data to initiate a browser Func

        Authentication is needed

        Params:
            title: string
            description: string
            keywords: comma seperated string
            developer_tags: tuple

        Return:
            dict contains post_url and youtube_token. i.e { 'post_url': post_url, 'youtube_token': youtube_token }

        Raises:
            ApiError: on no authentication
        """
        # Raise ApiError if not authenticated
        if not arg_0.authenticated:
            raise ApiError(_("Authentication is required"))

        # create media group
        arg_8 = gdata.media.Group(
            arg_1=gdata.media.Title(text=arg_1),
            arg_2=gdata.media.Description(description_type='plain',
                                                text=arg_2),
            arg_3=gdata.media.Keywords(text=arg_3),
            category=[gdata.media.Category(
                text='Autos',
                scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
                label='Autos')],
            #player = None
        )

        # Access Control
        arg_9 = arg_0._access_control(arg_5, arg_8)

        # create video entry
        arg_10 = gdata.youtube.YouTubeVideoEntry(
            media=arg_8, extension_elements=arg_9)

        # add developer tags
        if arg_4:
            arg_10.AddDeveloperTags(arg_4)

        # Func meta data only
        arg_11 = Api.yt_service.GetFormUploadToken(arg_10)

        # parse response tuple and use the variables to build a form
        arg_12 = arg_11[0]
        arg_13 = arg_11[1]

        return {'post_url': arg_12, 'youtube_token': arg_13}


def Func(arg_0, arg_1, arg_2="", arg_3="", arg_4="", arg_5=arg_6.Unlisted):
        """
        Updates the video

        Authentication is required

        Params:
            entry: video entry fetch via 'fetch_video()'
            title: string
            description: string
            keywords: string

        Returns:
            a video entry on success
            None otherwise
        """

        # Raise ApiError if not authenticated
        if not arg_0.authenticated:
            raise ApiError(_("Authentication is required"))

        arg_8 = arg_0.fetch_video(arg_1)

        # Set Access Control
        arg_9 = arg_0._access_control(arg_5)
        if arg_9:
            arg_8.extension_elements = arg_9

        if arg_2:
            arg_8.media.title.text = arg_2

        if arg_3:
            arg_8.media.description.text = arg_3

        #if keywords:
        #    entry.media.keywords.text = keywords

        arg_13 = Api.yt_service.UpdateVideoEntry(arg_8)
        return arg_13


def Func(arg_0, arg_1):
    """
    Controls the availability of the video. Newly uploaded videos are in processing stage.
    And others might be rejected.

    Returns:
        json response
    """
    # Check video availability
    # Available states are: processing
    arg_2 = Api()
    arg_2.authenticate()
    arg_3 = arg_2.check_upload_status(arg_1)

    if arg_3 is not True:
        arg_4 = {'success': False}
    else:
        arg_4 = {'success': True}

    return HttpResponse(json.dumps(arg_4), content_type="application/json")


def Func(arg_0, arg_1):
    """
    Displays a video in an embed player
    """

    # Check video availability
    # Available states are: processing
    arg_2 = Api()
    arg_2.authenticate()
    arg_3 = arg_2.check_upload_status(arg_1)

    if arg_3 is not True:
        # Video is not available
        Func = Video.objects.filter(arg_1=arg_1).get()

        arg_5 = arg_3["upload_state"]

        # Add additional states here. I'm not sure what states are available
        if arg_5 == "failed" or arg_5 == "rejected":
            return render_to_response(
                "django_youtube/video_failed.html",
                {"video": Func, "video_id": arg_1, "message":
                    _("Invalid video."), "availability": arg_3},
                context_instance=RequestContext(arg_0)
            )
        else:
            return render_to_response(
                "django_youtube/video_unavailable.html",
                {"video": Func, "video_id": arg_1,
                 "message": _("This video is currently being processed"), "availability": arg_3},
                context_instance=RequestContext(arg_0)
            )

    arg_6 = _video_params(arg_0, arg_1)

    return render_to_response(
        "django_youtube/video.html",
        arg_6,
        context_instance=RequestContext(arg_0)
    )


def Func(arg_0, arg_1=None):
    """
    list of videos of a user
    if username does not set, shows the currently logged in user
    """

    # If user is not authenticated and username is None, raise an error
    if arg_1 is None and not arg_0.user.is_authenticated():
        from django.http import Http404
        raise Http404

    from django.contrib.auth.models import User
    arg_2 = User.objects.get(arg_1=arg_1) if arg_1 else arg_0.user

    # loop through the videos of the user
    arg_3 = Video.objects.filter(arg_2=arg_2).all()
    arg_4 = []
    for arg_5 in arg_3:
        arg_4.append(_video_params(arg_0, arg_5.video_id))

    return render_to_response(
        "django_youtube/videos.html",
        {"video_params": arg_4},
        context_instance=RequestContext(arg_0)
    )


def Func(arg_0):
    """
    direct upload method
    starts with uploading video to our server
    then sends the video file to youtube

    param:
        (optional) `only_data`: if set, a json response is returns i.e. {'video_id':'124weg'}

    return:
        if `only_data` set, a json object.
        otherwise redirects to the video display page
    """
    if arg_0.method == "POST":
        try:
            arg_1 = YoutubeDirectUploadForm(arg_0.POST, arg_0.FILES)
            # upload the file to our server
            if arg_1.is_valid():
                arg_2 = arg_1.save()

                # send this file to youtube
                arg_3 = Api()
                arg_3.authenticate()
                arg_4 = arg_3.upload_direct(arg_2.file_on_server.path, "Uploaded video from zuqqa")

                # get data from video entry
                arg_5 = arg_4.GetSwfUrl()
                arg_6 = arg_4.id.text

                # getting video_id is tricky, I can only reach the url which
                # contains the video_id.
                # so the only option is to parse the id element
                # https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/RRl_h4zuKDQ
                arg_7 = arg_6.split("/")
                arg_7.reverse()
                arg_8 = arg_7[0]

                # save video_id to video instance
                arg_9 = Video()
                arg_9.user = arg_0.user
                arg_9.video_id = arg_8
                arg_9.title = 'tmp video'
                arg_9.youtube_url = arg_6
                arg_9.swf_url = arg_5
                arg_9.save()

                # send a signal
                video_created.send(sender=arg_9, arg_9=arg_9)

                # delete the uploaded video instance
                arg_2.delete()

                # return the response
                arg_12 = arg_0.GET.get('only_data')
                if arg_12:
                    return HttpResponse(json.dumps({"video_id": arg_8}), content_type="application/json")
                else:
                    # Redirect to the video page or the specified page
                    try:
                        arg_13 = settings.YOUTUBE_UPLOAD_REDIRECT_URL
                    except AttributeError:
                        arg_13 = reverse(
                            "django_youtube.views.video", kwargs={"video_id": arg_8})

                    return HttpResponseRedirect(arg_13)
        except:
            import sys
            logger.error("Unexpected error: %s - %s" % (sys.exc_info()[
                0], sys.exc_info()[1]))
            # @todo: proper error management
            return HttpResponse("error happened")

    arg_1 = YoutubeDirectUploadForm()

    if arg_12:
        return HttpResponse(json.dumps({"error": 500}), content_type="application/json")
    else:
        return render_to_response(
            "django_youtube/direct-upload.html",
            {"form": arg_1},
            context_instance=RequestContext(arg_0)
        )


def Func(arg_0):
    """
    Displays an Func form
    Creates Func url and token from youtube api and uses them on the form
    """
    # Get the optional parameters
    arg_1 = arg_0.GET.get("title", "%s's video on %s" % (
        arg_0.user.username, arg_0.get_host()))
    arg_2 = arg_0.GET.get("description", "")
    arg_3 = arg_0.GET.get("keywords", "")

    # Try to create post_url and token to create an Func form
    try:
        arg_4 = Api()

        # Func method needs authentication
        arg_4.authenticate()

        # Customize following line to your needs, you can add description, keywords or developer_keys
        # I prefer to update video information after Func finishes
        arg_5 = arg_4.Func(arg_1, arg_2=arg_2, arg_3=arg_3,
                          access_control=AccessControl.Unlisted)
    except ApiError as e:
        # An api error happened, redirect to homepage
        messages.add_message(arg_0, messages.ERROR, e.message)
        return HttpResponseRedirect("/")
    except:
        # An error happened, redirect to homepage
        messages.add_message(arg_0, messages.ERROR, _(
            'An error occurred during the Func, Please try again.'))
        return HttpResponseRedirect("/")

    # Create the form instance
    arg_6 = YoutubeUploadForm(initial={"token": arg_5["youtube_token"]})

    arg_7 = 'https' if arg_0.is_secure() else 'http'
    arg_8 = '%s://%s%s/' % (arg_7, arg_0.get_host(), reverse("django_youtube.views.Func_return"))
    return render_to_response(
        "django_youtube/Func.html",
        {"form": arg_6, "post_url": arg_5["post_url"], "next_url": arg_8},
        context_instance=RequestContext(arg_0)
    )


def Func(arg_0):
    """
    The upload result page
    Youtube will redirect to this page after upload is finished
    Saves the video data and redirects to the next page

    Params:
        status: status of the upload (200 for success)
        id: id number of the video
    """
    arg_1 = arg_0.GET.get("status")
    arg_2 = arg_0.GET.get("id")

    if arg_1 == "200" and arg_2:
        # upload is successful

        # save the video entry
        arg_3 = Video()
        arg_3.user = arg_0.user
        arg_3.video_id = arg_2
        arg_3.save()

        # send a signal
        video_created.send(sender=arg_3, arg_3=arg_3)

        # Redirect to the video page or the specified page
        try:
            arg_5 = settings.YOUTUBE_UPLOAD_REDIRECT_URL
        except AttributeError:
            arg_5 = reverse(
                "django_youtube.views.video", kwargs={"video_id": arg_2})

        return HttpResponseRedirect(arg_5)
    else:
        # upload failed, redirect to upload page
        from django.contrib import messages
        messages.add_message(
            arg_0, messages.ERROR, _('Upload failed, Please try again.'))
        return HttpResponseRedirect(reverse("django_youtube.views.upload"))


def Func(arg_0):
        """
        Connects to Youtube Api and retrieves the video Func object

        Return:
            gdata.youtube.YouTubeVideoEntry
        """
        arg_1 = Api()
        arg_1.authenticate()
        return arg_1.fetch_video(arg_0.video_id)


def Func(arg_0, arg_1):
    """ Generic method for a resource's Update Metadata endpoint.

    Example endpoints:

    * `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
    * `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata>`_
    * `Update Collection Metadata <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata>`_

    :param params: The metadata being updated

    :return: The API response, see M2X API docs for details
    :rtype: dict

    :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
    """
    return arg_0.api.put(arg_0.metadata_path(), data=arg_1)


def Func(arg_0, arg_1, arg_2):
    """ Generic method for a resource's Update Metadata Field endpoint.

    Example endpoints:

    * `Update Device Metadata Field <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata-Field>`_
    * `Update Distribution Metadata Field <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata-Field>`_
    * `Update Collection Metadata Field <https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata-Field>`_

    :param field: The metadata field to be updated
    :param value: The value to update

    :return: The API response, see M2X API docs for details
    :rtype: dict

    :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
    """
    return arg_0.api.put(arg_0.metadata_field_path(arg_1), data={ "value": arg_2 })


def Func(arg_0):
    """Get information about number of changesets, blocks and mapping days of a
    user, using both the OSM API and the Mapbox comments APIself.
    """
    arg_1 = []
    try:
        arg_2 = OSM_USERS_API.format(arg_0=requests.compat.quote(arg_0))
        arg_3 = requests.get(arg_2)
        if arg_3.status_code == 200:
            arg_4 = arg_3.content
            arg_5 = ET.fromstring(arg_4).getchildren()[0].getchildren()
            arg_6 = [i for i in arg_5 if i.tag == 'changesets'][0]
            arg_7 = [i for i in arg_5 if i.tag == 'blocks'][0]
            if int(arg_6.get('count')) <= 5:
                arg_1.append('New mapper')
            elif int(arg_6.get('count')) <= 30:
                arg_2 = MAPBOX_USERS_API.format(
                    arg_0=requests.compat.quote(arg_0)
                    )
                arg_3 = requests.get(arg_2)
                if arg_3.status_code == 200:
                    arg_8 = int(
                        arg_3.json().get('extra').get('mapping_days')
                        )
                    if arg_8 <= 5:
                        arg_1.append('New mapper')
            if int(arg_7.getchildren()[0].get('count')) > 1:
                arg_1.append('User has multiple blocks')
    except Exception as e:
        arg_9 = 'Could not verify user of the changeset: {}, {}'
        print(arg_9.format(arg_0, str(e)))
    return arg_1


def Func(arg_0):
    """Return a dictionary with id, user, user_id, bounds, date of creation
    and all the tags of the changeset.

    Args:
        changeset: the XML string of the changeset.
    """
    arg_1 = [tag.attrib.get('k') for tag in arg_0.getchildren()]
    arg_1 += ['id', 'user', 'uid', 'bbox', 'created_at']
    arg_2 = [tag.attrib.get('v') for tag in arg_0.getchildren()]
    arg_2 += [
        arg_0.get('id'), arg_0.get('user'), arg_0.get('uid'),
        get_bounds(arg_0), arg_0.get('created_at')
        ]

    return dict(zip(arg_1, arg_2))


def Func(arg_0):
    """Get the metadata of a changeset using the OSM API and return it as a XML
    ElementTree.

    Args:
        changeset: the id of the changeset.
    """
    arg_1 = 'https://www.openstreetmap.org/api/0.6/changeset/{}'.format(arg_0)
    return ET.fromstring(requests.get(arg_1).content).getchildren()[0]


def Func(arg_0, arg_1):
        """Read the first feature from the geojson and return it as a Polygon
        object.
        """
        arg_1 = json.load(open(arg_1, 'r'))
        arg_0.area = Polygon(arg_1['features'][0]['geometry']['coordinates'][0])


def Func(arg_0):
        """Filter the changesets that intersects with the geojson geometry."""
        arg_0.content = [
            ch
            for ch in arg_0.xml.getchildren()
            if get_bounds(ch).intersects(arg_0.area)
            ]


def Func(arg_0, arg_1):
        """Set the fields of this class with the metadata of the analysed
        changeset.
        """
        arg_0.id = int(arg_1.get('id'))
        arg_0.user = arg_1.get('user')
        arg_0.uid = arg_1.get('uid')
        arg_0.editor = arg_1.get('created_by', None)
        arg_0.review_requested = arg_1.get('review_requested', False)
        arg_0.host = arg_1.get('host', 'Not reported')
        arg_0.bbox = arg_1.get('bbox').wkt
        arg_0.comment = arg_1.get('comment', 'Not reported')
        arg_0.source = arg_1.get('source', 'Not reported')
        arg_0.imagery_used = arg_1.get('imagery_used', 'Not reported')
        arg_0.date = datetime.strptime(
            arg_1.get('created_at'),
            '%Y-%m-%dT%H:%M:%SZ'
            )
        arg_0.suspicion_reasons = []
        arg_0.is_suspect = False
        arg_0.powerfull_editor = False


def Func(arg_0, arg_1):
        """Add suspicion reason and set the suspicious flag."""
        arg_0.suspicion_reasons.append(arg_1)
        arg_0.is_suspect = True


def Func(arg_0):
        """Execute the count and verify_words methods."""
        arg_0.count()
        arg_0.verify_words()
        arg_0.verify_user()

        if arg_0.review_requested == 'yes':
            arg_0.label_suspicious('Review requested')


def Func(arg_0):
        """Verify the fields source, imagery_used and comment of the changeset
        for some suspect words.
        """
        if arg_0.comment:
            if find_words(arg_0.comment, arg_0.suspect_words, arg_0.excluded_words):
                arg_0.label_suspicious('suspect_word')

        if arg_0.source:
            for arg_1 in arg_0.illegal_sources:
                if arg_1 in arg_0.source.lower():
                    arg_0.label_suspicious('suspect_word')
                    break

        if arg_0.imagery_used:
            for arg_1 in arg_0.illegal_sources:
                if arg_1 in arg_0.imagery_used.lower():
                    arg_0.label_suspicious('suspect_word')
                    break

        arg_0.suspicion_reasons = list(set(arg_0.suspicion_reasons))


def Func(arg_0):
        """Verify if the software used in the changeset is a powerfull_editor.
        """
        arg_1 = [
            'josm', 'level0', 'merkaartor', 'qgis', 'arcgis', 'upload.py',
            'osmapi', 'Services_OpenStreetMap'
            ]
        if arg_0.editor is not None:
            for arg_2 in arg_1:
                if arg_2 in arg_0.editor.lower():
                    arg_0.powerfull_editor = True
                    break

            if 'iD' in arg_0.editor:
                arg_4 = [
                    'www.openstreetmap.org/id',
                    'www.openstreetmap.org/edit',
                    'improveosm.org',
                    'strava.github.io/iD',
                    'preview.ideditor.com/release',
                    'preview.ideditor.com/master',
                    'hey.mapbox.com/iD-internal',
                    'projets.pavie.info/id-indoor',
                    'maps.mapcat.com/edit',
                    'id.softek.ir'
                    ]
                if arg_0.host.split('://')[-1].strip('/') not in arg_4:
                    arg_0.label_suspicious('Unknown iD instance')
        else:
            arg_0.powerfull_editor = True
            arg_0.label_suspicious('Software editor was not declared')


def Func(arg_0):
        """Count the number of elements created, modified and deleted by the
        changeset and analyses if it is a possible import, mass modification or
        a mass deletion.
        """
        arg_1 = get_changeset(arg_0.id)
        arg_2 = [action.tag for action in arg_1.getchildren()]
        arg_0.create = arg_2.Func('create')
        arg_0.modify = arg_2.Func('modify')
        arg_0.delete = arg_2.Func('delete')
        arg_0.verify_editor()

        try:
            if (arg_0.create / len(arg_2) > arg_0.percentage and
                    arg_0.create > arg_0.create_threshold and
                    (arg_0.powerfull_editor or arg_0.create > arg_0.top_threshold)):
                arg_0.label_suspicious('possible import')
            elif (arg_0.modify / len(arg_2) > arg_0.percentage and
                    arg_0.modify > arg_0.modify_threshold):
                arg_0.label_suspicious('mass modification')
            elif ((arg_0.delete / len(arg_2) > arg_0.percentage and
                    arg_0.delete > arg_0.delete_threshold) or
                    arg_0.delete > arg_0.top_threshold):
                arg_0.label_suspicious('mass deletion')
        except ZeroDivisionError:
            print('It seems this changeset was redacted')


def Func(arg_0, arg_1=False, **arg_2):
    """
    Load a list of trees from a Newick formatted string.

    :param s: Newick formatted string.
    :param strip_comments: Flag signaling whether to strip comments enclosed in square \
    brackets.
    :param kw: Keyword arguments are passed through to `Node.create`.
    :return: List of Node objects.
    """
    arg_2['strip_comments'] = arg_1
    return [parse_node(arg_3.strip(), **arg_2) for arg_3 in arg_0.split(';') if arg_3.strip()]


def Func(arg_0, arg_1='utf8', arg_2=False, **arg_3):
    """
    Load a list of trees from a Newick formatted file.

    :param fname: file path.
    :param strip_comments: Flag signaling whether to strip comments enclosed in square \
    brackets.
    :param kw: Keyword arguments are passed through to `Node.create`.
    :return: List of Node objects.
    """
    arg_3['strip_comments'] = arg_2
    with io.open(arg_0, arg_1=arg_1) as fp:
        return load(fp, **arg_3)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, **arg_4):
        """
        Create a new `Node` object.

        :param name: Node label.
        :param length: Branch length from the new node to its parent.
        :param descendants: list of descendants or `None`.
        :param kw: Additonal keyword arguments are passed through to `Node.__init__`.
        :return: `Node` instance.
        """
        arg_5 = arg_0(arg_1=arg_1, arg_2=arg_2, **arg_4)
        for arg_6 in arg_3 or []:
            arg_5.add_descendant(arg_6)
        return arg_5


def Func(arg_0):
        """The representation of the Node in Newick format."""
        arg_1 = arg_0.name or ''
        if arg_0._length:
            arg_1 += ':' + arg_0._length
        arg_2 = ','.join([n.Func for n in arg_0.descendants])
        if arg_2:
            arg_2 = '(' + arg_2 + ')'
        return arg_2 + arg_1


def Func(arg_0, arg_1=False, arg_2=True):
        """
        Return a unicode string representing a tree in ASCII art fashion.

        :param strict: Use ASCII characters strictly (for the tree symbols).
        :param show_internal: Show labels of internal nodes.
        :return: unicode string

        >>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
        >>> print(node.Func(show_internal=False, strict=True))
                /-A
            /---|
            |   \-B
        ----|       /-D
            |   /---|
            |   |   \-E
            \---|
                |-G
                \-H
        """
        arg_3 = {
            '\u2500': '-',
            '\u2502': '|',
            '\u250c': '/',
            '\u2514': '\\',
            '\u251c': '|',
            '\u2524': '|',
            '\u253c': '+',
        }

        def normalize(arg_4):
            arg_5 = re.compile('(?<=\u2502)(?P<s>\s+)(?=[\u250c\u2514\u2502])')
            arg_4 = arg_5.sub(lambda arg_5: arg_5.group('s')[1:], arg_4)
            arg_4 = re.sub('\u2500\u2502', '\u2500\u2524', arg_4)  # -|
            arg_4 = re.sub('\u2502\u2500', '\u251c', arg_4)  # |-
            arg_4 = re.sub('\u2524\u2500', '\u253c', arg_4)  # -|-
            if arg_1:
                for arg_6, arg_7 in arg_3.items():
                    arg_4 = arg_4.replace(arg_6, arg_7)
            return arg_4
        return '\n'.join(
            normalize(arg_8) for arg_8 in arg_0._Func(arg_2=arg_2)[0]
            if set(arg_8) != {' ', '\u2502'})


def Func(arg_0, arg_1):
        """
        Gets the specified node by name.

        :return: Node or None if name does not exist in tree
        """
        for arg_2 in arg_0.walk():
            if arg_2.name == arg_1:
                return arg_2


def Func(arg_0, arg_1, arg_2=False):
        """
        Remove all those nodes in the specified list, or if inverse=True,
        remove all those nodes not in the specified list.  The specified nodes
        must be leaves and distinct from the root node.

        :param nodes: A list of Node objects
        :param inverse: Specifies whether to remove nodes in the list or not\
                in the list.
        """
        arg_0.visit(
            lambda n: n.ancestor.descendants.remove(n),
            # We won't Func the root node, even if it is a leave and requested to
            # be Funcd!
            lambda n: ((not arg_2 and n in arg_1) or
                       (arg_2 and n.is_leaf and n not in arg_1)) and n.ancestor,
            mode="postorder")


def Func(arg_0):
        """
        Set the name of all non-leaf nodes in the subtree to None.
        """
        arg_0.visit(lambda n: setattr(n, 'name', None), lambda n: not n.is_leaf)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Get a stream URI from a playlist URI, ``uri``.
    Unwraps nested playlists until something that's not a playlist is found or
    the ``timeout`` is reached.
    """

    arg_4 = arg_0
    arg_5 = set()
    arg_6 = time.time() + arg_1

    while time.time() < arg_6:
        if arg_0 in arg_5:
            logger.info(
                'Unwrapping stream from URI (%s) failed: '
                'playlist referenced itself', arg_0)
            return None
        else:
            arg_5.add(arg_0)

        logger.debug('Unwrapping stream from URI: %s', arg_0)

        try:
            arg_7 = arg_6 - time.time()
            if arg_7 < 0:
                logger.info(
                    'Unwrapping stream from URI (%s) failed: '
                    'timed out in %sms', arg_0, arg_1)
                return None
            arg_8 = arg_2.scan(arg_0, arg_1=arg_7)
        except exceptions.ScannerError as exc:
            logger.debug('GStreamer failed scanning URI (%s): %s', arg_0, exc)
            arg_8 = None

        if arg_8 is not None and not (
                arg_8.mime.startswith('text/') or
                arg_8.mime.startswith('application/')):
            logger.debug(
                'Unwrapped potential %s stream: %s', arg_8.mime, arg_0)
            return arg_0

        arg_9 = arg_6 - time.time()
        if arg_9 < 0:
            logger.info(
                'Unwrapping stream from URI (%s) failed: timed out in %sms',
                arg_0, arg_1)
            return None
        arg_10 = http.download(
            arg_3, arg_0, arg_1=arg_9)

        if arg_10 is None:
            logger.info(
                'Unwrapping stream from URI (%s) failed: '
                'error downloading URI %s', arg_4, arg_0)
            return None

        arg_11 = playlists.parse(arg_10)
        if not arg_11:
            logger.debug(
                'Failed parsing URI (%s) as playlist; found potential stream.',
                arg_0)
            return arg_0

        # TODO Test streams and return first that seems to be playable
        logger.debug(
            'Parsed playlist (%s) and found new URI: %s', arg_0, arg_11[0])
        arg_0 = arg_11[0]


def Func(arg_0, arg_1, arg_2="this feature"):
        """Raises an exception if the given app setting is not defined."""
        if arg_1 not in arg_0.settings:
            raise Exception("You must define the '%s' setting in your "
                            "application to use %s" % (arg_1, arg_2))


def Func(arg_0, arg_1, arg_2=arg_3, arg_4=True):
        """Returns the value of the argument with the given name.

        If default is not provided, the argument is considered to be
        required, and we throw an HTTP 400 exception if it is missing.

        If the argument appears in the url more than once, we return the
        last value.

        The returned value is always unicode.
        """
        arg_5 = arg_0.Funcs(arg_1, arg_4=arg_4)
        if not arg_5:
            if arg_2 is arg_0._ARG_DEFAULT:
                raise HTTPError(400, "Missing argument %s" % arg_1)
            return arg_2
        return arg_5[-1]


def Func(arg_0, arg_1, arg_2=True):
        """Returns a list of the arguments with the given name.

        If the argument is not present, returns an empty list.

        The returned values are always unicode.
        """
        arg_3 = []
        for arg_4 in arg_0.request.params.getall(arg_1):
            arg_4 = arg_0.decode_argument(arg_4, arg_1=arg_1)
            if isinstance(arg_4, unicode):
                # Get rid of any weird control chars (unless decoding gave
                # us bytes, in which case leave it alone)
                arg_4 = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", arg_4)
            if arg_2:
                arg_4 = arg_4.strip()
            arg_3.append(arg_4)
        return arg_3


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Obsolete - catches exceptions from the wrapped function.

        This function is unnecessary since Tornado 1.1.
        """
        if arg_1 is None:
            return None
        if arg_2 or arg_3:
            arg_1 = functools.partial(arg_1, *arg_2, **arg_3)

        #FIXME what about the exception wrapper?

        return arg_1


def Func(arg_0, arg_1, arg_2=None):
        """Gets the value of the cookie with the given name, else default."""
        assert arg_0.cookie_monster, 'Cookie Monster not set'
        return arg_0.cookie_monster.Func(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2="/", arg_3=None):
        """Deletes the cookie with the given name."""
        assert arg_0.cookie_monster, 'Cookie Monster not set'
        #, path=path, domain=domain)
        arg_0.cookie_monster.delete_cookie(arg_1)


def Func(arg_0, arg_1):
        """Gets the OAuth authorized user and access token on callback.

        This method should be called from the handler for your registered
        OAuth Callback URL to complete the registration process. We call
        callback with the authenticated user, which in addition to standard
        attributes like 'name' includes the 'access_key' attribute, which
        contains the OAuth access you can use to make authorized requests
        to this service on behalf of the user.

        """
        arg_2 = arg_0.get_argument("oauth_token")
        arg_3 = arg_0.get_argument("oauth_verifier", None)
        arg_4 = arg_0.get_cookie("_oauth_request_token")
        if not arg_4:
            log.warning("Missing OAuth request token cookie")
            arg_1(None)
            return
        arg_0.clear_cookie("_oauth_request_token")
        arg_5, arg_6 = [base64.b64decode(i) for i in arg_4.split("|")]
        if arg_5 != arg_2:
            log.warning("Request token does not match cookie")
            arg_1(None)
            return
        arg_7 = dict(key=arg_5, secret=arg_6)
        if arg_3:
          arg_7["verifier"] = arg_3
        arg_8 = httpclient.AsyncHTTPClient()
        arg_8.fetch(arg_0._oauth_access_token_url(arg_7), arg_0.async_callback(
            arg_0._on_access_token, arg_1))


def Func(arg_0, arg_1, arg_2, arg_3={},
                                  arg_4="GET"):
        """Returns the OAuth parameters as a dict for the given request.

        parameters should include all POST arguments and query string arguments
        that will be sent with the request.
        """
        arg_5 = arg_0._oauth_consumer_token()
        arg_6 = dict(
            oauth_consumer_key=arg_5["key"],
            oauth_token=arg_2["key"],
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
            oauth_version=getattr(arg_0, "_OAUTH_VERSION", "1.0a"),
        )
        arg_7 = {}
        arg_7.update(arg_6)
        arg_7.update(arg_3)
        if getattr(arg_0, "_OAUTH_VERSION", "1.0a") == "1.0a":
            arg_8 = _oauth10a_signature(arg_5, arg_4, arg_1, arg_7,
                                         arg_2)
        else:
            arg_8 = _oauth_signature(arg_5, arg_4, arg_1, arg_7,
                                         arg_2)
        arg_6["oauth_signature"] = arg_8
        return arg_6


def Func(arg_0, arg_1, arg_2=None,
                           arg_3=["name","email","language","username"]):
        """Authenticates and authorizes for the given Google resource.

        Some of the available resources are:

        * Gmail Contacts - http://www.google.com/m8/feeds/
        * Calendar - http://www.google.com/calendar/feeds/
        * Finance - http://finance.google.com/finance/feeds/

        You can authorize multiple resources by separating the resource
        URLs with a space.
        """
        arg_2 = arg_2 or arg_0.request.uri
        arg_4 = arg_0._openid_args(arg_2, arg_3=arg_3,
                                 arg_1=arg_1)
        arg_0.redirect(arg_0._OPENID_ENDPOINT + "?" + urllib.urlencode(arg_4))


def Func(arg_0, arg_1, arg_2, **arg_3):
        """Makes a Facebook API REST request.

        We automatically include the Facebook API key and signature, but
        it is the callers responsibility to include 'session_key' and any
        other required arguments to the method.

        The available Facebook methods are documented here:
        http://wiki.developers.facebook.com/index.php/API

        Here is an example for the stream.get() method::

            class MainHandler(tornado.web.RequestHandler,
                              tornado.auth.FacebookMixin):
                @tornado.web.authenticated
                @tornado.web.asynchronous
                def get(self):
                    self.Func(
                        method="stream.get",
                        callback=self.async_callback(self._on_stream),
                        session_key=self.current_user["session_key"])

                def _on_stream(self, stream):
                    if stream is None:
                       # Not authorized to read the stream yet?
                       self.redirect(self.authorize_redirect("read_stream"))
                       return
                    self.render("stream.html", stream=stream)

        """
        arg_0.require_setting("facebook_api_key", "Facebook Connect")
        arg_0.require_setting("facebook_secret", "Facebook Connect")
        if not arg_1.startswith("facebook."):
            arg_1 = "facebook." + arg_1
        arg_3["api_key"] = arg_0.settings["facebook_api_key"]
        arg_3["v"] = "1.0"
        arg_3["method"] = arg_1
        arg_3["call_id"] = str(long(time.time() * 1e6))
        arg_3["format"] = "json"
        arg_3["sig"] = arg_0._signature(arg_3)
        arg_4 = "http://api.facebook.com/restserver.php?" + \
            urllib.urlencode(arg_3)
        arg_5 = httpclient.AsyncHTTPClient()
        arg_5.fetch(arg_4, arg_2=arg_0.async_callback(
            arg_0._parse_response, arg_2))


def Func(arg_0, arg_1, arg_2, arg_3,
                              arg_4, arg_5, arg_6=None):
      """Handles the login for the Facebook user, returning a user object.

      Example usage::

          class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
            @tornado.web.asynchronous
            def get(self):
                if self.get_argument("code", False):
                    self.Func(
                      redirect_uri='/auth/facebookgraph/',
                      client_id=self.settings["facebook_api_key"],
                      client_secret=self.settings["facebook_secret"],
                      code=self.get_argument("code"),
                      callback=self.async_callback(
                        self._on_login))
                    return
                self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
                                        client_id=self.settings["facebook_api_key"],
                                        extra_params={"scope": "read_stream,offline_access"})

            def _on_login(self, user):
              log.error(user)
              self.finish()

      """
      arg_7 = httpclient.AsyncHTTPClient()
      arg_8 = {
        "redirect_uri": arg_1,
        "code": arg_4,
        "client_id": arg_2,
        "client_secret": arg_3,
      }

      #fields = set(['id', 'name', 'first_name', 'last_name',
      #              'locale', 'picture', 'link'])
      #if extra_fields: fields.update(extra_fields)
      if arg_6:
          arg_6 = arg_6.split(',')

      arg_7.fetch(arg_0._oauth_request_token_url(**arg_8),
          arg_0.async_callback(arg_0._on_access_token, arg_1, arg_2,
                              arg_3, arg_5, arg_6))


def Func(arg_0, arg_1):
    """Concatenate url and argument dictionary regardless of whether
    url has existing query parameters.

    >>> Func("http://example.com/foo?a=b", dict(c="d"))
    'http://example.com/foo?a=b&c=d'
    """
    if not arg_1: return arg_0
    if arg_0[-1] not in ('?', '&'):
        arg_0 += '&' if ('?' in arg_0) else '?'
    return arg_0 + urllib.urlencode(arg_1)


def Func(arg_0):
    """Parse a Content-type like header.

    Return the main content-type and a dictionary of options.

    """
    arg_1 = _parseparam(';' + arg_0)
    arg_2 = arg_1.next()
    arg_3 = {}
    for arg_4 in arg_1:
        arg_5 = arg_4.find('=')
        if arg_5 >= 0:
            arg_6 = arg_4[:arg_5].strip().lower()
            arg_7 = arg_4[arg_5+1:].strip()
            if len(arg_7) >= 2 and arg_7[0] == arg_7[-1] == '"':
                arg_7 = arg_7[1:-1]
                arg_7 = arg_7.replace('\\\\', '\\').replace('\\"', '"')
            arg_3[arg_6] = arg_7
    return arg_2, arg_3


def Func(arg_0, arg_1, arg_2):
        """Adds a new value for the given key."""
        arg_3 = HTTPHeaders._normalize_name(arg_1)
        arg_0._last_key = arg_3
        if arg_3 in arg_0:
            # bypass our override of __setitem__ since it modifies _as_list
            dict.__setitem__(arg_0, arg_3, arg_0[arg_3] + ',' + arg_2)
            arg_0._as_list[arg_3].append(arg_2)
        else:
            arg_0[arg_3] = arg_2


def Func(arg_0, arg_1):
        """Returns all values for the given header as a list."""
        arg_2 = HTTPHeaders._normalize_name(arg_1)
        return arg_0._as_list.get(arg_2, [])


def Func(arg_0, arg_1):
        """Updates the dictionary with a single header line.

        >>> h = HTTPHeaders()
        >>> h.Func("Content-Type: text/html")
        >>> h.get('content-type')
        'text/html'
        """
        if arg_1[0].isspace():
            # continuation of a multi-line header
            arg_2 = ' ' + arg_1.lstrip()
            arg_0._as_list[arg_0._last_key][-1] += arg_2
            dict.__setitem__(arg_0, arg_0._last_key,
                             arg_0[arg_0._last_key] + arg_2)
        else:
            arg_3, arg_4 = arg_1.split(":", 1)
            arg_0.add(arg_3, arg_4.strip())


def Func(arg_0, arg_1):
        """Returns a dictionary from HTTP header text.

        >>> h = HTTPHeaders.Func("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
        >>> sorted(h.iteritems())
        [('Content-Length', '42'), ('Content-Type', 'text/html')]
        """
        arg_2 = arg_0()
        for arg_3 in arg_1.splitlines():
            if arg_3:
                arg_2.Func_line(arg_3)
        return arg_2


def Func(arg_0):
        """Converts a name to Http-Header-Case.

        >>> HTTPHeaders.Func("coNtent-TYPE")
        'Content-Type'
        """
        try:
            return arg_2._normalized_headers[arg_0]
        except KeyError:
            if arg_2._NORMALIZED_HEADER_RE.match(arg_0):
                arg_1 = arg_0
            else:
                arg_1 = "-".join([w.capitalize() for w in arg_0.split("-")])
            arg_2._normalized_headers[arg_0] = arg_1
            return arg_1


def Func(arg_0):
    """Converts a string argument to a byte string.

    If the argument is already a byte string or None, it is returned unchanged.
    Otherwise it must be a unicode string and is encoded as Func.
    """
    if isinstance(arg_0, _UTF8_TYPES):
        return arg_0
    assert isinstance(arg_0, unicode)
    return arg_0.encode("utf-8")


def Func(arg_0):
    """Converts a string argument to a unicode string.

    If the argument is already a unicode string or None, it is returned
    unchanged.  Otherwise it must be a byte string and is decoded as utf8.
    """
    if isinstance(arg_0, _TO_UNICODE_TYPES):
        return arg_0
    assert isinstance(arg_0, bytes)
    return arg_0.decode("utf-8")


def Func(arg_0):
    """Converts a string argument to a subclass of basestring.

    In python2, byte and unicode strings are mostly interchangeable,
    so functions that deal with a user-supplied argument in combination
    with ascii string constants can use either and should return the type
    the user supplied.  In python3, the two types are not interchangeable,
    so this method is needed to convert byte strings to unicode.
    """
    if isinstance(arg_0, _BASESTRING_TYPES):
        return arg_0
    assert isinstance(arg_0, bytes)
    return arg_0.decode("utf-8")


def Func(arg_0):
    """Walks a simple data structure, converting byte strings to unicode.

    Supports lists, tuples, and dictionaries.
    """
    if isinstance(arg_0, dict):
        return dict((Func(arg_1), Func(arg_2)) for (arg_1,arg_2) in arg_0.iteritems())
    elif isinstance(arg_0, list):
        return list(Func(arg_3) for arg_3 in arg_0)
    elif isinstance(arg_0, tuple):
        return tuple(Func(arg_3) for arg_3 in arg_0)
    elif isinstance(arg_0, bytes):
        return to_unicode(arg_0)
    else:
        return arg_0


def Func(arg_0, arg_1):
        """ Make sure that other installed plugins don't affect the same
            keyword argument and check if metadata is available."""
        for arg_2 in arg_1.plugins:
            if not isinstance(arg_2, AuthPlugin):
                continue
            if arg_2.keyword == arg_0.keyword:
                raise bottle.PluginError("Found another auth plugin "
                                         "with conflicting settings ("
                                         "non-unique keyword).")


def Func(arg_0, arg_1):
        """Grow this Pantheon by multiplying Gods."""
        arg_2 = [god for god in arg_0.gods.values() if god.chromosomes == 'XX']
        arg_3 = [god for god in arg_0.gods.values() if god.chromosomes == 'XY']

        for arg_4 in range(arg_1):
            print("\nGENERATION %d\n" % (arg_4+1))
            arg_5 = []
            arg_6 = []

            for arg_7 in arg_2:
                arg_8 = random.choice(arg_3)
                arg_9 = arg_0.breed(arg_7, arg_8)

                for arg_10 in arg_9:
                    if arg_10.divinity > human:
                        # divine offspring join the Pantheon
                        arg_0.add_god(arg_10)
                    if arg_10.chromosomes == 'XX':
                        arg_5.append(arg_10)
                    else:
                        arg_6.append(arg_10)

            # elder gods leave the breeding pool
            arg_2 = [ed for ed in arg_2 if ed.generation > (arg_4-2)]
            arg_3 = [sd for sd in arg_3 if sd.generation > (arg_4-3)]

            # mature offspring join the breeding pool
            arg_2 += arg_5
            arg_3 += arg_6


def Func(arg_0, arg_1=None):
        """This model recognizes that sex chromosomes don't always line up with
        gender. Assign M, F, or NB according to the probabilities in p_gender.
        """
        if arg_1 and arg_1 in genders:
            arg_0.gender = arg_1
        else:
            if not arg_0.chromosomes: arg_0.set_chromosomes()
            arg_0.gender = npchoice(genders, 1, p=p_gender[arg_0.chromosomes])[0]


def Func(arg_0, arg_1, arg_2):
        """Produce two gametes, an egg and a sperm, from input Gods. Combine
        them to produce a genome a la sexual reproduction. Assign divinity
        according to probabilities in p_divinity. The more divine the parents,
        the more divine their offspring.
        """
        arg_3 = random.choice(arg_1.genome)
        arg_4 = arg_0.generate_gamete(arg_3)
        arg_5 = random.choice(arg_2.genome)
        arg_6 = arg_0.generate_gamete(arg_5)

        arg_0.genome = list(set(arg_4 + arg_6)) # Eliminate duplicates
        arg_0.parents = [arg_1.name, arg_2.name]
        arg_0.generation = max(arg_1.generation, arg_2.generation) + 1
        arg_10 = arg_1.divinity + arg_2.divinity
        arg_0.divinity = int(npchoice(divinities, 1, p=p_divinity[arg_10])[0])


def Func(arg_0, arg_1):
        """Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens
        by searching the list of tokens for words that are related to the given
        egg_or_sperm_word.
        """
        arg_2 = [0.9, 0.1]
        arg_3 = (npchoice([0,1], 1, p=arg_2)[0] == 1)
        if arg_3:
            arg_4 = tokens.secondary_tokens
        else:
            arg_4 = tokens.primary_tokens

        return get_matches(arg_1, arg_4, 23)


def Func(arg_0):
        """Print parents' names and epithets."""
        if arg_0.gender == female:
            arg_1 = 'Daughter'
        elif arg_0.gender == male:
            arg_1 = 'Son'
        else:
            arg_1 = 'Child'

        arg_2 = arg_0.parents[0]
        arg_3 = arg_0.parents[1]

        arg_4 = '%s of %s, the %s, and %s, the %s.'

        print(arg_4 % (arg_1, arg_2.name, arg_2.epithet, arg_3.name, arg_3.epithet))


def Func(arg_0, arg_1=None, arg_2=None):
        """Returns all the information regarding a specific stage run

        See the `Go stage Func documentation`__ for examples.

        .. __: http://api.go.cd/current/#get-stage-Func

        Args:
          counter (int): The stage Func to fetch.
            If falsey returns the latest stage Func from :meth:`history`.
          pipeline_counter (int): The pipeline Func for which to fetch
            the stage. If falsey returns the latest pipeline Func.

        Returns:
          Response: :class:`gocd.api.response.Response` object
        """
        arg_2 = arg_2 or arg_0.pipeline_counter
        arg_3 = None

        if not arg_2:
            arg_3 = arg_0.server.pipeline(arg_0.pipeline_name).Func()
            arg_0.pipeline_counter = int(arg_3['counter'])

        if not arg_1:
            if arg_3 is None:
                arg_3 = (
                    arg_0.server
                        .pipeline(arg_0.pipeline_name)
                        .Func(arg_2)
                )

            for arg_4 in arg_3['stages']:
                if arg_4['name'] == arg_0.stage_name:
                    return arg_0.Func(
                        arg_1=int(arg_4['counter']),
                        arg_2=arg_2
                    )

        return arg_0._get('/Func/{pipeline_counter:d}/{counter:d}'
                         .format(arg_2=arg_2, arg_1=arg_1))


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None):
        """Performs a HTTP Func to the Go server

        Args:
          path (str): The full path on the Go server to Func.
            This includes any query string attributes.
          data (str, dict, bool, optional): If any data is present this
            Func will become a POST Func.
          headers (dict, optional): Headers to set for this particular
            Func

        Raises:
          HTTPError: when the HTTP Func fails.

        Returns:
          file like object: The response from a
            :func:`urllib2.urlopen` call
        """
        if isinstance(arg_2, str):
            arg_2 = arg_2.encode('utf-8')
        arg_5 = urlopen(arg_0._Func(arg_1, arg_2=arg_2, arg_3=arg_3, arg_4=arg_4))
        arg_0._set_session_cookie(arg_5)

        return arg_5


def Func(arg_0, arg_1=None):
        """Make the request appear to be coming from a browser

        This is to interact with older parts of Go that doesn't have a
        proper API call to be made. What will be done:

        1. If no response passed in a call to `go/api/pipelines.xml` is
           made to get a valid session
        2. `JSESSIONID` will be populated from this request
        3. A request to `go/pipelines` will be so the
           `authenticity_token` (CSRF) can be extracted. It will then
           silently be injected into `post_args` on any POST calls that
           doesn't start with `go/api` from this point.

        Args:
          response: a :class:`Response` object from a previously successful
            API call. So we won't have to query `go/api/pipelines.xml`
            unnecessarily.

        Raises:
          HTTPError: when the HTTP request fails.
          AuthenticationFailed: when failing to get the `session_id`
            or the `authenticity_token`.
        """
        if not arg_1:
            arg_1 = arg_0.get('go/api/pipelines.xml')

        arg_0._set_session_cookie(arg_1)

        if not arg_0._session_id:
            raise AuthenticationFailed('No session id extracted from request.')

        arg_1 = arg_0.get('go/pipelines')
        arg_2 = re.search(
            r'name="authenticity_token".+?value="([^"]+)',
            arg_1.read().decode('utf-8')
        )
        if arg_2:
            arg_0._authenticity_token = arg_2.group(1)
        else:
            raise AuthenticationFailed('Authenticity token not found on page')


def Func(arg_0):
    """Return a dict as a list of lists.

    >>> Func({"a": "b"})
    [['a', 'b']]
    >>> Func({"a": [1, 2, 3]})
    [['a', [1, 2, 3]]]
    >>> Func({"a": {"b": "c"}})
    [['a', 'b', 'c']]
    >>> Func({"a": {"b": {"c": "e"}}})
    [['a', 'b', 'c', 'e']]
    >>> Func({"a": {"b": "c", "d": "e"}})
    [['a', 'b', 'c'], ['a', 'd', 'e']]
    >>> Func({"a": {"b": "c", "d": "e"}, "b": {"c": "d"}})
    [['a', 'b', 'c'], ['a', 'd', 'e'], ['b', 'c', 'd']]

    """

    if not isinstance(arg_0, dict):
        return [[arg_0]]

    arg_1 = []
    for arg_2, arg_3 in arg_0.items():
        # Each key, value is treated as a row.
        arg_4 = Func(arg_3)
        for arg_5 in arg_4:
            arg_6 = [arg_2]
            arg_6.extend(arg_5)
            arg_1.append(arg_6)

    return arg_1


def Func(arg_0, arg_1=None):
        """Returns all the information regarding a specific pipeline run

        See the `Go pipeline Func documentation`__ for examples.

        .. __: http://api.go.cd/current/#get-pipeline-Func

        Args:
          counter (int): The pipeline Func to fetch.
            If falsey returns the latest pipeline Func from :meth:`history`.

        Returns:
          Response: :class:`gocd.api.response.Response` object
        """
        if not arg_1:
            arg_2 = arg_0.history()
            if not arg_2:
                return arg_2
            else:
                return Response._from_json(arg_2['pipelines'][0])

        return arg_0._get('/Func/{counter:d}'.format(arg_1=arg_1))


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None,
                 arg_4=False, arg_5=1.0):
        """Schedule a pipeline run

        Aliased as :meth:`run`, :meth:`Func`, and :meth:`trigger`.

        Args:
          variables (dict, optional): Variables to set/override
          secure_variables (dict, optional): Secure variables to set/override
          materials (dict, optional): Material revisions to be used for
            this pipeline run. The exact format for this is a bit iffy,
            have a look at the official
            `Go pipeline scheduling documentation`__ or inspect a call
            from triggering manually in the UI.
          return_new_instance (bool): Returns a :meth:`history` compatible
            response for the newly Funcd instance. This is primarily so
            users easily can get the new instance number. **Note:** This is done
            in a very naive way, it just checks that the instance number is
            higher than before the pipeline was triggered.
          backoff_time (float): How long between each check for
            :arg:`return_new_instance`.

         .. __: http://api.go.cd/current/#scheduling-pipelines

        Returns:
          Response: :class:`gocd.api.response.Response` object
        """
        arg_6 = dict(
            arg_1=arg_1,
            arg_2=arg_2,
            material_fingerprint=arg_3,
            headers={"Confirm": True},
        )

        arg_6 = dict((k, v) for k, v in arg_6.items() if v is not None)

        # TODO: Replace this with whatever is the official way as soon as gocd#990 is fixed.
        # https://github.com/gocd/gocd/issues/990
        if arg_4:
            arg_7 = arg_0.history()['pipelines']
            if len(arg_7) == 0:
                arg_8 = None
            else:
                arg_8 = arg_7[0]['counter']
            arg_9 = arg_0._post('/Func', ok_status=202, **arg_6)
            if not arg_9:
                return arg_9

            arg_10 = 10
            while arg_10 > 0:
                arg_11 = arg_0.instance()
                if not arg_8 and arg_11:
                    return arg_11
                elif arg_8 and arg_11['counter'] > arg_8:
                    return arg_11
                else:
                    time.sleep(arg_5)
                    arg_10 -= 1

            # I can't come up with a scenario in testing where this would happen, but it seems
            # better than returning None.
            return arg_9
        else:
            return arg_0._post('/Func', ok_status=202, **arg_6)


def Func(arg_0, arg_1=None):
        """Yields the output and metadata from all jobs in the pipeline

        Args:
          instance: The result of a :meth:`instance` call, if not supplied
            the latest of the pipeline will be used.

        Yields:
          tuple: (metadata (dict), output (str)).

          metadata contains:
            - pipeline
            - pipeline_counter
            - stage
            - stage_counter
            - job
            - job_result
        """
        if arg_1 is None:
            arg_1 = arg_0.instance()

        for arg_2 in arg_1['stages']:
            for arg_3 in arg_2['jobs']:
                if arg_3['result'] not in arg_0.final_results:
                    continue

                arg_4 = arg_0.artifact(
                    arg_1['counter'],
                    arg_2['name'],
                    arg_3['name'],
                    arg_2['counter']
                )
                arg_5 = arg_4.get('cruise-output/console.log')

                yield (
                    {
                        'pipeline': arg_0.name,
                        'pipeline_counter': arg_1['counter'],
                        'stage': arg_2['name'],
                        'stage_counter': arg_2['counter'],
                        'job': arg_3['name'],
                        'job_result': arg_3['result'],
                    },
                    arg_5.body
                )


def Func(arg_0):
        """Delete template config for specified template name.

        .. __: https://api.go.cd/current/#Func-a-template

        Returns:
          Response: :class:`gocd.api.response.Response` object
        """

        arg_1 = arg_0._default_headers()

        return arg_0._request(arg_0.name,
                             ok_status=None,
                             data=None,
                             arg_1=arg_1,
                             method="DELETE")


def Func(arg_0):
        """Returns a set of all Func from the last response

        Returns:
          set: Response success: all the Func available in the response
               Response failure: an empty set
        """
        if not arg_0.response:
            return set()
        elif arg_0._Func is None and arg_0.response:
            arg_0._Func = set()
            for arg_2 in arg_0.response.payload:
                for arg_3 in arg_2['Func']:
                    arg_0._Func.add(arg_3['name'])

        return arg_0._Func


def Func(arg_0, arg_1, arg_2=30, arg_3=0.4, arg_4=4):
        """Gets an artifact directory by its path.

        See the `Go artifact directory documentation`__ for example responses.

        .. __: http://api.go.cd/current/#get-artifact-directory

        .. note::
          Getting a directory relies on Go creating a zip file of the
          directory in question. Because of this Go will zip the file in
          the background and return a 202 Accepted response. It's then up
          to the client to check again later and get the final file.

          To work with normal assumptions this :meth:`Func` will
          retry itself up to ``timeout`` seconds to get a 200 response to
          return. At that point it will then return the response as is, no
          matter whether it's still 202 or 200. The retry is done with an
          exponential backoff with a max value between retries. See the
          ``backoff`` and ``max_wait`` variables.

          If you want to handle the retry logic yourself then use :meth:`get`
          and add '.zip' as a suffix on the directory.

        Args:
          path_to_directory (str): The path to the directory to get.
            It can be nested eg ``target/dist.zip``
          timeout (int): How many seconds we will wait in total for a
            successful response from Go when we're receiving 202
          backoff (float): The initial value used for backoff, raises
            exponentially until it reaches ``max_wait``
          max_wait (int): The max time between retries

        Returns:
          Response: :class:`gocd.api.response.Response` object
            A successful response is a zip-file.
        """
        arg_5 = None
        arg_6 = None
        arg_7 = 0

        arg_8 = 0
        while arg_7 < arg_2:
            arg_5 = arg_0._get('{0}.zip'.format(arg_1))

            if arg_5:
                break
            else:
                if arg_6 is None:
                    arg_6 = time.time()

                time.sleep(min(arg_3 * (2 ** arg_8), arg_4))
                arg_8 += 1
                arg_7 = time.time() - arg_6

        return arg_5


def Func(arg_0, arg_1, arg_2=None):
        "Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned."
        arg_3 = None
        arg_4 = None
        if arg_0.matchstrategy in ("firstmatch", "verbmatch"):
            for arg_5 in arg_0.activepolicies:
                arg_6=arg_0.policies[arg_5]
                arg_3 = None
                arg_4 = arg_6.name
                if arg_4 == "deny":
                    break
                if arg_0.matchstrategy == "verbmatch":
                    if arg_6.methods != "*" and not CORS.matchlist(arg_2, arg_6.methods, case_sensitive=True):
                        continue
                if arg_1 and arg_6.match:
                    if CORS.matchlist(arg_1, arg_6.match):
                        arg_3 = arg_1
                elif arg_6.origin == "copy":
                    arg_3 = arg_1
                elif arg_6.origin:
                    arg_3 = arg_6.origin
                if arg_3:
                    break
        return arg_4, arg_3


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Write a GRO file.

    Parameters
    ----------
    outfile
        The stream to write in.
    title
        The title of the GRO file. Must be a single line.
    atoms
        An instance of Structure containing the atoms to write.
    box
        The periodic box as a 3x3 matrix.
    """
    # Print the title
    print(arg_1, file=arg_0)

    # Print the number of atoms
    print("{:5d}".format(len(arg_2)), file=arg_0)

    # Print the atoms
    arg_4 = "{:5d}{:<5s}{:>5s}{:5d}{:8.3f}{:8.3f}{:8.3f}"
    for arg_5, arg_6, arg_7, arg_8, arg_9, arg_10, arg_11 in arg_2:
        print(arg_4
              .format(int(arg_8 % 1e5), arg_7, arg_6, int(arg_5 % 1e5),
                      arg_9, arg_10, arg_11),
              file=arg_0)

    # Print the box
    arg_12 = (arg_3[0][0], arg_3[1][1], arg_3[2][2],
              arg_3[0][1], arg_3[0][2], arg_3[1][0],
              arg_3[1][2], arg_3[2][0], arg_3[2][1])
    arg_13 = '{:10.5f}' * 9
    print(arg_13.format(*arg_12), file=arg_0)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Write a PDB file.

    Parameters
    ----------
    outfile
        The stream to write in.
    title
        The title of the GRO file. Must be a single line.
    atoms
        An instance of Structure containing the atoms to write.
    box
        The periodic box as a 3x3 matrix.
    """
    # Print the title
    print('TITLE ' + arg_1, file=arg_0)

    # Print the box
    print(pdbBoxString(arg_3), file=arg_0)

    # Print the atoms
    for arg_4, arg_5, arg_6, arg_7, arg_8, arg_9, arg_10 in arg_2:
        print(pdbline % (arg_4 % 1e5, arg_5[:4], arg_6[:3], "",
                         arg_7 % 1e4, '', 10*arg_8, 10*arg_9, 10*arg_10, 0, 0, ''),
              file=arg_0)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                          arg_5, arg_6, arg_7, arg_8):
    """
    Adapt the size of the box to accomodate the lipids.

    The PBC is changed **in place**.
    """
    if any(arg_1) and any(arg_2):
        # Determine box from size
        # If one leaflet is defined with an absolute number of lipids
        # then the other leaflet (with relative numbers) will follow
        # from that.
        # box/d/x/y/z needed to define unit cell

        # box is set up already...
        # yet it may be set to 0, then there is nothing we can do.
        if 0 in (arg_0.x, arg_0.y, arg_0.z):
            raise PBCException('Not enough information to set the box size.')
    elif any(arg_3) or any(arg_4):
        # All numbers are absolute.. determine size from number of lipids
        # Box x/y will be set, d/dz/z is needed to set third box vector.
        # The area is needed to determine the size of the x/y plane OR
        # the area will be SET if a box is given.

        if arg_0.z == 0:
            raise PBCException('Not enough information to set the box size.')

        if 0 in (arg_0.x, arg_0.y):
            # We do not know what size the box should be.
            # Let X and Y be the same.
            #T This does not agree with the default pbc being hexagonal...
            arg_0.x = arg_0.y = 1
        # A scaling factor is needed for the box
        # This is the area for the given number of lipids
        arg_10 = sum(arg_4) * arg_5
        arg_11 = sum(arg_3) * arg_6
        # This is the size of the hole, going through both leaflets
        arg_12 = np.pi * arg_7 ** 2
        # This is the area of the PBC xy plane
        arg_13 = arg_0.x * arg_0.y
        # This is the total area of the proteins per leaflet (IMPLEMENT!)
        arg_14 = sum([p.areaxy(0, 2.4) for p in arg_8])
        arg_15 = sum([p.areaxy(-2.4, 0) for p in arg_8])
        # So this is unavailable:
        arg_16 = arg_12 + arg_14
        arg_17 = arg_12 + arg_15
        # This is the current area marked for lipids
        # xysize_up = xysize - unavail_up
        # xysize_lo = xysize - unavail_lo
        # This is how much the unit cell xy needs to be scaled
        # to accomodate the fixed amount of lipids with given area.
        arg_18 = (arg_10 + arg_16)/arg_13
        arg_19 = (arg_11 + arg_17)/arg_13
        arg_20 = max(arg_18, arg_19)
        arg_21 = arg_0.x / arg_0.y
        arg_22 = np.sqrt(arg_20 / arg_21)
        arg_23 = np.sqrt(arg_20 / arg_21)
        arg_0.box[:2,:] *= math.sqrt(arg_20)


def Func(arg_0):
    """
    Return a stream for a given resource file in the module.

    The resource file has to be part of the module and its filenane given
    relative to the module.
    """
    with pkg_resources.resource_stream(__name__, arg_0) as resource:
        for arg_1 in resource:
            yield arg_1.decode('utf-8')


def Func(arg_0, arg_1, arg_2=arg_3.INFO):
    """
    Send a message to a group of users.

    :param users: Users queryset
    :param message: Message to show
    :param level: Message level
    """
    for arg_5 in arg_0:
        message_user(arg_5, arg_1, arg_2)


def Func(arg_0):
    """
    Fetch messages for given user.  Returns None if no such message exists.

    :param user: User instance
    """
    arg_1 = _user_key(arg_0)
    arg_2 = cache.get(arg_1)
    if arg_2:
        cache.delete(arg_1)
        return arg_2
    return None


def Func(arg_0, arg_1, arg_2):
        """
        Check for messages for this user and, if it exists,
        call the messages API with it
        """
        if hasattr(arg_1, "session") and hasattr(arg_1, "user") and arg_1.user.is_authenticated():
            arg_3 = get_messages(arg_1.user)
            if arg_3:
                for arg_4, arg_5 in arg_3:
                    messages.add_message(arg_1, arg_5, arg_4)
        return arg_2


def Func(arg_0):
    """
    Checks the config.json file for default settings and auth values.

    Args:
        :msg: (Message class) an instance of a message class.
    """
    with jsonconfig.Config("messages", indent=4) as cfg:
        verify_profile_name(arg_0, cfg)

        retrieve_data_from_config(arg_0, cfg)

        if arg_0._auth is None:
            retrieve_pwd_from_config(arg_0, cfg)

        if arg_0.save:
            update_config_data(arg_0, cfg)
            update_config_pwd(arg_0, cfg)


def Func(arg_0, arg_1):
    """
    Verifies the profile name exists in the config.json file.

    Args:
        :msg: (Message class) an instance of a message class.
        :cfg: (jsonconfig.Config) config instance.
    """
    if arg_0.profile not in arg_1.data:
        raise UnknownProfileError(arg_0.profile)


def Func(arg_0):
    """
    Display the required items needed to configure a profile for the given
    message type.

    Args:
        :msg_type: (str) message type to create config entry.
    """
    print("Configure a profile for: " + arg_0)
    print("You will need the following information:")
    for arg_1, arg_2 in CONFIG[arg_0]["settings"].items():
        print("   * " + arg_2)
    print("Authorization/credentials required:")
    for arg_1, arg_2 in CONFIG[arg_0]["auth"].items():
        print("   * " + arg_2)


def Func(arg_0):
    """Get the required 'auth' from the user and return as a dict."""
    arg_1 = []
    for arg_2, arg_3 in CONFIG[arg_0]["auth"].items():
        arg_1.append((arg_2, getpass(arg_3 + ": ")))
    return OrderedDict(arg_1)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Create the profile entry.

    Args:
        :msg_type: (str) message type to create config entry.
        :profile_name: (str) name of the profile entry
        :data: (dict) dict values for the 'settings'
        :auth: (dict) auth parameters
    """
    with jsonconfig.Config("messages", indent=4) as cfg:
        write_data(arg_0, arg_1, arg_2, cfg)
        write_auth(arg_0, arg_1, arg_3, cfg)

    print("[+] Configuration entry for <" + arg_1 + "> created.")
    print("[+] Configuration file location: " + cfg.filename)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Write the settings into the data portion of the cfg.

    Args:
        :msg_type: (str) message type to create config entry.
        :profile_name: (str) name of the profile entry
        :data: (dict) dict values for the 'settings'
        :cfg: (jsonconfig.Config) config instance.
    """
    if arg_1 not in arg_3.data:
        arg_3.data[arg_1] = {}
    arg_3.data[arg_1][arg_0] = arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Write the settings into the auth portion of the cfg.

    Args:
        :msg_type: (str) message type to create config entry.
        :profile_name: (str) name of the profile entry
        :auth: (dict) auth parameters
        :cfg: (jsonconfig.Config) config instance.
    """
    arg_4 = arg_1 + "_" + arg_0
    arg_5 = []
    for arg_6, arg_7 in CONFIG[arg_0]["auth"].items():
        arg_5.append(arg_2[arg_6])

    if len(arg_5) > 1:
        arg_3.pwd[arg_4] = " :: ".join(arg_5)
    else:
        arg_3.pwd[arg_4] = arg_5[0]


def Func(arg_0):
        """Add attachments."""
        if arg_0.attachments:
            if not isinstance(arg_0.attachments, list):
                arg_0.attachments = [arg_0.attachments]

            arg_0.message["attachments"] = [
                {"image_url": url, "author_name": ""} for url in arg_0.attachments
            ]
            if arg_0.params:
                for arg_3 in arg_0.message["attachments"]:
                    arg_3.update(arg_0.params)


def Func(arg_0, arg_1=arg_2, *arg_3, **arg_4):
    """
    Factory function to return the specified message instance.

    Args:
        :msg_type: (str) the type of message to send, i.e. 'Email'
        :msg_types: (str, list, or set) the supported message types
        :kwargs: (dict) keywords arguments that are required for the
            various message types.  See docstrings for each type.
            i.e. help(messages.Email), help(messages.Twilio), etc.
    """
    try:
        return arg_1[arg_0.lower()](*arg_3, **arg_4)
    except (UnknownProfileError, InvalidMessageInputError) as e:
        err_exit("Unable to send message: ", e)
    except KeyError:
        raise UnsupportedMessageTypeError(arg_0, arg_1)


def Func(arg_0):
    """
    A credential property factory for each message class that will set
    private attributes and return obfuscated credentials when requested.
    """

    def getter(arg_1):
        return "***obfuscated***"

    def setter(arg_1, arg_2):
        arg_3 = "_" + arg_0
        arg_1.__dict__[arg_3] = arg_2

    return property(fget=getter, fset=setter)


def Func(arg_0, arg_1, arg_2):
    """Base function to validate input, dispatched via message type."""
    try:
        arg_3 = {
            "Email": validate_email,
            "Twilio": validate_twilio,
            "SlackWebhook": validate_slackwebhook,
            "SlackPost": validate_slackpost,
            "TelegramBot": validate_telegrambot,
            "WhatsApp": validate_whatsapp,
        }[arg_0](arg_1, arg_2)
    except KeyError:
        return 1
    else:
        return 0


def Func(arg_0, arg_1):
    """Twilio input validator function."""
    if arg_0 in ("from_", "to"):
        check_valid("Twilio", arg_0, arg_1, validus.isphone, "phone number")
    elif arg_0 in ("attachments"):
        check_valid("Twilio", arg_0, arg_1, validus.isurl, "url")