text:
"""Ordering Points To Identify the Clustering Structure (OPTICS)

These routines execute the OPTICS algorithm, and implement various
cluster extraction methods of the ordered list.

Authors: Shane Grigsby <refuge@rocktalus.com>
         Adrin Jalali <adrinjalali@gmail.com>
         Erich Schubert <erich@debian.org>
         Hanmin Qin <qinhanmin2005@sina.com>
License: BSD 3 clause
"""

import warnings
import numpy as np

from ..utils import check_array
from ..utils import gen_batches, get_chunk_n_rows
from ..neighbors import NearestNeighbors
from ..base import BaseEstimator, ClusterMixin
from ..metrics import pairwise_distances

class OPTICS(BaseEstimator, ClusterMixin):
    """Estimate clustering structure from vector array

    OPTICS (Ordering Points To Identify the Clustering Structure), closely
    related to DBSCAN, finds core sample of high density and expands clusters
    from them [1]_. Unlike DBSCAN, keeps cluster hierarchy for a variable
    neighborhood radius. Better suited for usage on large datasets than the
    current sklearn implementation of DBSCAN.

    Clusters are then extracted using a DBSCAN-like method
    (cluster_method = 'dbscan') or an automatic
    technique proposed in [1]_ (cluster_method = 'xi').

    This implementation deviates from the original OPTICS by first performing
    k-nearest-neighborhood searches on all points to identify core sizes, then
    computing only the distances to unprocessed points when constructing the
    cluster order. Note that we do not employ a heap to manage the expansion
    candidates, so the time complexity will be O(n^2).

    Read more in the :ref:`User Guide <optics>`.

    Parameters
    ----------
    min_samples : int > 1 or float between 0 and 1 (default=None)
        The number of samples in a neighborhood for a point to be considered as
        a core point. Also, up and down steep regions can't have more then
        ``min_samples`` consecutive non-steep points. Expressed as an absolute
        number or a fraction of the number of samples (rounded to be at least
        2).

    max_eps : float, optional (default=np.inf)
        The maximum distance between two samples for one to be considered as
        in the neighborhood of the other. Default value of ``np.inf`` will
        identify clusters across all scales; reducing ``max_eps`` will result
        in shorter run times.

    metric : string or callable, optional (default='minkowski')
        Metric to use for distance computation. Any metric from scikit-learn
        or scipy.spatial.distance can be used.

        If metric is a callable function, it is called on each
        pair of instances (rows) and the resulting value recorded. The callable
        should take two arrays as input and return one value indicating the
        distance between them. This works for Scipy's metrics, but is less
        efficient than passing the metric name as a string. If metric is
        "precomputed", X is assumed to be a distance matrix and must be square.

        Valid values for metric are:

        - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
          'manhattan']

        - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
          'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
          'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
          'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
          'yule']

        See the documentation for scipy.spatial.distance for details on these
        metrics.

    p : integer, optional (default=2)
        Parameter for the Minkowski metric from
        :class:`sklearn.metrics.pairwise_distances`. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

    metric_params : dict, optional (default=None)
        Additional keyword arguments for the metric function.

    cluster_method : string, optional (default='xi')
        The extraction method used to extract clusters using the calculated
        reachability and ordering. Possible values are "xi" and "dbscan".

    eps : float, optional (default=None)
        The maximum distance between two samples for one to be considered as
        in the neighborhood of the other. By default it assumes the same value
        as ``max_eps``.
        Used only when ``cluster_method='dbscan'``.

    xi : float, between 0 and 1, optional (default=0.05)
        Determines the minimum steepness on the reachability plot that
        constitutes a cluster boundary. For example, an upwards point in the
        reachability plot is defined by the ratio from one point to its
        successor being at most 1-xi.
        Used only when ``cluster_method='xi'``.

    predecessor_correction : bool, optional (default=True)
        Correct clusters according to the predecessors calculated by OPTICS
        [2]_. This parameter has minimal effect on most datasets.
        Used only when ``cluster_method='xi'``.

    min_cluster_size : int > 1 or float between 0 and 1 (default=None)
        Minimum number of samples in an OPTICS cluster, expressed as an
        absolute number or a fraction of the number of samples (rounded to be
        at least 2). If ``None``, the value of ``min_samples`` is used instead.
        Used only when ``cluster_method='xi'``.

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
        Algorithm used to compute the nearest neighbors:

        - 'ball_tree' will use :class:`BallTree`
        - 'kd_tree' will use :class:`KDTree`
        - 'brute' will use a brute-force search.
        - 'auto' will attempt to decide the most appropriate algorithm
          based on the values passed to :meth:`fit` method. (default)

        Note: fitting on sparse input will override the setting of
        this parameter, using brute force.

    leaf_size : int, optional (default=30)
        Leaf size passed to :class:`BallTree` or :class:`KDTree`. This can
        affect the speed of the construction and query, as well as the memory
        required to store the tree. The optimal value depends on the
        nature of the problem.

    n_jobs : int or None, optional (default=None)
        The number of parallel jobs to run for neighbors search.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    Attributes
    ----------
    labels_ : array, shape (n_samples,)
        Cluster labels for each point in the dataset given to fit().
        Noisy samples and points which are not included in a leaf cluster
        of ``cluster_hierarchy_`` are labeled as -1.

    reachability_ : array, shape (n_samples,)
        Reachability distances per sample, indexed by object order. Use
        ``clust.reachability_[clust.ordering_]`` to access in cluster order.

    ordering_ : array, shape (n_samples,)
        The cluster ordered list of sample indices.

    core_distances_ : array, shape (n_samples,)
        Distance at which each sample becomes a core point, indexed by object
        order. Points which will never be core have a distance of inf. Use
        ``clust.core_distances_[clust.ordering_]`` to access in cluster order.

    predecessor_ : array, shape (n_samples,)
        Point that a sample was reached from, indexed by object order.
        Seed points have a predecessor of -1.

    cluster_hierarchy_ : array, shape (n_clusters, 2)
        The list of clusters in the form of ``[start, end]`` in each row, with
        all indices inclusive. The clusters are ordered according to
        ``(end, -start)`` (ascending) so that larger clusters encompassing
        smaller clusters come after those smaller ones. Since ``labels_`` does
        not reflect the hierarchy, usually
        ``len(cluster_hierarchy_) > np.unique(optics.labels_)``. Please also
        note that these indices are of the ``ordering_``, i.e.
        ``X[ordering_][start:end + 1]`` form a cluster.
        Only available when ``cluster_method='xi'``.

    See also
    --------
    DBSCAN
        A similar clustering for a specified neighborhood radius (eps).
        Our implementation is optimized for runtime.

    References
    ----------
    .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel,
       and Jörg Sander. "OPTICS: ordering points to identify the clustering
       structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60.

    .. [2] Schubert, Erich, Michael Gertz.
       "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of
       the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329.
    """

    def __init__(self, min_samples=5, max_eps=np.inf, metric='minkowski', p=2,
                 metric_params=None, cluster_method='xi', eps=None, xi=0.05,
                 predecessor_correction=True, min_cluster_size=None,
                 algorithm='auto', leaf_size=30, n_jobs=None):
        self.max_eps = max_eps
        self.min_samples = min_samples
        self.min_cluster_size = min_cluster_size
        self.algorithm = algorithm
        self.metric = metric
        self.metric_params = metric_params
        self.p = p
        self.leaf_size = leaf_size
        self.cluster_method = cluster_method
        self.eps = eps
        self.xi = xi
        self.predecessor_correction = predecessor_correction
        self.n_jobs = n_jobs

    def fit(self, X, y=None):
        """Perform OPTICS clustering

        Extracts an ordered list of points and reachability distances, and
        performs initial clustering using ``max_eps`` distance specified at
        OPTICS object instantiation.

        Parameters
        ----------
        X : array, shape (n_samples, n_features), or (n_samples, n_samples)  \
if metric='precomputed'.
            A feature array, or array of distances between samples if
            metric='precomputed'.

        y : ignored

        Returns
        -------
        self : instance of OPTICS
            The instance.
        """
        X = check_array(X, dtype=np.float)

        if self.cluster_method not in ['dbscan', 'xi']:
            raise ValueError("cluster_method should be one of"
                             " 'dbscan' or 'xi' but is %s" %
                             self.cluster_method)

        (self.ordering_, self.core_distances_, self.reachability_,
         self.predecessor_) = compute_optics_graph(
             X=X, min_samples=self.min_samples, algorithm=self.algorithm,
             leaf_size=self.leaf_size, metric=self.metric,
             metric_params=self.metric_params, p=self.p, n_jobs=self.n_jobs,
             max_eps=self.max_eps)

        # Extract clusters from the calculated orders and reachability
        if self.cluster_method == 'xi':
            labels_, clusters_ = cluster_optics_xi(
                self.reachability_,
                self.predecessor_,
                self.ordering_,
                self.min_samples,
                self.min_cluster_size,
                self.xi,
                self.predecessor_correction)
            self.cluster_hierarchy_ = clusters_
        elif self.cluster_method == 'dbscan':
            if self.eps is None:
                eps = self.max_eps
            else:
                eps = self.eps

            if eps > self.max_eps:
                raise ValueError('Specify an epsilon smaller than %s. Got %s.'
                                 % (self.max_eps, eps))

            labels_ = cluster_optics_dbscan(self.reachability_,
                                            self.core_distances_,
                                            self.ordering_,
                                            eps)

        self.labels_ = labels_
        return self

def _validate_size(size, n_samples, param_name):
    if size <= 0 or (size !=
                     int(size)
                     and size > 1):
        raise ValueError('%s must be a positive integer '
                         'or a float between 0 and 1. Got %r' %
                         (param_name, size))
    elif size > n_samples:
        raise ValueError('%s must be no greater than the'
                         ' number of samples (%d). Got %d' %
                         (param_name, n_samples, size))

# OPTICS helper functions
def _compute_core_distances_(X, neighbors, min_samples, working_memory):
    """Compute the k-th nearest neighbor of each sample

    Equivalent to neighbors.kneighbors(X, self.min_samples)[0][:, -1]
    but with more memory efficiency.

    Parameters
    ----------
    X : array, shape (n_samples, n_features)
        The data.
    neighbors : NearestNeighbors instance
        The fitted nearest neighbors estimator.
    working_memory : int, optional
        The sought maximum memory for temporary distance matrix chunks.
        When None (default), the value of
        ``sklearn.get_config()['working_memory']`` is used.

    Returns
    -------
    core_distances : array, shape (n_samples,)
        Distance at which each sample becomes a core point.
        Points which will never be core have a distance of inf.
    """
    n_samples = X.shape[0]
    core_distances = np.empty(n_samples)
    core_distances.fill(np.nan)

    chunk_n_rows = get_chunk_n_rows(row_bytes=16 * min_samples,
                                    max_n_rows=n_samples,
                                    working_memory=working_memory)
    slices = gen_batches(n_samples, chunk_n_rows)
    for sl in slices:
        core_distances[sl] = neighbors.kneighbors(
            X[sl], min_samples)[0][:, -1]
    return core_distances

def compute_optics_graph(X, min_samples, max_eps, metric, p, metric_params,
                         algorithm, leaf_size, n_jobs):
    """Computes the OPTICS reachability graph.

    Read more in the :ref:`User Guide <optics>`.

    Parameters
    ----------
    X : array, shape (n_samples, n_features), or (n_samples, n_samples)  \
if metric='precomputed'.
        A feature array, or array of distances between samples if
        metric='precomputed'

    min_samples : int (default=5)
        The number of samples in a neighborhood for a point to be considered
        as a core point. Expressed as an absolute number or a fraction of the
        number of samples (rounded to be at least 2).

    max_eps : float, optional (default=np.inf)
        The maximum distance between two samples for one to be considered as
        in the neighborhood of the other. Default value of ``np.inf`` will
        identify clusters across all scales; reducing ``max_eps`` will result
        in shorter run times.

    metric : string or callable, optional (default='minkowski')
        Metric to use for distance computation. Any metric from scikit-learn
        or scipy.spatial.distance can be used.

        If metric is a callable function, it is called on each
        pair of instances (rows) and the resulting value recorded. The callable
        should take two arrays as input and return one value indicating the
        distance between them. This works for Scipy's metrics, but is less
        efficient than passing the metric name as a string. If metric is
        "precomputed", X is assumed to be a distance matrix and must be square.

        Valid values for metric are:

        - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
          'manhattan']

        - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
          'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
          'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
          'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
          'yule']

        See the documentation for scipy.spatial.distance for details on these
        metrics.

    p : integer, optional (default=2)
        Parameter for the Minkowski metric from
        :class:`sklearn.metrics.pairwise_distances`. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

    metric_params : dict, optional (default=None)
        Additional keyword arguments for the metric function.

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
        Algorithm used to compute the nearest neighbors:

        - 'ball_tree' will use :class:`BallTree`
        - 'kd_tree' will use :class:`KDTree`
        - 'brute' will use a brute-force search.
        - 'auto' will attempt to decide the most appropriate algorithm
          based on the values passed to :meth:`fit` method. (default)

        Note: fitting on sparse input will override the setting of
        this parameter, using brute force.

    leaf_size : int, optional (default=30)
        Leaf size passed to :class:`BallTree` or :class:`KDTree`. This can
        affect the speed of the construction and query, as well as the memory
        required to store the tree. The optimal value depends on the
        nature of the problem.

    n_jobs : int or None, optional (default=None)
        The number of parallel jobs to run for neighbors search.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    Returns
    -------
    ordering_ : array, shape (n_samples,)
        The cluster ordered list of sample indices.

    core_distances_ : array, shape (n_samples,)
        Distance at which each sample becomes a core point, indexed by object
        order. Points which will never be core have a distance of inf. Use
        ``clust.core_distances_[clust.ordering_]`` to access in cluster order.

    reachability_ : array, shape (n_samples,)
        Reachability distances per sample, indexed by object order. Use
        ``clust.reachability_[clust.ordering_]`` to access in cluster order.

    predecessor_ : array, shape (n_samples,)
        Point that a sample was reached from, indexed by object order.
        Seed points have a predecessor of -1.

    References
    ----------
    .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel,
       and Jörg Sander. "OPTICS: ordering points to identify the clustering
       structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60.
    """
    n_samples = X.shape[0]
    _validate_size(min_samples, n_samples, 'min_samples')
    if min_samples <= 1:
        min_samples = max(2, min_samples * n_samples)

    # Start all points as 'unprocessed' ##
    reachability_ = np.empty(n_samples)
    reachability_.fill(np.inf)
    predecessor_ = np.empty(n_samples, dtype=int)
    predecessor_.fill(-1)

    nbrs = NearestNeighbors(n_neighbors=min_samples,
                            algorithm=algorithm,
                            leaf_size=leaf_size,
                            metric=metric,
                            metric_params=metric_params,
                            p=p,
                            n_jobs=n_jobs)

    nbrs.fit(X)
    # Here we first do a kNN query for each point, this differs from
    # the original OPTICS that only used epsilon range queries.
    # TODO: handle working_memory somehow?
    core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,
                                               min_samples=min_samples,
                                               working_memory=None)
    # OPTICS puts an upper limit on these, use inf for undefined.
    core_distances_[core_distances_ > max_eps] = np.inf

    # Main OPTICS loop. Not parallelizable. The order that entries are
    # written to the 'ordering_' list is important!
    # Note that this implementation is O(n^2) theoretically, but
    # supposedly with very low constant factors.
    processed = np.zeros(X.shape[0], dtype=bool)
    ordering = np.zeros(X.shape[0], dtype=int)
    for ordering_idx in range(X.shape[0]):
        # Choose next based on smallest reachability distance
        # (And prefer smaller ids on ties, possibly np.inf!)
        index = np.where(processed == 0)[0]
        point = index[np.argmin(reachability_[index])]

        processed[point] = True
        ordering[ordering_idx] = point
        if core_distances_[point] != np.inf:
            _set_reach_dist(core_distances_=core_distances_,
                            reachability_=reachability_,
                            predecessor_=predecessor_,
                            point_index=point,
                            processed=processed, X=X, nbrs=nbrs,
                            metric=metric, metric_params=metric_params,
                            p=p, max_eps=max_eps)
    if np.all(np.isinf(reachability_)):
        warnings.warn("All reachability values are inf. Set a larger"
                      " max_eps or all data will be considered outliers.",
                      UserWarning)
    return ordering, core_distances_, reachability_, predecessor_

def _set_reach_dist(core_distances_, reachability_, predecessor_,
                    point_index, processed, X, nbrs, metric, metric_params,
                    p, max_eps):
    P = X[point_index:point_index + 1]
    # Assume that radius_neighbors is faster without distances
    # and we don't need all distances, nevertheless, this means
    # we may be doing some work twice.
    indices = nbrs.radius_neighbors(P, radius=max_eps,
                                    return_distance=False)[0]

    # Getting indices of neighbors that have not been processed
    unproc = np.compress(~np.take(processed, indices), indices)
    # Neighbors of current point are already processed.
    if not unproc.size:
        return

    # Only compute distances to unprocessed neighbors:
    if metric == 'precomputed':
        dists = X[point_index, unproc]
    else:
        _params = dict() if metric_params is None else metric_params.copy()
        if metric == 'minkowski' and 'p' not in _params:
            # the same logic as neighbors, p is ignored if explicitly set
            # in the dict params
            _params['p'] = p
        dists = pairwise_distances(P, np.take(X, unproc, axis=0),
                                   metric, n_jobs=None,
                                   **_params).ravel()

    rdists = np.maximum(dists, core_distances_[point_index])
    improved = np.where(rdists < np.take(reachability_, unproc))
    reachability_[unproc[improved]] = rdists[improved]
    predecessor_[unproc[improved]] = point_index

def cluster_optics_dbscan(reachability, core_distances, ordering, eps):
    """Performs DBSCAN extraction for an arbitrary epsilon.

    Extracting the clusters runs in linear time. Note that this results in
    ``labels_`` which are close to a `DBSCAN` with similar settings and
    ``eps``, only if ``eps`` is close to ``max_eps``.

    Parameters
    ----------
    reachability : array, shape (n_samples,)
        Reachability distances calculated by OPTICS (``reachability_``)

    core_distances : array, shape (n_samples,)
        Distances at which points become core (``core_distances_``)

    ordering : array, shape (n_samples,)
        OPTICS ordered point indices (``ordering_``)

    eps : float
        DBSCAN ``eps`` parameter. Must be set to < ``max_eps``. Results
        will be close to DBSCAN algorithm if ``eps`` and ``max_eps`` are close
        to one another.

    Returns
    -------
    labels_ : array, shape (n_samples,)
        The estimated labels.

    """
    n_samples = len(core_distances)
    labels = np.zeros(n_samples, dtype=int)

    far_reach = reachability > eps
    near_core = core_distances <= eps
    labels[ordering] = np.cumsum(far_reach[ordering] & near_core[ordering]) - 1
    labels[far_reach & ~near_core] = -1
    return labels

def cluster_optics_xi(reachability, predecessor, ordering, min_samples,
                      min_cluster_size=None, xi=0.05,
                      predecessor_correction=True):
    """Automatically extract clusters according to the Xi-steep method.

    Parameters
    ----------
    reachability : array, shape (n_samples,)
        Reachability distances calculated by OPTICS (`reachability_`)

    predecessor : array, shape (n_samples,)
        Predecessors calculated by OPTICS.

    ordering : array, shape (n_samples,)
        OPTICS ordered point indices (`ordering_`)

    min_samples : int > 1 or float between 0 and 1 (default=None)
        The same as the min_samples given to OPTICS. Up and down steep regions
        can't have more then ``min_samples`` consecutive non-steep points.
        Expressed as an absolute number or a fraction of the number of samples
        (rounded to be at least 2).

    min_cluster_size : int > 1 or float between 0 and 1 (default=None)
        Minimum number of samples in an OPTICS cluster, expressed as an
        absolute number or a fraction of the number of samples (rounded to be
        at least 2). If ``None``, the value of ``min_samples`` is used instead.

    xi : float, between 0 and 1, optional (default=0.05)
        Determines the minimum steepness on the reachability plot that
        constitutes a cluster boundary. For example, an upwards point in the
        reachability plot is defined by the ratio from one point to its
        successor being at most 1-xi.

    predecessor_correction : bool, optional (default=True)
        Correct clusters based on the calculated predecessors.

    Returns
    -------
    labels : array, shape (n_samples)
        The labels assigned to samples. Points which are not included
        in any cluster are labeled as -1.

    clusters : array, shape (n_clusters, 2)
        The list of clusters in the form of ``[start, end]`` in each row, with
        all indices inclusive. The clusters are ordered according to ``(end,
        -start)`` (ascending) so that larger clusters encompassing smaller
        clusters come after such nested smaller clusters. Since ``labels`` does
        not reflect the hierarchy, usually ``len(clusters) >
        np.unique(labels)``.
    """
    n_samples = len(reachability)
    _validate_size(min_samples, n_samples, 'min_samples')
    if min_samples <= 1:
        min_samples = max(2, min_samples * n_samples)
    if min_cluster_size is None:
        min_cluster_size = min_samples
    _validate_size(min_cluster_size, n_samples, 'min_cluster_size')
    if min_cluster_size <= 1:
        min_cluster_size = max(2, min_cluster_size * n_samples)

    clusters = _xi_cluster(reachability[ordering], predecessor[ordering],
                           ordering, xi,
                           min_samples, min_cluster_size,
                           predecessor_correction)
    labels = _extract_xi_labels(ordering, clusters)
    return labels, clusters

def _extend_region(steep_point, xward_point, start, min_samples):
    """Extend the area until it's maximal.

    It's the same function for both upward and downward reagions, depending on
    the given input parameters. Assuming:

        - steep_{upward/downward}: bool array indicating whether a point is a
          steep {upward/downward};
        - upward/downward: bool array indicating whether a point is
          upward/downward;

    To extend an upward reagion, ``steep_point=steep_upward`` and
    ``xward_point=downward`` are expected, and to extend a downward region,
    ``steep_point=steep_downward`` and ``xward_point=upward``.

    Parameters
    ----------
    steep_point : bool array, shape (n_samples)
        True if the point is steep downward (upward).

    xward_point : bool array, shape (n_samples)
        True if the point is an upward (respectively downward) point.

    start : integer
        The start of the xward region.

    min_samples : integer
       The same as the min_samples given to OPTICS. Up and down steep
       regions can't have more then ``min_samples`` consecutive non-steep
       points.

    Returns
    -------
    index : integer
        The current index iterating over all the samples, i.e. where we are up
        to in our search.

    end : integer
        The end of the region, which can be behind the index. The region
        includes the ``end`` index.
    """
    n_samples = len(steep_point)
    non_xward_points = 0
    index = start
    end = start
    # find a maximal area
    while index < n_samples:
        if steep_point[index]:
            non_xward_points = 0
            end = index
        elif not xward_point[index]:
            # it's not a steep point, but still goes up.
            non_xward_points += 1
            # region should include no more than min_samples consecutive
            # non steep xward points.
            if non_xward_points > min_samples:
                break
        else:
            return end
        index += 1
    return end

def _update_filter_sdas(sdas, mib, xi_complement, reachability_plot):
    """Update steep down areas (SDAs) using the new maximum in between (mib)
    value, and the given complement of xi, i.e. ``1 - xi``.
    """
    if np.isinf(mib):
        return []
    res = [sda for sda in sdas
           if mib <= reachability_plot[sda['start']] * xi_complement]
    for sda in res:
        sda['mib'] = max(sda['mib'], mib)
    return res

def _correct_predecessor(reachability_plot, predecessor_plot, ordering, s, e):
    """Correct for predecessors.

    Applies Algorithm 2 of [1]_.

    Input parameters are ordered by the computer OPTICS ordering.

    .. [1] Schubert, Erich, Michael Gertz.
       "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of
       the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329.
    """
    while s < e:
        if reachability_plot[s] > reachability_plot[e]:
            return s, e
        p_e = ordering[predecessor_plot[e]]
        for i in range(s, e):
            if p_e == ordering[i]:
                return s, e
        e -= 1
    return None, None

def _xi_cluster(reachability_plot, predecessor_plot, ordering, xi, min_samples,
                min_cluster_size, predecessor_correction):
    """Automatically extract clusters according to the Xi-steep method.

    This is rouphly an implementation of Figure 19 of the OPTICS paper.

    Parameters
    ----------
    reachability_plot : array, shape (n_samples)
        The reachability plot, i.e. reachability ordered according to
        the calculated ordering, all computed by OPTICS.

    predecessor_plot : array, shape (n_samples)
        Predecessors ordered according to the calculated ordering.

    xi : float, between 0 and 1
        Determines the minimum steepness on the reachability plot that
        constitutes a cluster boundary. For example, an upwards point in the
        reachability plot is defined by the ratio from one point to its
        successor being at most 1-xi.

    min_samples : int > 1 or float between 0 and 1 (default=None)
        The same as the min_samples given to OPTICS. Up and down steep regions
        can't have more then ``min_samples`` consecutive non-steep points.
        Expressed as an absolute number or a fraction of the number of samples
        (rounded to be at least 2).

    min_cluster_size : int > 1 or float between 0 and 1
        Minimum number of samples in an OPTICS cluster, expressed as an
        absolute number or a fraction of the number of samples (rounded
        to be at least 2).

    predecessor_correction : bool
        Correct clusters based on the calculated predecessors.

    Returns
    -------
    clusters : array, shape (n_clusters, 2)
        The list of clusters in the form of [start, end] in each row, with all
        indices inclusive. The clusters are ordered in a way that larger
        clusters encompassing smaller clusters come after those smaller
        clusters.
    """

    # Our implementation adds an inf to the end of reachability plot
    # this helps to find potential clusters at the end of the
    # reachability plot even if there's no upward region at the end of it.
    reachability_plot = np.hstack((reachability_plot, np.inf))

    xi_complement = 1 - xi
    sdas = []  # steep down areas, introduced in section 4.3.2 of the paper
    clusters = []
    index = 0
    mib = 0.  # maximum in between, section 4.3.2

    # Our implementation corrects a mistake in the original
    # paper, i.e., in Definition 9 steep downward point,
    # r(p) * (1 - x1) <= r(p + 1) should be
    # r(p) * (1 - x1) >= r(p + 1)
    with np.errstate(invalid='ignore'):
        ratio = reachability_plot[:-1] / reachability_plot[1:]
        steep_upward = ratio <= xi_complement
        steep_downward = ratio >= 1 / xi_complement
        downward = ratio > 1
        upward = ratio < 1

    # the following loop is is almost exactly as Figure 19 of the paper.
    # it jumps over the areas which are not either steep down or up areas
    for steep_index in iter(np.flatnonzero(steep_upward | steep_downward)):
        # just continue if steep_index has been a part of a discovered xward
        # area.
        if steep_index < index:
            continue

        mib = max(mib, np.max(reachability_plot[index:steep_index + 1]))

        # steep downward areas
        if steep_downward[steep_index]:
            sdas = _update_filter_sdas(sdas, mib, xi_complement,
                                       reachability_plot)
            D_start = steep_index
            D_end = _extend_region(steep_downward, upward,
                                   D_start, min_samples)
            D = {'start': D_start, 'end': D_end, 'mib': 0.}
            sdas.append(D)
            index = D_end + 1
            mib = reachability_plot[index]

        # steep upward areas
        else:
            sdas = _update_filter_sdas(sdas, mib, xi_complement,
                                       reachability_plot)
            U_start = steep_index
            U_end = _extend_region(steep_upward, downward, U_start,
                                   min_samples)
            index = U_end + 1
            mib = reachability_plot[index]

            U_clusters = []
            for D in sdas:
                c_start = D['start']
                c_end = U_end

                # line (**), sc2*
                if reachability_plot[c_end + 1] * xi_complement < D['mib']:
                    continue

                # Definition 11: criterion 4
                D_max = reachability_plot[D['start']]
                if D_max * xi_complement >= reachability_plot[c_end + 1]:
                    # Find the first index from the left side which is almost
                    # at the same level as the end of the detected cluster.
                    while (reachability_plot[c_start + 1] >
                           reachability_plot[c_end + 1]
                           and c_start < D['end']):
                        c_start += 1
                elif reachability_plot[c_end + 1] * xi_complement >= D_max:
                    # Find the first index from the right side which is almost
                    # at the same level as the beginning of the detected
                    # cluster.
                    # Our implementation corrects a mistake in the original
                    # paper, i.e., in Definition 11 4c, r(x) < r(sD) should be
                    # r(x) > r(sD).
                    while (reachability_plot[c_end - 1] > D_max
                           and c_end > U_start):
                        c_end -= 1

                # predecessor correction
                if predecessor_correction:
                    c_start, c_end = _correct_predecessor(reachability_plot,
                                                          predecessor_plot,
                                                          ordering,
                                                          c_start,
                                                          c_end)
                if c_start is None:
                    continue

                # Definition 11: criterion 3.a
                if c_end - c_start + 1 < min_cluster_size:
                    continue

                # Definition 11: criterion 1
                if c_start > D['end']:
                    continue

                # Definition 11: criterion 2
                if c_end < U_start:
                    continue

                U_clusters.append((c_start, c_end))

            # add smaller clusters first.
            U_clusters.reverse()
            clusters.extend(U_clusters)

    return np.array(clusters)

def _extract_xi_labels(ordering, clusters):
    """Extracts the labels from the clusters returned by `_xi_cluster`.
    We rely on the fact that clusters are stored
    with the smaller clusters coming before the larger ones.

    Parameters
    ----------
    ordering : array, shape (n_samples)
        The ordering of points calculated by OPTICS

    clusters : array, shape (n_clusters, 2)
        List of clusters i.e. (start, end) tuples,
        as returned by `_xi_cluster`.

    Returns
    -------
    labels : array, shape (n_samples)
    """

    labels = np.full(len(ordering), -1, dtype=int)
    label = 0
    for c in clusters:
        if not np.any(labels[c[0]:(c[1] + 1)] != -1):
            labels[c[0]:(c[1] + 1)] = label
            label += 1
    labels[ordering] = labels.copy()
    return labels


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using ItzWarty;

namespace Shade.Server.Accounts
{
    public class AccountServiceImpl : AccountService
    {
       private Dictionary<string, ShardAccountService> shardAccountServicesByShardId = new Dictionary<string, ShardAccountService>();

       public AccountServiceImpl(ShadeServiceLocator shadeServiceLocator, PlatformConfiguration platformConfiguration)
       {
          shadeServiceLocator.RegisterService(typeof(AccountService), this);

          foreach (var shardConfiguration in platformConfiguration.ShardConfigurations) {
             InitializeShard(shardConfiguration);
          }
       }

       private void InitializeShard(ShardConfiguration shardConfiguration)
       {
          string shardId = shardConfiguration.ShardId;
          var shardAccountService = new ShardAccountServiceImpl(shardId);
          shardAccountServicesByShardId.Add(shardId, shardAccountService);
       }

       public AccountKey CreateAccount(string shardId, string username)
       {
          var shardAccountService = shardAccountServicesByShardId.GetValueOrDefault(shardId);

          AccountKey result = null;
          if (shardAccountService != null) {
             result = shardAccountService.CreateAccount(username);
          }
          return result;
       }
    }
}

redpajama_set_name: RedPajamaGithub


text:
cask 'hewlettpackardprinterdrivers' do
  version '3.1'
  sha256 'd8b618878b1949496197e31ee4b8d36b50ad6169cc5acef8c1cb1917e6b4200b'

  url "https://support.apple.com/downloads/DL907/en_US/hpprinterdriver#{version}.dmg"
  name 'HP Printer Drivers'
  homepage 'https://support.apple.com/kb/DL907'
  license :gratis

  pkg 'HewlettPackardPrinterDrivers.pkg'

  uninstall pkgutil: [
                       'com.apple.pkg.HewlettPackardPrinterDrivers',
                       'com.apple.pkg.HewlettPackardPrinterDriversPreInstall',
                     ]
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<!--
  ~ Copyright (c) 2010-2017 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<user xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
    <name>guybrushhh</name>
    <fullName>
        <t:orig>Guybrush Threepwood</t:orig>
        <t:norm>guybrush threepwood</t:norm>
    </fullName>
    <givenName>
        <t:orig>Guybrush</t:orig>
        <t:norm>guybrush</t:norm>
    </givenName>
    <familyName>
        <t:orig>Threepwood</t:orig>
        <t:norm>threepwood</t:norm>
    </familyName>
</user>


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Web.Http.Metadata;
using System.Web.Http.Properties;
using System.Web.Http.Validation.Validators;

namespace System.Web.Http.Validation.Providers
{
    /// <summary>
    /// An implementation of <see cref="ModelValidatorProvider"/> which provides validators that throw exceptions when the model is invalid.
    /// </summary>
    public class InvalidModelValidatorProvider : AssociatedValidatorProvider
    {
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
        {
            if (metadata.ContainerType == null || String.IsNullOrEmpty(metadata.PropertyName))
            {
                // Validate that the type's fields and nonpublic properties don't have any validation attributes on them
                // Validation only runs against public properties
                Type type = metadata.ModelType;
                PropertyInfo[] nonPublicProperties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (PropertyInfo nonPublicProperty in nonPublicProperties)
                {
                    if (nonPublicProperty.GetCustomAttributes(typeof(ValidationAttribute), inherit: true).Length > 0)
                    {
                        yield return new ErrorModelValidator(validatorProviders, Error.Format(SRResources.ValidationAttributeOnNonPublicProperty, nonPublicProperty.Name, type));
                    }
                }

                FieldInfo[] allFields = metadata.ModelType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (FieldInfo field in allFields)
                {
                    if (field.GetCustomAttributes(typeof(ValidationAttribute), inherit: true).Length > 0)
                    {
                        yield return new ErrorModelValidator(validatorProviders, Error.Format(SRResources.ValidationAttributeOnField, field.Name, type));
                    }
                }
            }
            else
            {
                // Validate that value-typed properties marked as [Required] are also marked as [DataMember(IsRequired=true)]
                // Certain formatters may not recognize a member as required if it's marked as [Required] but not [DataMember(IsRequired=true)]
                // This is not a problem for reference types because [Required] will still cause a model error to be raised after a null value is deserialized
                if (metadata.ModelType.IsValueType && attributes.Any(attribute => attribute is RequiredAttribute))
                {
                    if (!DataMemberModelValidatorProvider.IsRequiredDataMember(metadata.ContainerType, attributes))
                    {
                        yield return new ErrorModelValidator(validatorProviders, Error.Format(SRResources.MissingDataMemberIsRequired, metadata.PropertyName, metadata.ContainerType));
                    }
                }
            }
        }
    }
}


text:
'use strict';
var getWindow = require('./isWindow');

module.exports = function scrollTop(node, val) {
  var win = getWindow(node);

  if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop;

  if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val;
};


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.tomasapp.maps" version="1.1.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Maps</name>
    <description>
        Test maps app.
    </description>
    <author email="tomas.navarro@gmail.com" href="http://tomasapp.com">
        tomasnama
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>


text:
<% include ../header.html %>

写日志

                返回日志列表

            <form id="uploadImg" enctype="multipart/form-data" method="post">
                选择文件
                    <input type="file" data-type = 'Img' multiple="multiple" accept="image/jpeg,image/png,image/bmp,image/gif" onchange="uploadImg(this)" data-type="normal">

            </form>
            <form id="uploadBgImg" enctype="multipart/form-data" method="post">
                选择背景图片
                    <input type="file" data-type = 'BgImg' accept="image/jpeg,image/x-png,image/png,image/pjpeg" onchange="uploadImg(this)" data-type="background">

            </form>

        <form class="blog-editor-form" method="post">

                <% if(action === 'addidle'){%>

                <input style="display: none" name="back_img" id="inputbackgroudImg">

                    <input type="text" required id="title" name="title" placeholder="标题"/>

                    <textarea rows="4" id="quote" name="quote" placeholder="简介"></textarea>

                 <textarea name="content" required id="textareacontent"></textarea>

                    标签:
                    <input class="tag_input" name='tag' id="blogtagtxt"/>

                <%}else {%>
                <input style="display: none" name="back_img"  value='<%= idle.back_img %>' id="inputbackgroudImg">

                    <input type="text" required id="title" value='<%= idle.title %>' name="title"
                           placeholder="标题"/>

                    <textarea id="quote" placeholder="简介" name="quote"><%= idle.quote %></textarea>

                    <textarea name="content" required id="textareacontent"><%= idle.content %></textarea>

                    标签:
                    <input class="tag_input" name='tag' id="idletagtxt"/>

                <%}%>

                        <button type="submit" class="btn btn-primary">发表</button>
                        <button type="button" class="btn btn-default">取消</button>

                        <button type="button" class="btn btn-default" data-type="idle" onclick="changeMd2Html(this)">预览</button>
                        <button type="button" class="btn btn-default">保存草稿</button>

        </form>

            <%=idle.content%>

<% include ../footer.html %>


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2011 - 2013   MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_FMS_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_FMS_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>

namespace boost { namespace simd { namespace tag
  {
    /*!
      @brief  fms generic tag

      Represents the fms function in generic contexts.

      @par Models:
      Hierarchy
    **/
    struct fms_ : ext::elementwise_<fms_>
    {
      /// @brief Parent hierarchy
      typedef ext::elementwise_<fms_> parent;
    };
  }

  /*!
    Computes the fused multiply-substract of three value.

    @par semantic:
    For any given value @c x,  @c y,  @c z of type @c T:

    @code
    T r = fms(x, y, z);
    @endcode

    The code is similar to:

    @code
    T r = x*y-z;
    @endcode

    @param  a0
    @param  a1
    @param  a2

    @return a value of the same type as the input.
  **/
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::fms_, fms, 3)

  /*!
    Computes the fused negated substract-multiply of three values.

    @par semantic:
    For any given value @c x,  @c y,  @c z of type @c T:

    @code
    T r = fnsm(x, y, z);
    @endcode

    The code is similar to:

    @code
    T r = -(x-y*z);
    @endcode

    @param  a0
    @param  a1
    @param  a2

    @return a value of the same type as the input.
  **/
  BOOST_DISPATCH_FUNCTION_INTERFACE(tag::fms_, fnsm, 3)
  {
    typename boost::dispatch::make_functor<tag::fms_, A0>::type callee;
    return callee(a2, a1, a0);
  }
} }

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Discella angulata Cooke

### Remarks
null


text:
package views.formdata;

import models.GlobalDbInfo;
import models.Magician;
import play.data.validation.Constraints.Email;
import play.data.validation.Constraints.MaxLength;
import play.data.validation.Constraints.MinLength;
import play.data.validation.Constraints.Required;
import play.data.validation.ValidationError;

import java.util.ArrayList;
import java.util.List;

/**
 * EditUserFormData allows for the storage of a subset of Magician data from an HTML form.
 *

 * This is a Play Framework backing class that allows for the storage of HTML Form Data input by the user (usually as
 * String data being moved in/out of Model data).
 *

 * These backing classes also contain basic input form validation for required fields, field length, etc.
 *

 * This is utilized partially at account creation, and again whenever the Magician info is updated.
 */
public class EditUserFormData {

  /**
   * Magician ID hidden field.
   */
  public long id;

  /**
   * Input data First Name field.
   */
  @Required(message = "Everybody (except Teller) has a first name.")
  @MaxLength(value = GlobalDbInfo.MAX_SHORT_TEXT_LENGTH,
      message = "Your name can't be longer than " + GlobalDbInfo.MAX_SHORT_TEXT_LENGTH + " characters.")
  public String firstName;

  /**
   * Input data Last Name field.
   */
  @Required(message = "A Last Name must be provided.")
  @MaxLength(value = GlobalDbInfo.MAX_SHORT_TEXT_LENGTH,
      message = "Your name can't be longer than " + GlobalDbInfo.MAX_SHORT_TEXT_LENGTH + " characters.")
  public String lastName;

  /**
   * Input data Email field.
   */
  @Required(message = "An Email address must be provided.")
  @Email(message = "An Email address must be provided.")
  @MaxLength(value = GlobalDbInfo.MAX_LONG_TEXT_LENGTH,
      message = "The Email address can't be longer than " + GlobalDbInfo.MAX_LONG_TEXT_LENGTH + " characters.")
  public String email;

  /**
   * Input data MagicianType selector; stored as a string from the selectbox.
   */
  @Required(message = "How would you identify yourself as a magician?  Please select from the list.")
  public String magicianType;

  /**
   * Input data Password field.
   */
  @Required(message = "You need to have a password.")
  @MaxLength(value = GlobalDbInfo.MAX_LONG_TEXT_LENGTH,
      message = "Your password can't be longer than " + GlobalDbInfo.MAX_SHORT_TEXT_LENGTH + " characters.")
  @MinLength(value = GlobalDbInfo.MIN_PASSWORD_LENGTH,
      message = "The password must be at least " + GlobalDbInfo.MIN_PASSWORD_LENGTH + " characters.")
  public String password;

  /**
   * Default no-arg constructor required by Play.
   */
  public EditUserFormData() {
    // No content.
  }

  /**
   * Constructor that builds the EditUserFormData object from a provided Magician.
   *
   * @param magician The Magician object passed to the constructor.
   */
  public EditUserFormData(Magician magician) {
    this.id = magician.getId();
    this.firstName = magician.getFirstName();
    this.lastName = magician.getLastName();
    this.email = magician.getEmail();
    this.magicianType = magician.getMagicianType().getName();
    this.password = magician.getPassword();
  }

  /**
   * Enforce special user interface validation rules for Magician HTML form data.
   *
   * @return Either null if no errors, or a List of Div IDs and their associated error messages.
   */
  public List<ValidationError> validate() {

    List<ValidationError> errors = new ArrayList<ValidationError>();

    int upperCase = 0;
    int lowerCase = 0;
    int number = 0;

    for (int k = 0; k < this.password.length(); k++) {
      if (Character.isUpperCase(this.password.charAt(k))) {
        upperCase++;
      }

      if (Character.isLowerCase(this.password.charAt(k))) {
        lowerCase++;
      }

      if (Character.isDigit(this.password.charAt(k))) {
        number++;
      }
    }

    int symbolicChars = this.password.length() - upperCase - lowerCase - number;

    if (upperCase < GlobalDbInfo.MIN_PASSWORD_UPPERCASE_CHARS) {
      errors.add(new ValidationError("password",
          "You should have at least " + GlobalDbInfo.MIN_PASSWORD_UPPERCASE_CHARS + " uppercase character."));
    }

    if (lowerCase < GlobalDbInfo.MIN_PASSWORD_LOWERCASE_CHARS) {
      errors.add(new ValidationError("password",
          "You should have at least " + GlobalDbInfo.MIN_PASSWORD_LOWERCASE_CHARS + " lowercase character."));
    }

    if (number < GlobalDbInfo.MIN_PASSWORD_NUMERIC_CHARS) {
      errors.add(new ValidationError("password",
          "You should have at least " + GlobalDbInfo.MIN_PASSWORD_NUMERIC_CHARS + " number."));
    }

    if (symbolicChars < GlobalDbInfo.MIN_PASSWORD_SYMBOL_CHARS) {
      errors.add(new ValidationError("password",
          "You should have at least " + GlobalDbInfo.MIN_PASSWORD_SYMBOL_CHARS + " symbol."));
    }

    if (!MagicianTypeFormData.isMagicianType(magicianType)) {
      errors.add(new ValidationError("magicianType",
          "How would you identify yourself as a magician?  Please select from the list."));
    }

    if (Magician.find().where().ne("id", id).ieq("email", email).findList().size() > 0) {
      errors.add(new ValidationError("email",
          "A user with this email address has already created an account.  Please enter a different email."));
    }

    return errors.isEmpty() ? null : errors;
  }
}


text:
package com.amazonaws.services.eks.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ConfigStatus {

    CREATING("CREATING"),
    DELETING("DELETING"),
    ACTIVE("ACTIVE");

    private String value;

    private ConfigStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ConfigStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ConfigStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ConfigStatus enumEntry : ConfigStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
from hypothesis import given
from hypothesis.strategies import binary

from msgpack import packb

from mitmproxy.contentviews import msgpack
from . import full_eval

def msgpack_encode(content):
    return packb(content, use_bin_type=True)

def test_parse_msgpack():
    assert msgpack.parse_msgpack(msgpack_encode({"foo": 1}))
    assert msgpack.parse_msgpack(b"aoesuteoahu") is msgpack.PARSE_ERROR
    assert msgpack.parse_msgpack(msgpack_encode({"foo": "\xe4\xb8\x96\xe7\x95\x8c"}))

def test_format_msgpack():
    assert list(msgpack.format_msgpack({
        "data": [
            "str",
            42,
            True,
            False,
            None,
            {},
            []
        ]
    }))

def test_view_msgpack():
    v = full_eval(msgpack.ViewMsgPack())
    assert v(msgpack_encode({}))
    assert not v(b"aoesuteoahu")
    assert v(msgpack_encode([1, 2, 3, 4, 5]))
    assert v(msgpack_encode({"foo": 3}))
    assert v(msgpack_encode({"foo": True, "nullvalue": None}))

@given(binary())
def test_view_msgpack_doesnt_crash(data):
    v = full_eval(msgpack.ViewMsgPack())
    v(data)

def test_render_priority():
    v = msgpack.ViewMsgPack()
    assert v.render_priority(b"data", content_type="application/msgpack")
    assert v.render_priority(b"data", content_type="application/x-msgpack")
    assert not v.render_priority(b"data", content_type="text/plain")


text:
package com.browseengine.bobo.facets.data;

import java.util.Arrays;

public class PrimitiveLongArrayWrapper {
  public long[] data;

  public PrimitiveLongArrayWrapper(long[] data) {
    this.data = data;
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof PrimitiveLongArrayWrapper) {
      return Arrays.equals(data, ((PrimitiveLongArrayWrapper) other).data);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Arrays.hashCode(data);
  }
}


text:
package backup

import (
	"testing"

	"github.com/heptio/ark/pkg/apis/ark/v1"
	"github.com/heptio/ark/pkg/client"
	"github.com/heptio/ark/pkg/discovery"
	"github.com/heptio/ark/pkg/util/collections"
	arktest "github.com/heptio/ark/pkg/util/test"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func TestBackupGroup(t *testing.T) {
	backup := &v1.Backup{}

	namespaces := collections.NewIncludesExcludes().Includes("a")
	resources := collections.NewIncludesExcludes().Includes("b")
	labelSelector := "foo=bar"

	dynamicFactory := &arktest.FakeDynamicFactory{}
	defer dynamicFactory.AssertExpectations(t)

	discoveryHelper := arktest.NewFakeDiscoveryHelper(true, nil)

	backedUpItems := map[itemKey]struct{}{
		{resource: "a", namespace: "b", name: "c"}: {},
	}

	cohabitatingResources := map[string]*cohabitatingResource{
		"a": {
			resource:       "a",
			groupResource1: schema.GroupResource{Group: "g1", Resource: "a"},
			groupResource2: schema.GroupResource{Group: "g2", Resource: "a"},
		},
	}

	actions := map[schema.GroupResource]Action{
		{Group: "", Resource: "pods"}: &fakeAction{},
	}

	podCommandExecutor := &mockPodCommandExecutor{}
	defer podCommandExecutor.AssertExpectations(t)

	tarWriter := &fakeTarWriter{}

	resourceHooks := []resourceHook{
		{name: "myhook"},
	}

	gb := (&defaultGroupBackupperFactory{}).newGroupBackupper(
		arktest.NewLogger(),
		backup,
		namespaces,
		resources,
		labelSelector,
		dynamicFactory,
		discoveryHelper,
		backedUpItems,
		cohabitatingResources,
		actions,
		podCommandExecutor,
		tarWriter,
		resourceHooks,
	).(*defaultGroupBackupper)

	resourceBackupperFactory := &mockResourceBackupperFactory{}
	defer resourceBackupperFactory.AssertExpectations(t)
	gb.resourceBackupperFactory = resourceBackupperFactory

	resourceBackupper := &mockResourceBackupper{}
	defer resourceBackupper.AssertExpectations(t)

	resourceBackupperFactory.On("newResourceBackupper",
		mock.Anything,
		backup,
		namespaces,
		resources,
		labelSelector,
		dynamicFactory,
		discoveryHelper,
		backedUpItems,
		cohabitatingResources,
		actions,
		podCommandExecutor,
		tarWriter,
		resourceHooks,
	).Return(resourceBackupper)

	group := &metav1.APIResourceList{
		GroupVersion: "v1",
		APIResources: []metav1.APIResource{
			{Name: "persistentvolumes"},
			{Name: "pods"},
			{Name: "persistentvolumeclaims"},
		},
	}

	expectedOrder := []string{"pods", "persistentvolumeclaims", "persistentvolumes"}
	var actualOrder []string

	runFunc := func(args mock.Arguments) {
		actualOrder = append(actualOrder, args.Get(1).(metav1.APIResource).Name)
	}

	resourceBackupper.On("backupResource", group, metav1.APIResource{Name: "pods"}).Return(nil).Run(runFunc)
	resourceBackupper.On("backupResource", group, metav1.APIResource{Name: "persistentvolumeclaims"}).Return(nil).Run(runFunc)
	resourceBackupper.On("backupResource", group, metav1.APIResource{Name: "persistentvolumes"}).Return(nil).Run(runFunc)

	err := gb.backupGroup(group)
	require.NoError(t, err)

	// make sure PVs were last
	assert.Equal(t, expectedOrder, actualOrder)
}

type mockResourceBackupperFactory struct {
	mock.Mock
}

func (rbf *mockResourceBackupperFactory) newResourceBackupper(
	log *logrus.Entry,
	backup *v1.Backup,
	namespaces *collections.IncludesExcludes,
	resources *collections.IncludesExcludes,
	labelSelector string,
	dynamicFactory client.DynamicFactory,
	discoveryHelper discovery.Helper,
	backedUpItems map[itemKey]struct{},
	cohabitatingResources map[string]*cohabitatingResource,
	actions map[schema.GroupResource]Action,
	podCommandExecutor podCommandExecutor,
	tarWriter tarWriter,
	resourceHooks []resourceHook,
) resourceBackupper {
	args := rbf.Called(
		log,
		backup,
		namespaces,
		resources,
		labelSelector,
		dynamicFactory,
		discoveryHelper,
		backedUpItems,
		cohabitatingResources,
		actions,
		podCommandExecutor,
		tarWriter,
		resourceHooks,
	)
	return args.Get(0).(resourceBackupper)
}

type mockResourceBackupper struct {
	mock.Mock
}

func (rb *mockResourceBackupper) backupResource(group *metav1.APIResourceList, resource metav1.APIResource) error {
	args := rb.Called(group, resource)
	return args.Error(0)
}


text:
<?php
namespace vedebel\sitemap;

/**
 * Class for configuring sitemap generation.
 *
 * Class Config
 * @package vedebel\sitemap
 */
class Config
{
    const DEBUG_FILE = 2;
    const DEBUG_STDOUT = 1;

    const DEFAULT_VALUES = [
        'async' => true,
        'maxDepth' => 3,
        'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
        'limits' => [
            'threads' => 3,
            'linksTotal' => 1000,
            'linksPerFile' => 50000,

        ],
        'timeouts' => [
            'request' => 20,
            'sleep' => 0
        ],
        'debug' => [
            'enable' => false,
            'mode' => self::DEBUG_FILE,
            'logFile' => __DIR__ . '/crawl.log',
        ],
        'download' => [
            'enable' => false,
            'directory' => __DIR__ . '/download'
        ],
        'onProgress' => false
    ];

    /**
     * @var array
     */
    private $config;

    /**
     * Constructing config object by passing array with params.
     *
     * Config constructor.
     * @param Url $url
     * @param array $config
     */
    public function __construct(Url $url, array $config)
    {
        $this->config = $config;
        $this->config['url'] = $url;
    }

    /**
     * Common getter for all of the params.
     *
     * @param $name
     * @return mixed
     */
    public function get(string $name)
    {
        $path = explode('.', $name);

        return $this->getByPath($path);
    }

    /**
     * Common getter for all of the params.
     *
     * @param string $name
     * @param $value
     * @return mixed
     */
    public function set(string $name, $value)
    {
        $path = explode('.', $name);

        $this->setInPath($path, $value);
    }

    /**
     * Magic getter that allows access to all of the params through property.
     *
     * @param $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->get($name);
    }

    /**
     * Magic getter that allows access to all of the params through getPropertyName methods.
     *
     * @param $name
     * @param $arguments
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        if (strpos($name, 'get') !== 0) {
            throw new \BadMethodCallException(sprintf('There is no method named %d', $name));
        }

        $propertyName = lcfirst(substr($name, 3));

        return $this->get($propertyName);
    }

    /**
     * Retrieves value by its path in config array.
     *
     * @param array $path
     * @param bool $useDefault
     * @return mixed
     */
    private function getByPath(array $path, bool $useDefault = false)
    {
        if ($useDefault) {
            $currentLevel = self::DEFAULT_VALUES;
        } else {
            $currentLevel = $this->config;
        }

        $leftPath = $path;

        do {
            if (!count($leftPath)) {
                break;
            }

            $pathItem = array_shift($leftPath);

            if (!isset($currentLevel[$pathItem])) {
                break;
            }

            $currentLevel = $currentLevel[$pathItem];

            if (count($leftPath) === 0) {
                $value = $currentLevel;
                break;
            }
        } while ($pathItem);

        if (!isset($value)) {
            if ($useDefault) {
                throw new \InvalidArgumentException(sprintf('There is no value for path %s', print_r($path, 1)));
            }

            $value = $this->getByPath($path, true);
        }

        return $value;
    }

    /**
     * @param array $path
     * @param $value
     */
    private function setInPath(array $path, $value)
    {
        $currentLevel = &$this->config;

        do {
            if (!count($path)) {
                break;
            }

            $pathItem = array_shift($path);

            if (!isset($currentLevel[$pathItem])) {
                $currentLevel[$pathItem] = null;
            }

            $currentLevel = &$currentLevel[$pathItem];

            if (count($path) === 0) {
                $currentLevel = $value;
                break;
            }

            $currentLevel = [];
        } while ($pathItem);
    }
}


text:
<?php
require_once 'header.php';

if($this->session->userdata('usua_id')){
	require_once 'navbar.php';
}

echo $contenido;

require_once 'footer.php';


text: Gelieve in het 'Aan' veld een ontvanger in te geven.


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Fl. atlant. 1:280, t. 81. 1798

#### Original name
null

### Remarks
null


text:
Participants

    ...loading...

Join the meetup

The meetup is free! Please let us know if you can make it. We will also inform you about updates and future events.

  <form method="post" action="#" data-meetup="{{include.meetup}}">
    Name
    <input type="text" name="name" class="full-width" />
    Email Address
    <input type="text" name="email" class="full-width" />
    <input type="submit" value="Signup" class="button" /> Great, see you at the meetup!
  </form>


text:
{{error}}

{{item.$name}}

{{item.description}}


text:
import urllib

url = "http://ernestmarples.com/"

class PostcodeNotFound(Exception):
    pass

def find(postcode):
    resource = "%s?%s" % (url, urllib.urlencode({'p':postcode,'f':'csv'}))

    try:
        #Get location
        resource = urllib.urlopen(resource)
        #Make sure it's in csv format. If it's not, we were redirected to home page
        assert resource.info()['Content-Type'] == "text/csv"
        #Split it on commas
        values = resource.read().split(',')
        #Make sure it's in the format postcode, lat, long
        assert len(values) == 3
        #Return the lat and long
        return [float(v) for v in values[1:]]
    except (IOError, AssertionError, ValueError):
        raise PostcodeNotFound()


text:
package net.lipecki.watson.receipt;

import lombok.Builder;
import lombok.Data;

import java.util.Optional;

@Data
@Builder
public class AddReceiptProductProducerDto {

    private String uuid;
    private String name;

    public Optional<String> getUuid() {
        return Optional.ofNullable(this.uuid);
    }

    public Optional<String> getName() {
        return Optional.ofNullable(this.name);
    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/html/Album/vendor/zendframework/zendframework/library/Zend/EventManager/AbstractListenerAggregate.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/html/Album /

vendor /

zendframework /

zendframework /

library /

Zend /

EventManager /

AbstractListenerAggregate.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

0.00%

0 / 1

      CRAP

0.00%

0 / 6

      AbstractListenerAggregate

0.00%

0 / 1

0.00%

0 / 1

      12

0.00%

0 / 6

       detach(EventManagerInterface $events)

0.00%

0 / 1

      12

0.00%

0 / 6

1
	<?php

2

9

10
	namespace Zend\EventManager;

11

12

13
	/**

14
	 * Abstract aggregate listener

15
	 */

16
	abstract class AbstractListenerAggregate implements ListenerAggregateInterface

17
	{

18
	    /**

19
	     * @var \Zend\Stdlib\CallbackHandler[]

20
	     */

21
	    protected $listeners = array();

22

23
	    /**

24
	     * {@inheritDoc}

25
	     */

26
	    public function detach(EventManagerInterface $events)

27
	    {

28
	        foreach ($this->listeners as $index => $callback) {

29
	            if ($events->detach($callback)) {

30
	                unset($this->listeners[$index]);

31
	            }

32
	        }

33
	    }

34
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.6.0-1+deb.sury.org~trusty+1 and PHPUnit 3.7.28 at Tue Oct 7 22:36:47 AMT 2014.


text:
package griffon.pivot.support.adapters;

import griffon.core.CallableWithArgs;

/**
 * @author Andres Almiray
 * @since 2.0.0
 */
public class ListButtonItemAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.ListButtonItemListener {
    private CallableWithArgs<Void> itemsCleared;
    private CallableWithArgs<Void> itemsSorted;
    private CallableWithArgs<Void> itemInserted;
    private CallableWithArgs<Void> itemUpdated;
    private CallableWithArgs<Void> itemsRemoved;

    public CallableWithArgs<Void> getItemsCleared() {
        return this.itemsCleared;
    }

    public CallableWithArgs<Void> getItemsSorted() {
        return this.itemsSorted;
    }

    public CallableWithArgs<Void> getItemInserted() {
        return this.itemInserted;
    }

    public CallableWithArgs<Void> getItemUpdated() {
        return this.itemUpdated;
    }

    public CallableWithArgs<Void> getItemsRemoved() {
        return this.itemsRemoved;
    }

    public void setItemsCleared(CallableWithArgs<Void> itemsCleared) {
        this.itemsCleared = itemsCleared;
    }

    public void setItemsSorted(CallableWithArgs<Void> itemsSorted) {
        this.itemsSorted = itemsSorted;
    }

    public void setItemInserted(CallableWithArgs<Void> itemInserted) {
        this.itemInserted = itemInserted;
    }

    public void setItemUpdated(CallableWithArgs<Void> itemUpdated) {
        this.itemUpdated = itemUpdated;
    }

    public void setItemsRemoved(CallableWithArgs<Void> itemsRemoved) {
        this.itemsRemoved = itemsRemoved;
    }

    public void itemsCleared(org.apache.pivot.wtk.ListButton arg0) {
        if (itemsCleared != null) {
            itemsCleared.call(arg0);
        }
    }

    public void itemsSorted(org.apache.pivot.wtk.ListButton arg0) {
        if (itemsSorted != null) {
            itemsSorted.call(arg0);
        }
    }

    public void itemInserted(org.apache.pivot.wtk.ListButton arg0, int arg1) {
        if (itemInserted != null) {
            itemInserted.call(arg0, arg1);
        }
    }

    public void itemUpdated(org.apache.pivot.wtk.ListButton arg0, int arg1) {
        if (itemUpdated != null) {
            itemUpdated.call(arg0, arg1);
        }
    }

    public void itemsRemoved(org.apache.pivot.wtk.ListButton arg0, int arg1, int arg2) {
        if (itemsRemoved != null) {
            itemsRemoved.call(arg0, arg1, arg2);
        }
    }

}


text:
"use strict";

var React = require('react');
var d3 = require('d3');
var d3Chart = require('../utils/d3Chart.js');

var Chart = React.createClass({
  propTypes: {
    data: React.PropTypes.array,
    domain: React.PropTypes.object
  },
  componentDidMount: function() {
    var el = this.getDOMNode();
    d3Chart.create(el, {
      width: '240',
      height: '130'
      }, this.getChartState()
    );
  },
  componentDidUpdate: function() {

    var el = this.getDOMNode();
    d3Chart.update(el, this.getChartState());

  },
  getChartState: function() {

    return {
      data: this.props.data,
      domain: this.props.data.map(function(obj){ return obj.period; })
    };
  },
  componentWillUnmount: function() {
    var el = this.getDOMNode();
    d3Chart.destroy(el);
  },
  render: function() {
    return (

    );
  }

});

module.exports = Chart;


text:
module Cinch
  module Plugin
    module ClassMethods
      def use_auth(silent: false)
        if silent
          hook :pre, for: [:match], method: :authed_silent?
        else
          hook :pre, for: [:match], method: :authed?
        end
      end
    end

    def authed_silent?(m)
      @bot.admins.include?(m.user.nick) && User(m.user.nick).authed?
    end

    def authed?(m)
      if authed_silent?(m)
        true
      else
        m.reply "You do not have permission to do that.", true
        false
      end
    end
  end
end


text:
/*************************************************************************/
/*  soft_body_bullet.h                                                   */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef SOFT_BODY_BULLET_H
#define SOFT_BODY_BULLET_H

#include "collision_object_bullet.h"
#include "scene/resources/material.h" // TODO remove this please

#ifdef None
/// This is required to remove the macro None defined by x11 compiler because this word "None" is used internally by Bullet
#undef None
#define x11_None 0L
#endif

#include "BulletSoftBody/btSoftBodyHelpers.h"
#include "collision_object_bullet.h"
#include "scene/resources/mesh.h"
#include "servers/physics_server.h"

#ifdef x11_None
/// This is required to re add the macro None defined by x11 compiler
#undef x11_None
#define None 0L
#endif

/**
	@author AndreaCatania
*/

class SoftBodyBullet : public CollisionObjectBullet {

private:
	btSoftBody *bt_soft_body;
	Vector<Vector<int> > indices_table;
	btSoftBody::Material *mat0; // This is just a copy of pointer managed by btSoftBody
	bool isScratched;

	Ref<Mesh> soft_mesh;

	int simulation_precision;
	real_t total_mass;
	real_t linear_stiffness; // [0,1]
	real_t areaAngular_stiffness; // [0,1]
	real_t volume_stiffness; // [0,1]
	real_t pressure_coefficient; // [-inf,+inf]
	real_t pose_matching_coefficient; // [0,1]
	real_t damping_coefficient; // [0,1]
	real_t drag_coefficient; // [0,1]
	Vector<int> pinned_nodes;

	// Other property to add
	//btScalar				kVC;			// Volume conversation coefficient [0,+inf]
	//btScalar				kDF;			// Dynamic friction coefficient [0,1]
	//btScalar				kMT;			// Pose matching coefficient [0,1]
	//btScalar				kCHR;			// Rigid contacts hardness [0,1]
	//btScalar				kKHR;			// Kinetic contacts hardness [0,1]
	//btScalar				kSHR;			// Soft contacts hardness [0,1]

public:
	SoftBodyBullet();
	~SoftBodyBullet();

	virtual void reload_body();
	virtual void set_space(SpaceBullet *p_space);

	virtual void dispatch_callbacks();
	virtual void on_collision_filters_change();
	virtual void on_collision_checker_start();
	virtual void on_enter_area(AreaBullet *p_area);
	virtual void on_exit_area(AreaBullet *p_area);

	_FORCE_INLINE_ btSoftBody *get_bt_soft_body() const { return bt_soft_body; }

	void update_visual_server(class SoftBodyVisualServerHandler *p_visual_server_handler);

	void set_soft_mesh(const Ref<Mesh> &p_mesh);
	void destroy_soft_body();

	// Special function. This function has bad performance
	void set_soft_transform(const Transform &p_transform);

	void move_all_nodes(const Transform &p_transform);
	void set_node_position(int node_index, const Vector3 &p_global_position);
	void set_node_position(int node_index, const btVector3 &p_global_position);
	void get_node_position(int node_index, Vector3 &r_position) const;
	// Heavy function, Please cache this info
	void get_node_offset(int node_index, Vector3 &r_offset) const;
	// Heavy function, Please cache this info
	void get_node_offset(int node_index, btVector3 &r_offset) const;

	void set_node_mass(int node_index, btScalar p_mass);
	btScalar get_node_mass(int node_index) const;
	void reset_all_node_mass();
	void reset_all_node_positions();

	void set_activation_state(bool p_active);

	void set_total_mass(real_t p_val);
	_FORCE_INLINE_ real_t get_total_mass() const { return total_mass; }

	void set_linear_stiffness(real_t p_val);
	_FORCE_INLINE_ real_t get_linear_stiffness() const { return linear_stiffness; }

	void set_areaAngular_stiffness(real_t p_val);
	_FORCE_INLINE_ real_t get_areaAngular_stiffness() const { return areaAngular_stiffness; }

	void set_volume_stiffness(real_t p_val);
	_FORCE_INLINE_ real_t get_volume_stiffness() const { return volume_stiffness; }

	void set_simulation_precision(int p_val);
	_FORCE_INLINE_ int get_simulation_precision() const { return simulation_precision; }

	void set_pressure_coefficient(real_t p_val);
	_FORCE_INLINE_ real_t get_pressure_coefficient() const { return pressure_coefficient; }

	void set_pose_matching_coefficient(real_t p_val);
	_FORCE_INLINE_ real_t get_pose_matching_coefficient() const { return pose_matching_coefficient; }

	void set_damping_coefficient(real_t p_val);
	_FORCE_INLINE_ real_t get_damping_coefficient() const { return damping_coefficient; }

	void set_drag_coefficient(real_t p_val);
	_FORCE_INLINE_ real_t get_drag_coefficient() const { return drag_coefficient; }

private:
	void set_trimesh_body_shape(PoolVector<int> p_indices, PoolVector<Vector3> p_vertices);
	void setup_soft_body();

	void pin_node(int p_node_index);
	void unpin_node(int p_node_index);
	int search_node_pinned(int p_node_index) const;
};

#endif // SOFT_BODY_BULLET_H


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rosa vanheurckiana Crép. ex Boiss.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycogr. Suisse (1833)

#### Original name
Agaricus vitellinopes Secr.

### Remarks
null


text:
#include "manga_directory_entry.hpp"
#include "library.hpp"
#include "manga_entry.hpp"
#include "http_client.hpp"

namespace json11
{
    class Json;
}

namespace mangapp
{
    class manga_library : public base::library<manga_directory>
    {
    public:
        typedef manga_directory directory_type;
        typedef manga_entry file_entry_type;

        typedef std::function<void(mstch::map&&, bool)> context_event;
        typedef std::function<void(std::string const&)> string_event;
        typedef std::function<void(http_client::response_pointer &&)> response_event;

        typedef base::library<directory_type>::key_type key_type;

        manga_library(std::vector<std::wstring> const & library_paths, mangapp::users & users, std::string const & database_file);
        manga_library(std::vector<std::string> const & library_paths, mangapp::users & users, std::string const & database_file);
        manga_library(json11::Json const & settings_json, mangapp::users & users, std::string const & database_file);
        virtual ~manga_library();
    protected:
        virtual void search_online_source(manga_directory & manga, context_event on_event) final;
    private:
        http_client m_http_client;

        mstch::map build_series_context(mangaupdates::series const & series) const;

        void on_id(std::string const & id, manga_directory & manga, context_event on_event, string_event on_error);
        void search_title(manga_directory & manga,
                          string_event on_event,
                          unsigned int start_page = 1,
                          unsigned int max_pages = 5);
        void request_page(std::string const & name, unsigned int page_index, response_event on_event);

        void save_cover(key_type key, std::string const & id, std::string const & image);
        void save_details(key_type key, mangaupdates::series const & series);

        auto query_details(key_type key) const -> mangaupdates::series;
    };
}

#endif


text:
#ifndef CXXLAPACK_INTERFACE_LASD3_H
#define CXXLAPACK_INTERFACE_LASD3_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename IndexType>
    IndexType
    lasd3(IndexType             nl,
          IndexType             nr,
          IndexType             sqre,
          IndexType             k,
          float                 *d,
          float                 *D,
          IndexType             ldD,
          const float           dsigma,
          float                 *U,
          IndexType             ldU,
          float                 *U2,
          IndexType             ldU2,
          float                 *Vt,
          IndexType             ldVt,
          float                 *Vt2,
          IndexType             ldVt2,
          const IndexType       *idxc,
          const IndexType       *ctot,
          const float           *z);

template <typename IndexType>
    IndexType
    lasd3(IndexType             nl,
          IndexType             nr,
          IndexType             sqre,
          IndexType             k,
          double                *d,
          double                *D,
          IndexType             ldD,
          const double          dsigma,
          double                *U,
          IndexType             ldU,
          double                *U2,
          IndexType             ldU2,
          double                *Vt,
          IndexType             ldVt,
          double                *Vt2,
          IndexType             ldVt2,
          const IndexType       *idxc,
          const IndexType       *ctot,
          const double          *z);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_LASD3_H


text:
import {Light, LightShadow} from "three";
import {default as Object3DDescriptorBase, IObject3DProps} from "./object3DBase";

export interface ILightProps extends IObject3DProps {
  color?: number | string;
  intensity?: number;
}

abstract class LightDescriptorBase<TProps extends ILightProps,
  TInstance extends Light, TChild = any>
  extends Object3DDescriptorBase<TProps, TInstance, TChild> {
  protected constructor() {
    super();

    this.hasProp("color", (instance: Light,
                           newValue: any): void => {
      instance.color.set(newValue);
    }, false);

    this.hasSimpleProp("intensity", false);
  }
}

export default LightDescriptorBase;


text:
The Portfolio |
                        Check out some of my previous work

Filter My Projects

By Feature

            <input type="text" ng-model="searchString" placeholder="Search Descriptions">

                        <input type="checkbox" ng-model="tech.on" ng-change="checkChange()" /> {{tech.name}}

About This Filter: I built this AJAX filter using Angular JS to dynamically populate my projects as you type out your search term.

{{portfolioItem.name}}

{{portfolioItem.headline}}

{{portfolioItem.description | lenLimit200}}

                        View
                            Project


text:
__author__ = 'yalnazov'

from abc import ABCMeta, abstractproperty
from ..models.paymill_list import PaymillList
from six import with_metaclass, iteritems

class PaymillService(with_metaclass(ABCMeta, object)):

    """Abstract Base Classes(ABC) for all PAYMILL services.

    Do not use this class directly.

    """

    @abstractproperty
    def endpoint_path(self):
        return

    @abstractproperty
    def paymill_object(self):
        return

    def __init__(self, http_client):
        self.http_client = http_client

    def _create(self, params):
        return self.http_client('POST', params, self.endpoint_path(), self.paymill_object())

    def _detail(self, obj):
        return self.http_client('GET', params=None, url=self.endpoint_path() + '/' + obj.id,
                                return_type=self.paymill_object())

    def _update(self, obj, **kwargs):
        update_dict = dict()
        #pack all updatable object's fields in the update_dict
        for u in obj.updatable_fields():
            if obj[u] is not None:
                if hasattr(obj[u], 'id'):
                    update_dict.update(**{str(u): obj[u].id})
                else:
                    update_dict.update(**{str(u): obj[u]})
        #pack all special updatable object's fields in the update_dict
        for k, v in iteritems(kwargs):
            update_dict.update(**{k: v})

        return self.http_client('PUT', update_dict, self.endpoint_path() + '/' + obj.id,
                                self.paymill_object())

    def _list(self, **kwargs):
        return self.http_client('GET', dict(**kwargs), self.endpoint_path(), PaymillList)

    def _remove(self, obj, params=None):
        return self.http_client('DELETE', params, url=self.endpoint_path() + '/' + obj.id,
                                return_type=self.paymill_object())

    def list(self, count=None, offset=None, filtr=None, order=None):
        """Returns a remote representation of a PAYMILL List
        :param int count: list count
        :param int offset: list offset
        :param Filter filtr:
        :param Order order:
        :return: PaymillList
        """
        params = dict(count=count, offset=offset)
        if order is not None:
            params.update(order.to_dict())
        if filtr is not None:
            params.update(filtr.to_dict())

        return self._list(**params)


text:
#import <ObjFW/ObjFW.h>
#import "OFException+WinBacktrace.h"
#import "DrMinGWModule.h"
#import "DynamoRIOModule.h"
#import "WinCRTException.h"
#import "WinCRTException+PRIVATE.h"

#import "WinBacktrace.h"

#include <inttypes.h>

@interface OFException(DebugPrint)

- (void)printDebugInfo:(OFDictionary *)info number:(size_t)number;

@end

/* We provide control over many aspects of callstack formatting (i#290)
 * encoded in print_flags.
 * We put file:line in [] and absaddr <mod!offs> in ()
 *
 Example:
 *  0  suppress.exe!do_uninit_read+0x27 [e:\derek\drmemory\git\src\tests\suppress.c @ 53] (0x004011d7 <suppress.exe+0x11d7>)
 *  1  suppress.exe!uninit_test1+0xb [e:\derek\drmemory\git\src\tests\suppress.c @ 59] (0x0040119c <suppress.exe+0x119c>)
 *  2  suppress.exe!test+0xf [e:\derek\drmemory\git\src\tests\suppress.c @ 213] (0x00401070 <suppress.exe+0x1070>)
 *  3  suppress.exe!main+0x31 [e:\derek\drmemory\git\src\tests\suppress.c @ 247] (0x00401042 <suppress.exe+0x1042>)
 *  4  suppress.exe!__tmainCRTStartup+0x15e [f:\sp\vctools\crt_bld\self_x86\crt\src\crt0.c @ 327] (0x00401d87 <suppress.exe+0x1d87>)
 *  5  KERNEL32.dll!BaseProcessStart+0x27 (0x7d4e9982 <KERNEL32.dll+0x29982>)
 */

LONG WINAPI __WinBacktrace_Exception_Filter(LPEXCEPTION_POINTERS info) {

	PEXCEPTION_RECORD ExceptionRecord = info->ExceptionRecord;
    PCONTEXT ContextRecord = info->ContextRecord;

    void* pool = objc_autoreleasePoolPush();

    WinCRTException* WinRTException = [WinCRTException exceptionWithExceptionRecord:ExceptionRecord];

    if ([DrMinGWModule loaded] && [DynamoRIOModule loaded]) {

    	DynamoRIOModule* module = [DynamoRIOModule moduleWithContext:ContextRecord];

    	if ([WinBacktrace postmortemDebug])
    		[module miniDump:info];

		OFArray* stack = [module callectStackWithDepth:OF_BACKTRACE_SIZE];

		size_t depth = [stack count];

    	void* _stack[depth];

    	memset(_stack, 0, (sizeof(void*) * depth));

    	for (size_t idx = 0; idx < depth; idx++) {

    		_stack[idx] = (void*)[[stack objectAtIndex:idx] uIntPtrValue];

    	}

    	[WinRTException setBackTrace:_stack count:depth];

    	[WinRTException retain];

    	objc_autoreleasePoolPop(pool);

    	@throw [WinRTException autorelease];

    } else if ([DrMinGWModule loaded]) {

    	DrMinGWModule* module = [DrMinGWModule moduleWithContext:ContextRecord];

    	if ([WinBacktrace postmortemDebug])
    		[module miniDump:info];

    	OFArray* stack = [module callectStackWithDepth:OF_BACKTRACE_SIZE];

		size_t depth = [stack count];

    	void* _stack[depth];

    	memset(_stack, 0, (sizeof(void*) * depth));

    	for (size_t idx = 0; idx < depth; idx++) {

    		_stack[idx] = (void*)[[stack objectAtIndex:idx] uIntPtrValue];

    	}

    	[WinRTException setBackTrace:_stack count:depth];

    	[WinRTException retain];

    	objc_autoreleasePoolPop(pool);

    	@throw [WinRTException autorelease];

    } else {

    	[of_stderr writeFormat:@"Runtime Error 0x%04x %@ was occured at address 0x%p\r\n", ExceptionRecord->ExceptionCode, WinExceptionDescription(ExceptionRecord->ExceptionCode), ExceptionRecord->ExceptionAddress];

    	if (ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
    		if (ExceptionRecord->ExceptionInformation[0] == 0)
    			[of_stderr writeLine:@"Attempted to read the inaccessible data!"];
    		else if (ExceptionRecord->ExceptionInformation[0] == 1)
    			[of_stderr writeLine:@"Attempted to write to an inaccessible address!"];
    		else if (ExceptionRecord->ExceptionInformation[0] == 8)
    			[of_stderr writeLine:@"DEP violation!"];

    	} else if (ExceptionRecord->ExceptionCode == EXCEPTION_IN_PAGE_ERROR) {
    		if (ExceptionRecord->ExceptionInformation[0] == 0)
    			[of_stderr writeLine:@"Attempted to read the inaccessible data!"];
    		else if (ExceptionRecord->ExceptionInformation[0] == 1)
    			[of_stderr writeLine:@"Attempted to write to an inaccessible address!"];
    		else if (ExceptionRecord->ExceptionInformation[0] == 8)
    			[of_stderr writeLine:@"DEP violation!"];

    	}
    }

    objc_autoreleasePoolPop(pool);

    return 0x1;

}

void __WinBacktrace_Uncaught_Exception_Handler(id exception) {

	wchar_t path[1024];
	OFConstantString* dateFormat = @"%A %d %B %Y %H:%M:%S";

	DWORD length = GetModuleFileNameW(NULL, path, 1024);
	OFString* executablePath = [OFString stringWithUTF16String:path length:(size_t)length];
	OFString* executableDir = [executablePath stringByDeletingLastPathComponent];
	OFString* executableName = [executablePath lastPathComponent];
	OFString* backtraceLogFile = [executableDir stringByAppendingPathComponent:[OFString stringWithFormat:@"%@_backtrace.log", [executableName stringByDeletingPathExtension]]];

	OFFile* backtrace = [OFFile fileWithPath:[backtraceLogFile stringByStandardizingPath] mode:@"a+"];

	[of_stderr writeLine:[exception description]];

	[backtrace writeFormat:@"%@ %@ GMT+0:\n\n", executableName, [[OFDate date] dateStringWithFormat:dateFormat]];
	[backtrace writeString:@"========================START=========================\n\n"];
	if ([exception isKindOfClass:[WinCRTException class]]) {

		[backtrace writeLine:@"Windows CRT exception."];
		[backtrace writeLine:@"Executable main thread is dead!"];
		[backtrace writeLine:@"Executable stack is dead!"];

	} else {

		[backtrace writeFormat:@"PID %d TID 0x%llx\n\n", GetCurrentProcessId(), GetCurrentThreadId()];

	}

	[backtrace writeLine:[exception description]];
	[backtrace writeString:@"\n\n"];
	[of_stderr writeString:@"\r\n\r\n"];
	OFArray* stackInfo = [exception backtraceInfo];

	size_t idx = 0;
	for (OFDictionary* info in stackInfo) {

		[exception printDebugInfo:info  number:idx];

		[backtrace writeFormat:@"%zu %@\n", idx, [exception stringFromDebugInfo:info]];

		idx++;
	}
	[of_stderr writeString:@"\r\n\r\n"];
	[backtrace writeString:@"\n\n"];

	if ([WinBacktrace isPrintCallStack]) {
		if ([DrMinGWModule loaded]) {

			[backtrace writeString:@"Stack:\n\n"];

			OFArray* stack = nil;

			if ([DynamoRIOModule loaded]) {
				DynamoRIOModule* module = [DynamoRIOModule moduleWithContext:NULL];

				stack = [module backtraceStackWithDepth:256];

			} else {
				DrMinGWModule* module = [DrMinGWModule moduleWithContext:NULL];

				stack = [module backtraceStackWithDepth:256];
			}
			idx = 0;
			for (OFDictionary* i in stack){
				[backtrace writeLine:[OFString stringWithFormat:@"%zu %@", idx, [exception stringFromDebugInfo:i]]];
				idx++;
			}
		}
	}

	[backtrace writeString:@"========================END=========================\n\n"];
	[backtrace close];

	abort();
}

@implementation OFException (WinBacktrace)

- (void)printDebugBacktrace
{
	OFAutoreleasePool* pool = [OFAutoreleasePool new];

	OFArray* backtrace_ = nil;

	size_t idx = 0;

	if ((backtrace_ = [self backtraceInfo]) == nil) {
		backtrace_ = [self backtrace];

		[of_stderr writeFormat:@"\r\n\r\n"];

		for (OFString* stackAddress in backtrace_) {
			[of_stderr writeFormat:@"%zu %@\r\n", idx, stackAddress];
			idx++;
		}

		[of_stderr writeFormat:@"\r\n\r\n"];

		[pool release];
		return;
	}

	[backtrace_ retain];

	[of_stderr writeFormat:@"\r\n\r\n"];
	for (OFDictionary* info in backtrace_) {

		[self printDebugInfo:info number:idx];

		[pool releaseObjects];
		idx++;
	}
	[backtrace_ autorelease];
	[pool release];

	[of_stderr writeFormat:@"\r\n\r\n"];

	return;
}

- (OFArray *)backtraceInfo
{
	OFArray* info = nil;

	void* pool = objc_autoreleasePoolPush();

	if (![DynamoRIOModule loaded]) {
		if (![DrMinGWModule loaded])
			return nil;

		DrMinGWModule* module = [DrMinGWModule moduleWithContext:NULL];

    	info = [module backtraceWithStack:_backtrace depth:OF_BACKTRACE_SIZE];

		[info retain];

		objc_autoreleasePoolPop(pool);

		return [info autorelease];

	}

	DynamoRIOModule* module = [DynamoRIOModule module];

	info = [module backtraceWithStack:_backtrace depth:OF_BACKTRACE_SIZE];

	[info retain];

	objc_autoreleasePoolPop(pool);

	return [info autorelease];
}

- (void)printDebugInfo:(OFDictionary *)info  number:(size_t)number
{
	[of_stderr writeFormat:@"%zu %@\r\n",
		number,
		[self stringFromDebugInfo:info]
	];
}

- (OFString *)stringFromDebugInfo:(OFDictionary *)info
{
	return [OFString stringWithFormat:@"%@!%@+0x%x  [%@ @ %llu]  (0x%p <%@+0x%p>) [0x%p - 0x%p]",
		[[info objectForKey:kModuleName] isEqual:@"Unknown"] ? @"????" : [info objectForKey:kModuleName],
		([info objectForKey:kDemangledSymbolName] != nil) ? [info objectForKey:kDemangledSymbolName] : ([info objectForKey:kMangledSymbolName] != nil) ? [info objectForKey:kMangledSymbolName] : @"???",
		[[info objectForKey:kLineOffset] ptrDiffValue],
		([info objectForKey:kSourceFilePath] != nil) ? [info objectForKey:kSourceFilePath] : @"???",
		([info objectForKey:kLineNumber] != nil) ? [[info objectForKey:kLineNumber] uInt64Value] : 0,
		[[info objectForKey:kStackAddress] uIntPtrValue],
		[[info objectForKey:kModuleName] isEqual:@"Unknown"] ? @"????" : [info objectForKey:kModuleName],
		[[info objectForKey:kModuleOffset] ptrDiffValue],
		[[info objectForKey:kSymbolStartOffset] ptrDiffValue],
		[[info objectForKey:kSymbolEndOffset] ptrDiffValue]
	];
}

@end


text:
package ch.ntb.inf.deep.cgPPC;

interface Registers {
	final int nofGPR = 32;
	final int nofFPR = 32;

	final int topGPR = 31;	// highest numbered GPR
	final int topFPR = 31;	// highest numbered FPR

	final int paramStartGPR = 2;	// GPR with first parameter
	final int paramStartFPR = 1;	// FPR with first parameter

	final int paramEndGPR = 10;	// GPR with last parameter, must be < nonVolStartGPR
	final int paramEndFPR = 8;	// FPR with last parameter, must be < nonVolStartFPR

	final int nonVolStartGPR = 13;	// first nonvolatile GPR
	final int nonVolStartFPR = 13;	// first nonvolatile FPR

	final int returnGPR1 = 2;	// GPR with return value
	final int returnGPR2 = 3;	// GPR with return value used for longs
	final int returnFPR = 1;	// FPR with return value

	final int faux1 = 20;	// FPR which is never assigned and can be freely used
	final int faux2 = 21;	// FPR which is never assigned and can be freely used
	final int faux3 = 22;	// FPR which is never assigned and can be freely used

	final int stackPtr = 1;	// register for stack pointer

	// initial mask for GPR's, '1' means register is free
	final int regsGPRinitial = 0xfffffffc;
	// initial mask for FPR's, '1' means register is free
	final int regsFPRinitial = 0xfffffffe & ~(1<<faux1 | 1<<faux2 | 1<<faux3);

	final boolean gpr = true;
	final boolean fpr = false;

}