text:
"""
DBSCAN: Density-Based Spatial Clustering of Applications with Noise
"""

# Author: Robert Layton <robertlayton@gmail.com>
#         Joel Nothman <joel.nothman@gmail.com>
#         Lars Buitinck
#
# License: BSD 3 clause

import numpy as np
import warnings
from scipy import sparse

from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_array, check_consistent_length
from sklearn.neighbors import NearestNeighbors

from sklearn.cluster._dbscan_inner import dbscan_inner

def dbscan(X, eps=0.5, min_samples=5, metric='minkowski', metric_params=None,
           algorithm='auto', leaf_size=30, p=2, sample_weight=None,
           n_jobs=None):
    """Perform DBSCAN clustering from vector array or distance matrix.

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

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

    eps : float, optional
        The maximum distance between two samples for one to be considered
        as in the neighborhood of the other. This is not a maximum bound
        on the distances of points within a cluster. This is the most
        important DBSCAN parameter to choose appropriately for your data set
        and distance function.

    min_samples : int, optional
        The number of samples (or total weight) in a neighborhood for a point
        to be considered as a core point. This includes the point itself.

    metric : string, or callable
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string or callable, it must be one of
        the options allowed by :func:`sklearn.metrics.pairwise_distances` for
        its metric parameter.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square. X may be a sparse matrix, in which case only "nonzero"
        elements may be considered neighbors for DBSCAN.

    metric_params : dict, optional
        Additional keyword arguments for the metric function.

        .. versionadded:: 0.19

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
        The algorithm to be used by the NearestNeighbors module
        to compute pointwise distances and find nearest neighbors.
        See NearestNeighbors module documentation for details.

    leaf_size : int, optional (default = 30)
        Leaf size passed to BallTree or cKDTree. 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.

    p : float, optional
        The power of the Minkowski metric to be used to calculate distance
        between points.

    sample_weight : array, shape (n_samples,), optional
        Weight of each sample, such that a sample with a weight of at least
        ``min_samples`` is by itself a core sample; a sample with negative
        weight may inhibit its eps-neighbor from being core.
        Note that weights are absolute, and default to 1.

    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
    -------
    core_samples : array [n_core_samples]
        Indices of core samples.

    labels : array [n_samples]
        Cluster labels for each point.  Noisy samples are given the label -1.

    See also
    --------
    DBSCAN
        An estimator interface for this clustering algorithm.
    OPTICS
        A similar estimator interface clustering at multiple values of eps. Our
        implementation is optimized for memory usage.

    Notes
    -----
    For an example, see :ref:`examples/cluster/plot_dbscan.py
    <sphx_glr_auto_examples_cluster_plot_dbscan.py>`.

    This implementation bulk-computes all neighborhood queries, which increases
    the memory complexity to O(n.d) where d is the average number of neighbors,
    while original DBSCAN had memory complexity O(n). It may attract a higher
    memory complexity when querying these nearest neighborhoods, depending
    on the ``algorithm``.

    One way to avoid the query complexity is to pre-compute sparse
    neighborhoods in chunks using
    :func:`NearestNeighbors.radius_neighbors_graph
    <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
    ``mode='distance'``, then using ``metric='precomputed'`` here.

    Another way to reduce memory and computation time is to remove
    (near-)duplicate points and use ``sample_weight`` instead.

    :func:`cluster.optics <sklearn.cluster.optics>` provides a similar
    clustering with lower memory usage.

    References
    ----------
    Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based
    Algorithm for Discovering Clusters in Large Spatial Databases with Noise".
    In: Proceedings of the 2nd International Conference on Knowledge Discovery
    and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996

    Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
    DBSCAN revisited, revisited: why and how you should (still) use DBSCAN.
    ACM Transactions on Database Systems (TODS), 42(3), 19.
    """
    if not eps > 0.0:
        raise ValueError("eps must be positive.")

    X = check_array(X, accept_sparse='csr')
    if sample_weight is not None:
        sample_weight = np.asarray(sample_weight)
        check_consistent_length(X, sample_weight)

    # Calculate neighborhood for all samples. This leaves the original point
    # in, which needs to be considered later (i.e. point i is in the
    # neighborhood of point i. While True, its useless information)
    if metric == 'precomputed' and sparse.issparse(X):
        neighborhoods = np.empty(X.shape[0], dtype=object)
        X.sum_duplicates()  # XXX: modifies X's internals in-place

        # set the diagonal to explicit values, as a point is its own neighbor
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', sparse.SparseEfficiencyWarning)
            X.setdiag(X.diagonal())  # XXX: modifies X's internals in-place

        X_mask = X.data <= eps
        masked_indices = X.indices.astype(np.intp, copy=False)[X_mask]
        masked_indptr = np.concatenate(([0], np.cumsum(X_mask)))
        masked_indptr = masked_indptr[X.indptr[1:-1]]

        # split into rows
        neighborhoods[:] = np.split(masked_indices, masked_indptr)
    else:
        neighbors_model = NearestNeighbors(radius=eps, algorithm=algorithm,
                                           leaf_size=leaf_size,
                                           metric=metric,
                                           metric_params=metric_params, p=p,
                                           n_jobs=n_jobs)
        neighbors_model.fit(X)
        # This has worst case O(n^2) memory complexity
        neighborhoods = neighbors_model.radius_neighbors(X, eps,
                                                         return_distance=False)
        #np.savetxt('sklearn_neighborhoods', neighborhoods, fmt='%s')
    if sample_weight is None:
        n_neighbors = np.array([len(neighbors)
                                for neighbors in neighborhoods])
    else:
        n_neighbors = np.array([np.sum(sample_weight[neighbors])
                                for neighbors in neighborhoods])

    # Initially, all samples are noise.
    labels = np.full(X.shape[0], -1, dtype=np.intp)

    # A list of all core samples found.
    core_samples = np.asarray(n_neighbors >= min_samples, dtype=np.uint8)
    dbscan_inner(core_samples, neighborhoods, labels)
    return np.where(core_samples)[0], labels

class DBSCAN(BaseEstimator, ClusterMixin):
    """Perform DBSCAN clustering from vector array or distance matrix.

    DBSCAN - Density-Based Spatial Clustering of Applications with Noise.
    Finds core samples of high density and expands clusters from them.
    Good for data which contains clusters of similar density.

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

    Parameters
    ----------
    eps : float, optional
        The maximum distance between two samples for one to be considered
        as in the neighborhood of the other. This is not a maximum bound
        on the distances of points within a cluster. This is the most
        important DBSCAN parameter to choose appropriately for your data set
        and distance function.

    min_samples : int, optional
        The number of samples (or total weight) in a neighborhood for a point
        to be considered as a core point. This includes the point itself.

    metric : string, or callable
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string or callable, it must be one of
        the options allowed by :func:`sklearn.metrics.pairwise_distances` for
        its metric parameter.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square. X may be a sparse matrix, in which case only "nonzero"
        elements may be considered neighbors for DBSCAN.

        .. versionadded:: 0.17
           metric *precomputed* to accept precomputed sparse matrix.

    metric_params : dict, optional
        Additional keyword arguments for the metric function.

        .. versionadded:: 0.19

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
        The algorithm to be used by the NearestNeighbors module
        to compute pointwise distances and find nearest neighbors.
        See NearestNeighbors module documentation for details.

    leaf_size : int, optional (default = 30)
        Leaf size passed to BallTree or cKDTree. 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.

    p : float, optional
        The power of the Minkowski metric to be used to calculate distance
        between points.

    n_jobs : int or None, optional (default=None)
        The number of parallel jobs to run.
        ``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
    ----------
    core_sample_indices_ : array, shape = [n_core_samples]
        Indices of core samples.

    components_ : array, shape = [n_core_samples, n_features]
        Copy of each core sample found by training.

    labels_ : array, shape = [n_samples]
        Cluster labels for each point in the dataset given to fit().
        Noisy samples are given the label -1.

    Examples
    --------
    >>> from sklearn.cluster import DBSCAN
    >>> import numpy as np
    >>> X = np.array([[1, 2], [2, 2], [2, 3],
    ...               [8, 7], [8, 8], [25, 80]])
    >>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
    >>> clustering.labels_
    array([ 0,  0,  0,  1,  1, -1])
    >>> clustering # doctest: +NORMALIZE_WHITESPACE
    DBSCAN(algorithm='auto', eps=3, leaf_size=30, metric='euclidean',
        metric_params=None, min_samples=2, n_jobs=None, p=None)

    See also
    --------
    OPTICS
        A similar clustering at multiple values of eps. Our implementation
        is optimized for memory usage.

    Notes
    -----
    For an example, see :ref:`examples/cluster/plot_dbscan.py
    <sphx_glr_auto_examples_cluster_plot_dbscan.py>`.

    This implementation bulk-computes all neighborhood queries, which increases
    the memory complexity to O(n.d) where d is the average number of neighbors,
    while original DBSCAN had memory complexity O(n). It may attract a higher
    memory complexity when querying these nearest neighborhoods, depending
    on the ``algorithm``.

    One way to avoid the query complexity is to pre-compute sparse
    neighborhoods in chunks using
    :func:`NearestNeighbors.radius_neighbors_graph
    <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
    ``mode='distance'``, then using ``metric='precomputed'`` here.

    Another way to reduce memory and computation time is to remove
    (near-)duplicate points and use ``sample_weight`` instead.

    :class:`cluster.OPTICS` provides a similar clustering with lower memory
    usage.

    References
    ----------
    Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based
    Algorithm for Discovering Clusters in Large Spatial Databases with Noise".
    In: Proceedings of the 2nd International Conference on Knowledge Discovery
    and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996

    Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
    DBSCAN revisited, revisited: why and how you should (still) use DBSCAN.
    ACM Transactions on Database Systems (TODS), 42(3), 19.
    """

    def __init__(self, eps=0.5, min_samples=5, metric='euclidean',
                 metric_params=None, algorithm='auto', leaf_size=30, p=None,
                 n_jobs=None):
        self.eps = eps
        self.min_samples = min_samples
        self.metric = metric
        self.metric_params = metric_params
        self.algorithm = algorithm
        self.leaf_size = leaf_size
        self.p = p
        self.n_jobs = n_jobs

    def fit(self, X, y=None, sample_weight=None):
        """Perform DBSCAN clustering from features or distance matrix.

        Parameters
        ----------
        X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \
                array of shape (n_samples, n_samples)
            A feature array, or array of distances between samples if
            ``metric='precomputed'``.
        sample_weight : array, shape (n_samples,), optional
            Weight of each sample, such that a sample with a weight of at least
            ``min_samples`` is by itself a core sample; a sample with negative
            weight may inhibit its eps-neighbor from being core.
            Note that weights are absolute, and default to 1.

        y : Ignored

        """
        X = check_array(X, accept_sparse='csr')
        clust = dbscan(X, sample_weight=sample_weight,
                       **self.get_params())
        self.core_sample_indices_, self.labels_ = clust
        if len(self.core_sample_indices_):
            # fix for scipy sparse indexing issue
            self.components_ = X[self.core_sample_indices_].copy()
        else:
            # no core samples
            self.components_ = np.empty((0, X.shape[1]))
        return self

    def fit_predict(self, X, y=None, sample_weight=None):
        """Performs clustering on X and returns cluster labels.

        Parameters
        ----------
        X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \
                array of shape (n_samples, n_samples)
            A feature array, or array of distances between samples if
            ``metric='precomputed'``.
        sample_weight : array, shape (n_samples,), optional
            Weight of each sample, such that a sample with a weight of at least
            ``min_samples`` is by itself a core sample; a sample with negative
            weight may inhibit its eps-neighbor from being core.
            Note that weights are absolute, and default to 1.

        y : Ignored

        Returns
        -------
        y : ndarray, shape (n_samples,)
            cluster labels
        """
        self.fit(X, sample_weight=sample_weight)
        return self.labels_


text:
<TITLE>Review for Dead Men Don't Wear Plaid (1982)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Dead Men Don't Wear Plaid (1982)

reviewed by
Dennis Schwartz

DEAD MEN DON'T WEAR PLAID (director/writer: Carl Reiner; screenwriters:
George Gipe/Steve Martin; cinematographer: Michael Chapman; editor: Bud
Molin; cast: Steve Martin (Rigby Reardon), Rachel Ward (Juliet Forrest),
Carl Reiner (Field Marshal Von Kluck), Reni Santoni (Carlos Rodriguez),
George Gaynes (Dr. Forrest), 1982)

Reviewed by Dennis Schwartz

This is Carl Reiner's cleverly adapted spoof on noir films of the
post-World War11 days. The comedy film relies on creative editing of the
classics of the forties, somehow including a host of stars from Bogart
to Cagney to Ava, as part of its story. Steve Martin plays the private
eye Rigby Reardon, who is a cloddish imitation of Bogart in "The Big
Sleep." Any scene could have Martin conversing with someone like a Cary
Grant or a Veronica Ladd, or being shot at by Alan Ladd. Rachel Ward is
the sexy doll with the husky voice who plays his client Juliet Forest.
She comes into his office and faints at seeing the newspaper headline
announcing that her father, Dr. Forrest, has died in an auto accident
and she awakens to Martin's breast rearrangement of her. But she hires
him, anyway, for $10 a day plus expenses to find the killer of her
father, as she doesn't believe his death was accidental.

This is basically a one-idea film, and that idea, although cleverly
worked out as far as special effects, begins to run dry after a while,
as the story lags in character development. It seems cute to have the
stars of the forties say their straight lines from their film and then
have Martin put his comedic routines into it in order to fit it in with
the present story. But enough's enough! What keeps the film hopping are
some very funny quips and some dumb bon mots that were infantile but
amusing.

Dr. Forrest is a renown scientist and his hobby is in making cheese
molds. After Ward gives Martin the key to her father's lab, he goes
there to search his lab for clues and tells us he found the lab in room
no. 2 because it smelled like that number. His first clue is in the form
of a cryptic list he finds on the tip of a money bill, which is labelled
"The Friends of Carlotta." Unfortunately there are others who are after
that list, as the shamus must take precautions, even getting a bullet in
his shoulder for his troubles.

Back in Ward's house, Martin is about to faint and the haughty butler
(Reiner), when asked to catch him, says, "Sorry, I'm a butler not a
catcher." Ward uses her skill she learned at summer camp for taking care
of snake bites, to suck the bullet out of him.

With the help of Bogart's detective work ala Marlowe, Martin finds that
Carlotta is not the name of a woman, but an island off South America. If
you've seen "The Bribe," you've got the rest of the film's story, as the
Reiner team ran out of ideas and winged the ending the lazy way, with
old film clips. Martin does his best to pump energy into the tank, doing
sight gags, abetted by the manic role of Reni Santoni, as the friendly
policeman on the island who tells him the Nazis have landed. Nazis and
cheese go together in this film like Vincent Price to villainy.

A knowledge of some of the more popular noir classics like The Big
Sleep, Double Indemnity, and Suspicion, might help in soaking up the
films' nostalgia. The overall effect is not bad for a few belly laughs
and to marvel at the skills of 1980s technology, but no Cuban cigar for
the film, as the story went up in smoke somewhere over the hills of
Hollywood.

REVIEWED ON 6/4/2000     GRADE: C

Dennis Schwartz: "Ozus' World Movie Reviews"

http://www.sover.net/~ozus

ozus@sover.net

© ALL RIGHTS RESERVED   DENNIS SCHWARTZ

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews

redpajama_set_name: RedPajamaGithub


text:
package io.github.jeddict.jpa.spec.extend;

import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.Set;
import io.github.jeddict.source.JCRELoader;
import java.util.Map;

/**
 *
 * @author jGauravGupta
 */
public interface IAttributes extends JCRELoader {

    List<Attribute> findAllAttribute(String name);

    List<Attribute> findAllAttribute(String name,boolean includeParentClassAttibute);

    List<Attribute> getAllAttribute();

    List<Attribute> getAllAttribute(boolean includeParentClassAttibute);

    boolean isAttributeExist(String name);

    Set<String> getConnectedClass();

    Set<String> getConnectedClass(Set<String> javaClasses);

    void notifyListeners(Object source, String property, String oldValue, String newValue);

    void addChangeListener(PropertyChangeListener newListener);

    void removeChangeListener(PropertyChangeListener newListener);

    JavaClass getJavaClass();

    List<Attribute> getAllSortedAttribute();

    List<Attribute> getAllSortedAttribute(boolean includeParentClassAttibute);

    Map<String, Attribute> getAllAttributeMap();

    Map<String, Attribute> getAllAttributeMap(boolean includeParentClassAttibute);

}


text:
package net.sf.jasperreports.data;

import org.exolab.castor.mapping.GeneralizedFieldHandler;

/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: ClassNameFieldHandler.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class ClassNameFieldHandler extends GeneralizedFieldHandler
{
	/**
	 *
	 */
	public ClassNameFieldHandler()
	{
		super();
	}

	/**
	 *
	 */
	public Object convertUponGet(Object value)
	{
		if (value == null)
		{
			return null;
		}
		return ((Class<?>)value).getName();
	}

	/**
	 *
	 */
	public Object convertUponSet(Object value)
	{
		return null;
	}

	/**
	 *
	 */
	public Class<?> getFieldType()
	{
		return Class.class;
	}

	/**
	 *
	 */
	public Object newInstance(Object parent) throws IllegalStateException
	{
		return null;
	}
}


text:
package com.mrbjoern.fitness.controller.api.exercise;

import com.mrbjoern.fitness.domain.user.FitnessUser;
import com.mrbjoern.fitness.domain.workout.Workout;
import com.mrbjoern.fitness.repository.exercise.WorkoutRepository;
import com.mrbjoern.fitness.repository.user.FitnessUserRepository;
import com.mrbjoern.fitness.validation.ValidationError;
import com.mrbjoern.fitness.validation.ValidationErrorBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("api/workout/")
public class WorkoutController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final CounterService counterService;

    @Autowired
    private FitnessUserRepository fitnessUserRepository;
    @Autowired
    private WorkoutRepository workoutRepository;

    @Autowired
    public WorkoutController(CounterService counterService) {
        this.counterService = counterService;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = {"application/json"})
    @PreAuthorize("@securityService.hasAdminAccess()")
    public ResponseEntity getAllWorkouts() {
        Iterable<Workout> workouts = workoutRepository.findAll();

        counterService.increment("workout.getAll");

        return ResponseEntity.ok(workouts);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {"application/json"})
    public ResponseEntity getAllWorkoutsForUserWithId(HttpServletRequest request, @PathVariable long id) {
        FitnessUser user = fitnessUserRepository.findOne(id);
        if (user == null) {
            return ResponseEntity.badRequest().body(new ValidationError("Can only get workouts for own user"));
        } else if (!request.getUserPrincipal().getName().equals(user.getUsername())) {
            return ResponseEntity.badRequest().body(new ValidationError("Can only get workouts for own user"));
        }

        List<Workout> userWorkouts = workoutRepository.findWorkoutsByFitnessUser(user);

        return ResponseEntity.ok(userWorkouts);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.POST, produces = {"application/json"})
    public ResponseEntity createWorkoutForUserWithId(HttpServletRequest request, @PathVariable long id, @Valid @RequestBody Workout workout, Errors errors) {
        if (errors.hasErrors()) {
            return ResponseEntity.badRequest().body(ValidationErrorBuilder.fromBindingErrors(errors));
        }

        FitnessUser user = fitnessUserRepository.findOne(id);
        if (user == null || !request.getUserPrincipal().getName().equals(user.getUsername())) {
            return ResponseEntity.badRequest().body(new ValidationError("Workout must be added for own user"));
        }

        workout.setFitnessUser(user);

        workoutRepository.save(workout);

        counterService.increment("workout.created");

        return ResponseEntity.ok(workout);
    }

}


text:
package com.future.controller;

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

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.future.model.Person;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class DataInitializer {

	public static final int PERSON_COUNT = 3;

	@PersistenceContext
	private EntityManager entityManager;

	public List<Long> people = new ArrayList<Long>();

	public void initData() {
		people.clear();// clear out the previous list of people
		addPerson("Jim", "Smith");
		addPerson("Tina", "Marsh");
		addPerson("Steve", "Blair");
		entityManager.flush();
		entityManager.clear();
	}

	public void addPerson(String firstName, String lastName) {
		Person p = new Person();
		p.setFirstName(firstName);
		p.setLastName(lastName);
		entityManager.persist(p);
		people.add(p.getId());
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}
}


text:
#ifndef OPENCV_FLANN_AUTOTUNED_INDEX_H_
#define OPENCV_FLANN_AUTOTUNED_INDEX_H_

#include <sstream>

#include "general.h"
#include "nn_index.h"
#include "ground_truth.h"
#include "index_testing.h"
#include "sampling.h"
#include "kdtree_index.h"
#include "kdtree_single_index.h"
#include "kmeans_index.h"
#include "composite_index.h"
#include "linear_index.h"
#include "logger.h"

namespace cvflann
{

template<typename Distance>
NNIndex<Distance>* create_index_by_type(const Matrix<typename Distance::ElementType>& dataset, const IndexParams& params, const Distance& distance);

struct AutotunedIndexParams : public IndexParams
{
    AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1)
    {
        (*this)["algorithm"] = FLANN_INDEX_AUTOTUNED;
        // precision desired (used for autotuning, -1 otherwise)
        (*this)["target_precision"] = target_precision;
        // build tree time weighting factor
        (*this)["build_weight"] = build_weight;
        // index memory weighting factor
        (*this)["memory_weight"] = memory_weight;
        // what fraction of the dataset to use for autotuning
        (*this)["sample_fraction"] = sample_fraction;
    }
};

template <typename Distance>
class AutotunedIndex : public NNIndex<Distance>
{
public:
    typedef typename Distance::ElementType ElementType;
    typedef typename Distance::ResultType DistanceType;

    AutotunedIndex(const Matrix<ElementType>& inputData, const IndexParams& params = AutotunedIndexParams(), Distance d = Distance()) :
        dataset_(inputData), distance_(d)
    {
        target_precision_ = get_param(params, "target_precision",0.8f);
        build_weight_ =  get_param(params,"build_weight", 0.01f);
        memory_weight_ = get_param(params, "memory_weight", 0.0f);
        sample_fraction_ = get_param(params,"sample_fraction", 0.1f);
        bestIndex_ = NULL;
        speedup_ = 0;
    }

    AutotunedIndex(const AutotunedIndex&);
    AutotunedIndex& operator=(const AutotunedIndex&);

    virtual ~AutotunedIndex()
    {
        if (bestIndex_ != NULL) {
            delete bestIndex_;
            bestIndex_ = NULL;
        }
    }

    /**
     *          Method responsible with building the index.
     */
    virtual void buildIndex() CV_OVERRIDE
    {
        std::ostringstream stream;
        bestParams_ = estimateBuildParams();
        print_params(bestParams_, stream);
        Logger::info("----------------------------------------------------\n");
        Logger::info("Autotuned parameters:\n");
        Logger::info("%s", stream.str().c_str());
        Logger::info("----------------------------------------------------\n");

        bestIndex_ = create_index_by_type(dataset_, bestParams_, distance_);
        bestIndex_->buildIndex();
        speedup_ = estimateSearchParams(bestSearchParams_);
        stream.str(std::string());
        print_params(bestSearchParams_, stream);
        Logger::info("----------------------------------------------------\n");
        Logger::info("Search parameters:\n");
        Logger::info("%s", stream.str().c_str());
        Logger::info("----------------------------------------------------\n");
    }

    /**
     *  Saves the index to a stream
     */
    virtual void saveIndex(FILE* stream) CV_OVERRIDE
    {
        save_value(stream, (int)bestIndex_->getType());
        bestIndex_->saveIndex(stream);
        save_value(stream, get_param<int>(bestSearchParams_, "checks"));
    }

    /**
     *  Loads the index from a stream
     */
    virtual void loadIndex(FILE* stream) CV_OVERRIDE
    {
        int index_type;

        load_value(stream, index_type);
        IndexParams params;
        params["algorithm"] = (flann_algorithm_t)index_type;
        bestIndex_ = create_index_by_type<Distance>(dataset_, params, distance_);
        bestIndex_->loadIndex(stream);
        int checks;
        load_value(stream, checks);
        bestSearchParams_["checks"] = checks;
    }

    /**
     *      Method that searches for nearest-neighbors
     */
    virtual void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
    {
        int checks = get_param<int>(searchParams,"checks",FLANN_CHECKS_AUTOTUNED);
        if (checks == FLANN_CHECKS_AUTOTUNED) {
            bestIndex_->findNeighbors(result, vec, bestSearchParams_);
        }
        else {
            bestIndex_->findNeighbors(result, vec, searchParams);
        }
    }

    IndexParams getParameters() const CV_OVERRIDE
    {
        return bestIndex_->getParameters();
    }

    SearchParams getSearchParameters() const
    {
        return bestSearchParams_;
    }

    float getSpeedup() const
    {
        return speedup_;
    }

    /**
     *      Number of features in this index.
     */
    virtual size_t size() const CV_OVERRIDE
    {
        return bestIndex_->size();
    }

    /**
     *  The length of each vector in this index.
     */
    virtual size_t veclen() const CV_OVERRIDE
    {
        return bestIndex_->veclen();
    }

    /**
     * The amount of memory (in bytes) this index uses.
     */
    virtual int usedMemory() const CV_OVERRIDE
    {
        return bestIndex_->usedMemory();
    }

    /**
     * Algorithm name
     */
    virtual flann_algorithm_t getType() const CV_OVERRIDE
    {
        return FLANN_INDEX_AUTOTUNED;
    }

private:

    struct CostData
    {
        float searchTimeCost;
        float buildTimeCost;
        float memoryCost;
        float totalCost;
        IndexParams params;
    };

    void evaluate_kmeans(CostData& cost)
    {
        StartStopTimer t;
        int checks;
        const int nn = 1;

        Logger::info("KMeansTree using params: max_iterations=%d, branching=%d\n",
                     get_param<int>(cost.params,"iterations"),
                     get_param<int>(cost.params,"branching"));
        KMeansIndex<Distance> kmeans(sampledDataset_, cost.params, distance_);
        // measure index build time
        t.start();
        kmeans.buildIndex();
        t.stop();
        float buildTime = (float)t.value;

        // measure search time
        float searchTime = test_index_precision(kmeans, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn);

        float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float));
        cost.memoryCost = (kmeans.usedMemory() + datasetMemory) / datasetMemory;
        cost.searchTimeCost = searchTime;
        cost.buildTimeCost = buildTime;
        Logger::info("KMeansTree buildTime=%g, searchTime=%g, build_weight=%g\n", buildTime, searchTime, build_weight_);
    }

    void evaluate_kdtree(CostData& cost)
    {
        StartStopTimer t;
        int checks;
        const int nn = 1;

        Logger::info("KDTree using params: trees=%d\n", get_param<int>(cost.params,"trees"));
        KDTreeIndex<Distance> kdtree(sampledDataset_, cost.params, distance_);

        t.start();
        kdtree.buildIndex();
        t.stop();
        float buildTime = (float)t.value;

        //measure search time
        float searchTime = test_index_precision(kdtree, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn);

        float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float));
        cost.memoryCost = (kdtree.usedMemory() + datasetMemory) / datasetMemory;
        cost.searchTimeCost = searchTime;
        cost.buildTimeCost = buildTime;
        Logger::info("KDTree buildTime=%g, searchTime=%g\n", buildTime, searchTime);
    }

    //    struct KMeansSimpleDownhillFunctor {
    //
    //        Autotune& autotuner;
    //        KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {}
    //
    //        float operator()(int* params) {
    //
    //            float maxFloat = numeric_limits<float>::max();
    //
    //            if (params[0]<2) return maxFloat;
    //            if (params[1]<0) return maxFloat;
    //
    //            CostData c;
    //            c.params["algorithm"] = KMEANS;
    //            c.params["centers-init"] = CENTERS_RANDOM;
    //            c.params["branching"] = params[0];
    //            c.params["max-iterations"] = params[1];
    //
    //            autotuner.evaluate_kmeans(c);
    //
    //            return c.timeCost;
    //
    //        }
    //    };
    //
    //    struct KDTreeSimpleDownhillFunctor {
    //
    //        Autotune& autotuner;
    //        KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {}
    //
    //        float operator()(int* params) {
    //            float maxFloat = numeric_limits<float>::max();
    //
    //            if (params[0]<1) return maxFloat;
    //
    //            CostData c;
    //            c.params["algorithm"] = KDTREE;
    //            c.params["trees"] = params[0];
    //
    //            autotuner.evaluate_kdtree(c);
    //
    //            return c.timeCost;
    //
    //        }
    //    };

    void optimizeKMeans(std::vector<CostData>& costs)
    {
        Logger::info("KMEANS, Step 1: Exploring parameter space\n");

        // explore kmeans parameters space using combinations of the parameters below
        int maxIterations[] = { 1, 5, 10, 15 };
        int branchingFactors[] = { 16, 32, 64, 128, 256 };

        int kmeansParamSpaceSize = FLANN_ARRAY_LEN(maxIterations) * FLANN_ARRAY_LEN(branchingFactors);
        costs.reserve(costs.size() + kmeansParamSpaceSize);

        // evaluate kmeans for all parameter combinations
        for (size_t i = 0; i < FLANN_ARRAY_LEN(maxIterations); ++i) {
            for (size_t j = 0; j < FLANN_ARRAY_LEN(branchingFactors); ++j) {
                CostData cost;
                cost.params["algorithm"] = FLANN_INDEX_KMEANS;
                cost.params["centers_init"] = FLANN_CENTERS_RANDOM;
                cost.params["iterations"] = maxIterations[i];
                cost.params["branching"] = branchingFactors[j];

                evaluate_kmeans(cost);
                costs.push_back(cost);
            }
        }

        //         Logger::info("KMEANS, Step 2: simplex-downhill optimization\n");
        //
        //         const int n = 2;
        //         // choose initial simplex points as the best parameters so far
        //         int kmeansNMPoints[n*(n+1)];
        //         float kmeansVals[n+1];
        //         for (int i=0;i<n+1;++i) {
        //             kmeansNMPoints[i*n] = (int)kmeansCosts[i].params["branching"];
        //             kmeansNMPoints[i*n+1] = (int)kmeansCosts[i].params["max-iterations"];
        //             kmeansVals[i] = kmeansCosts[i].timeCost;
        //         }
        //         KMeansSimpleDownhillFunctor kmeans_cost_func(*this);
        //         // run optimization
        //         optimizeSimplexDownhill(kmeansNMPoints,n,kmeans_cost_func,kmeansVals);
        //         // store results
        //         for (int i=0;i<n+1;++i) {
        //             kmeansCosts[i].params["branching"] = kmeansNMPoints[i*2];
        //             kmeansCosts[i].params["max-iterations"] = kmeansNMPoints[i*2+1];
        //             kmeansCosts[i].timeCost = kmeansVals[i];
        //         }
    }

    void optimizeKDTree(std::vector<CostData>& costs)
    {
        Logger::info("KD-TREE, Step 1: Exploring parameter space\n");

        // explore kd-tree parameters space using the parameters below
        int testTrees[] = { 1, 4, 8, 16, 32 };

        // evaluate kdtree for all parameter combinations
        for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) {
            CostData cost;
            cost.params["algorithm"] = FLANN_INDEX_KDTREE;
            cost.params["trees"] = testTrees[i];

            evaluate_kdtree(cost);
            costs.push_back(cost);
        }

        //         Logger::info("KD-TREE, Step 2: simplex-downhill optimization\n");
        //
        //         const int n = 1;
        //         // choose initial simplex points as the best parameters so far
        //         int kdtreeNMPoints[n*(n+1)];
        //         float kdtreeVals[n+1];
        //         for (int i=0;i<n+1;++i) {
        //             kdtreeNMPoints[i] = (int)kdtreeCosts[i].params["trees"];
        //             kdtreeVals[i] = kdtreeCosts[i].timeCost;
        //         }
        //         KDTreeSimpleDownhillFunctor kdtree_cost_func(*this);
        //         // run optimization
        //         optimizeSimplexDownhill(kdtreeNMPoints,n,kdtree_cost_func,kdtreeVals);
        //         // store results
        //         for (int i=0;i<n+1;++i) {
        //             kdtreeCosts[i].params["trees"] = kdtreeNMPoints[i];
        //             kdtreeCosts[i].timeCost = kdtreeVals[i];
        //         }
    }

    /**
     *  Chooses the best nearest-neighbor algorithm and estimates the optimal
     *  parameters to use when building the index (for a given precision).
     *  Returns a dictionary with the optimal parameters.
     */
    IndexParams estimateBuildParams()
    {
        std::vector<CostData> costs;

        int sampleSize = int(sample_fraction_ * dataset_.rows);
        int testSampleSize = std::min(sampleSize / 10, 1000);

        Logger::info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d, target precision: %g\n", dataset_.rows, sampleSize, testSampleSize, target_precision_);

        // For a very small dataset, it makes no sense to build any fancy index, just
        // use linear search
        if (testSampleSize < 10) {
            Logger::info("Choosing linear, dataset too small\n");
            return LinearIndexParams();
        }

        // We use a fraction of the original dataset to speedup the autotune algorithm
        sampledDataset_ = random_sample(dataset_, sampleSize);
        // We use a cross-validation approach, first we sample a testset from the dataset
        testDataset_ = random_sample(sampledDataset_, testSampleSize, true);

        // We compute the ground truth using linear search
        Logger::info("Computing ground truth... \n");
        gt_matches_ = Matrix<int>(new int[testDataset_.rows], testDataset_.rows, 1);
        StartStopTimer t;
        t.start();
        compute_ground_truth<Distance>(sampledDataset_, testDataset_, gt_matches_, 0, distance_);
        t.stop();

        CostData linear_cost;
        linear_cost.searchTimeCost = (float)t.value;
        linear_cost.buildTimeCost = 0;
        linear_cost.memoryCost = 0;
        linear_cost.params["algorithm"] = FLANN_INDEX_LINEAR;

        costs.push_back(linear_cost);

        // Start parameter autotune process
        Logger::info("Autotuning parameters...\n");

        optimizeKMeans(costs);
        optimizeKDTree(costs);

        float bestTimeCost = costs[0].searchTimeCost;
        for (size_t i = 0; i < costs.size(); ++i) {
            float timeCost = costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost;
            if (timeCost < bestTimeCost) {
                bestTimeCost = timeCost;
            }
        }

        float bestCost = costs[0].searchTimeCost / bestTimeCost;
        IndexParams bestParams = costs[0].params;
        if (bestTimeCost > 0) {
            for (size_t i = 0; i < costs.size(); ++i) {
                float crtCost = (costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost) / bestTimeCost +
                                memory_weight_ * costs[i].memoryCost;
                if (crtCost < bestCost) {
                    bestCost = crtCost;
                    bestParams = costs[i].params;
                }
            }
        }

        delete[] gt_matches_.data;
        delete[] testDataset_.data;
        delete[] sampledDataset_.data;

        return bestParams;
    }

    /**
     *  Estimates the search time parameters needed to get the desired precision.
     *  Precondition: the index is built
     *  Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search.
     */
    float estimateSearchParams(SearchParams& searchParams)
    {
        const int nn = 1;
        const size_t SAMPLE_COUNT = 1000;

        assert(bestIndex_ != NULL); // must have a valid index

        float speedup = 0;

        int samples = (int)std::min(dataset_.rows / 10, SAMPLE_COUNT);
        if (samples > 0) {
            Matrix<ElementType> testDataset = random_sample(dataset_, samples);

            Logger::info("Computing ground truth\n");

            // we need to compute the ground truth first
            Matrix<int> gt_matches(new int[testDataset.rows], testDataset.rows, 1);
            StartStopTimer t;
            t.start();
            compute_ground_truth<Distance>(dataset_, testDataset, gt_matches, 1, distance_);
            t.stop();
            float linear = (float)t.value;

            int checks;
            Logger::info("Estimating number of checks\n");

            float searchTime;
            float cb_index;
            if (bestIndex_->getType() == FLANN_INDEX_KMEANS) {
                Logger::info("KMeans algorithm, estimating cluster border factor\n");
                KMeansIndex<Distance>* kmeans = (KMeansIndex<Distance>*)bestIndex_;
                float bestSearchTime = -1;
                float best_cb_index = -1;
                int best_checks = -1;
                for (cb_index = 0; cb_index < 1.1f; cb_index += 0.2f) {
                    kmeans->set_cb_index(cb_index);
                    searchTime = test_index_precision(*kmeans, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1);
                    if ((searchTime < bestSearchTime) || (bestSearchTime == -1)) {
                        bestSearchTime = searchTime;
                        best_cb_index = cb_index;
                        best_checks = checks;
                    }
                }
                searchTime = bestSearchTime;
                cb_index = best_cb_index;
                checks = best_checks;

                kmeans->set_cb_index(best_cb_index);
                Logger::info("Optimum cb_index: %g\n", cb_index);
                bestParams_["cb_index"] = cb_index;
            }
            else {
                searchTime = test_index_precision(*bestIndex_, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1);
            }

            Logger::info("Required number of checks: %d \n", checks);
            searchParams["checks"] = checks;

            speedup = linear / searchTime;

            delete[] gt_matches.data;
            delete[] testDataset.data;
        }

        return speedup;
    }

private:
    NNIndex<Distance>* bestIndex_;

    IndexParams bestParams_;
    SearchParams bestSearchParams_;

    Matrix<ElementType> sampledDataset_;
    Matrix<ElementType> testDataset_;
    Matrix<int> gt_matches_;

    float speedup_;

    /**
     * The dataset used by this index
     */
    const Matrix<ElementType> dataset_;

    /**
     * Index parameters
     */
    float target_precision_;
    float build_weight_;
    float memory_weight_;
    float sample_fraction_;

    Distance distance_;

};
}

#endif /* OPENCV_FLANN_AUTOTUNED_INDEX_H_ */


text:
package com.google.zxing.integration.android;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import com.google.zxing.client.android.Intents;
import com.journeyapps.barcodescanner.CaptureActivity;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Sean Owen
 * @author Fred Lin
 * @author Isaac Potoczny-Jones
 * @author Brad Drehmer
 * @author gcstang
 */
@SuppressWarnings("unused")
public class IntentIntegrator {

    public static int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
    private static final String TAG = IntentIntegrator.class.getSimpleName();

    // supported barcode formats
    public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
    public static final Collection<String> ONE_D_CODE_TYPES =
            list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
                    "ITF", "RSS_14", "RSS_EXPANDED");
    public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
    public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");

    public static final Collection<String> ALL_CODE_TYPES = null;

    private final Activity activity;
    private android.app.Fragment fragment;
    private android.support.v4.app.Fragment supportFragment;

    private final Map<String, Object> moreExtras = new HashMap<>(3);

    private Collection<String> desiredBarcodeFormats;

    private Class<?> captureActivity;

    protected Class<?> getDefaultCaptureActivity() {
        return CaptureActivity.class;
    }
    /**
     * @param activity {@link Activity} invoking the integration
     */
    public IntentIntegrator(Activity activity) {
        this.activity = activity;
    }

    public Class<?> getCaptureActivity() {
        if (captureActivity == null) {
            captureActivity = getDefaultCaptureActivity();
        }
        return captureActivity;
    }

    /**
     * Set the Activity class to use. It can be any activity, but should handle the intent extras
     * as used here.
     *
     * @param captureActivity the class
     */
    public IntentIntegrator setCaptureActivity(Class<?> captureActivity) {
        this.captureActivity = captureActivity;
        return this;
    }

    /**
     * @param fragment {@link Fragment} invoking the integration.
     *                 {@link #startActivityForResult(Intent, int)} will be called on the {@link Fragment} instead
     *                 of an {@link Activity}
     */
    public static IntentIntegrator forSupportFragment(android.support.v4.app.Fragment fragment) {
        IntentIntegrator integrator = new IntentIntegrator(fragment.getActivity());
        integrator.supportFragment = fragment;
        return integrator;
    }

    /**
     * @param fragment {@link Fragment} invoking the integration.
     *                 {@link #startActivityForResult(Intent, int)} will be called on the {@link Fragment} instead
     *                 of an {@link Activity}
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static IntentIntegrator forFragment(Fragment fragment) {
        IntentIntegrator integrator = new IntentIntegrator(fragment.getActivity());
        integrator.fragment = fragment;
        return integrator;
    }

    public Map<String, ?> getMoreExtras() {
        return moreExtras;
    }

    public final IntentIntegrator addExtra(String key, Object value) {
        moreExtras.put(key, value);
        return this;
    }

    /**
     * Set a prompt to display on the capture screen, instead of using the default.
     *
     * @param prompt the prompt to display
     */
    public final IntentIntegrator setPrompt(String prompt) {
        if (prompt != null) {
            addExtra(Intents.Scan.PROMPT_MESSAGE, prompt);
        }
        return this;
    }

    /**
     * By default, the orientation is locked. Set to false to not lock.
     *
     * @param locked true to lock orientation
     */
    public IntentIntegrator setOrientationLocked(boolean locked) {
        addExtra(Intents.Scan.ORIENTATION_LOCKED, locked);
        return this;
    }

    /**
     * Use the specified camera ID.
     *
     * @param cameraId camera ID of the camera to use. A negative value means "no preference".
     * @return this
     */
    public IntentIntegrator setCameraId(int cameraId) {
        if (cameraId >= 0) {
            addExtra(Intents.Scan.CAMERA_ID, cameraId);
        }
        return this;
    }

    /**
     * Set to false to disable beep on scan.
     *
     * @param enabled false to disable beep
     * @return this
     */
    public IntentIntegrator setBeepEnabled(boolean enabled) {
        addExtra(Intents.Scan.BEEP_ENABLED, enabled);
        return this;
    }

    /**
     * Set to true to enable saving the barcode image and sending its path in the result Intent.
     *
     * @param enabled true to enable barcode image
     * @return this
     */
    public IntentIntegrator setBarcodeImageEnabled(boolean enabled) {
        addExtra(Intents.Scan.BARCODE_IMAGE_ENABLED, enabled);
        return this;
    }

    /**
     * Set the desired barcode formats to scan.
     *
     * @param desiredBarcodeFormats names of {@code BarcodeFormat}s to scan for
     * @return this
     */
    public IntentIntegrator setDesiredBarcodeFormats(Collection<String> desiredBarcodeFormats) {
        this.desiredBarcodeFormats = desiredBarcodeFormats;
        return this;
    }

    /**
     * Initiates a scan for all known barcode types with the default camera.
     */
    public final void initiateScan() {
        startActivityForResult(createScanIntent(), REQUEST_CODE);
    }

    /**
     * Initiates a scan for all known barcode types with the default camera.
     * And starts a timer to finish on timeout
     * @return Activity.RESULT_CANCELED and true on parameter TIMEOUT.
     */
    public IntentIntegrator setTimeout(long timeout) {
        addExtra(Intents.Scan.TIMEOUT, timeout);
        return this;
    }

    /**
     * Create an scan intent with the specified options.
     *
     * @return the intent
     */
    public Intent createScanIntent() {
        Intent intentScan = new Intent(activity, getCaptureActivity());
        intentScan.setAction(Intents.Scan.ACTION);

        // check which types of codes to scan for
        if (desiredBarcodeFormats != null) {
            // set the desired barcode types
            StringBuilder joinedByComma = new StringBuilder();
            for (String format : desiredBarcodeFormats) {
                if (joinedByComma.length() > 0) {
                    joinedByComma.append(',');
                }
                joinedByComma.append(format);
            }
            intentScan.putExtra(Intents.Scan.FORMATS, joinedByComma.toString());
        }

        intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        attachMoreExtras(intentScan);
        return intentScan;
    }

    /**
     * Initiates a scan, only for a certain set of barcode types, given as strings corresponding
     * to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
     * like {@link #PRODUCT_CODE_TYPES} for example.
     *
     * @param desiredBarcodeFormats names of {@code BarcodeFormat}s to scan for
     */
    public final void initiateScan(Collection<String> desiredBarcodeFormats) {
        setDesiredBarcodeFormats(desiredBarcodeFormats);
        initiateScan();
    }

    /**
     * Start an activity. This method is defined to allow different methods of activity starting for
     * newer versions of Android and for compatibility library.
     *
     * @param intent Intent to start.
     * @param code   Request code for the activity
     * @see android.app.Activity#startActivityForResult(Intent, int)
     * @see android.app.Fragment#startActivityForResult(Intent, int)
     */
    protected void startActivityForResult(Intent intent, int code) {
        if (fragment != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                fragment.startActivityForResult(intent, code);
            }
        } else if (supportFragment != null) {
            supportFragment.startActivityForResult(intent, code);
        } else {
            activity.startActivityForResult(intent, code);
        }
    }

    protected void startActivity(Intent intent) {
        if (fragment != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                fragment.startActivity(intent);
            }
        } else if (supportFragment != null) {
            supportFragment.startActivity(intent);
        } else {
            activity.startActivity(intent);
        }
    }

    /**
     *
Call this from your {@link Activity}'s
     * {@link Activity#onActivityResult(int, int, Intent)} method.

     *
     * @param requestCode request code from {@code onActivityResult()}
     * @param resultCode  result code from {@code onActivityResult()}
     * @param intent      {@link Intent} from {@code onActivityResult()}
     * @return null if the event handled here was not related to this class, or
     * else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
     * the fields will be null.
     */
    public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String contents = intent.getStringExtra(Intents.Scan.RESULT);
                String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
                byte[] rawBytes = intent.getByteArrayExtra(Intents.Scan.RESULT_BYTES);
                int intentOrientation = intent.getIntExtra(Intents.Scan.RESULT_ORIENTATION, Integer.MIN_VALUE);
                Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
                String errorCorrectionLevel = intent.getStringExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL);
                String barcodeImagePath = intent.getStringExtra(Intents.Scan.RESULT_BARCODE_IMAGE_PATH);
                return new IntentResult(contents,
                        formatName,
                        rawBytes,
                        orientation,
                        errorCorrectionLevel,
                        barcodeImagePath);
            }
            return new IntentResult();
        }
        return null;
    }

    private static List<String> list(String... values) {
        return Collections.unmodifiableList(Arrays.asList(values));
    }

    private void attachMoreExtras(Intent intent) {
        for (Map.Entry<String, Object> entry : moreExtras.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // Kind of hacky
            if (value instanceof Integer) {
                intent.putExtra(key, (Integer) value);
            } else if (value instanceof Long) {
                intent.putExtra(key, (Long) value);
            } else if (value instanceof Boolean) {
                intent.putExtra(key, (Boolean) value);
            } else if (value instanceof Double) {
                intent.putExtra(key, (Double) value);
            } else if (value instanceof Float) {
                intent.putExtra(key, (Float) value);
            } else if (value instanceof Bundle) {
                intent.putExtra(key, (Bundle) value);
            } else {
                intent.putExtra(key, value.toString());
            }
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Persoonia 3(1): 76 (1964)

#### Original name
null

### Remarks
null


text:
 #import "FBSDKLoginError.h"

 #ifdef FBSDKCOCOAPODS
  #import <FBSDKCoreKit/FBSDKCoreKit+Internal.h>
 #else
  #import "FBSDKCoreKit+Internal.h"
 #endif

 #ifndef NS_ERROR_ENUM
  #define NS_ERROR_ENUM(_domain, _name) \
  enum _name : NSInteger _name; \
  enum __attribute__((ns_error_domain(_domain))) _name: NSInteger
 #endif

typedef NS_ERROR_ENUM(FBSDKLoginErrorDomain, FBSDKLoginErrorSubcode)
{
  FBSDKLoginErrorSubcodeUserCheckpointed = 459,
  FBSDKLoginErrorSubcodePasswordChanged = 460,
  FBSDKLoginErrorSubcodeUnconfirmedUser = 464,
};

@implementation NSError (FBSDKLoginError)

+ (NSError *)fbErrorForFailedLoginWithCode:(FBSDKLoginError)code
{
  return [self fbErrorForFailedLoginWithCode:code innerError:nil];
}

+ (NSError *)fbErrorForFailedLoginWithCode:(FBSDKLoginError)code
                                innerError:(NSError *)innerError
{
  NSMutableDictionary<NSString *, id> *userInfo = [NSMutableDictionary dictionary];

  [FBSDKTypeUtility dictionary:userInfo setObject:innerError forKey:NSUnderlyingErrorKey];

  NSString *errorDomain = FBSDKLoginErrorDomain;
  NSString *localizedDescription = nil;

  switch ((NSInteger)code) {
    case FBSDKErrorNetwork:
      errorDomain = FBSDKErrorDomain;
      localizedDescription =
      NSLocalizedStringWithDefaultValue(
        @"LoginError.SystemAccount.Network",
        @"FacebookSDK",
        [FBSDKInternalUtility bundleForStrings],
        @"Unable to connect to Facebook. Check your network connection and try again.",
        @"The user facing error message when the Accounts framework encounters a network error."
      );
      break;
    case FBSDKLoginErrorUserCheckpointed:
      localizedDescription =
      NSLocalizedStringWithDefaultValue(
        @"LoginError.SystemAccount.UserCheckpointed",
        @"FacebookSDK",
        [FBSDKInternalUtility bundleForStrings],
        @"You cannot log in to apps at this time. Please log in to www.facebook.com and follow the instructions given.",
        @"The user facing error message when the Facebook account signed in to the Accounts framework has been checkpointed."
      );
      break;
    case FBSDKLoginErrorUnconfirmedUser:
      localizedDescription =
      NSLocalizedStringWithDefaultValue(
        @"LoginError.SystemAccount.UnconfirmedUser",
        @"FacebookSDK",
        [FBSDKInternalUtility bundleForStrings],
        @"Your account is not confirmed. Please log in to www.facebook.com and follow the instructions given.",
        @"The user facing error message when the Facebook account signed in to the Accounts framework becomes unconfirmed."
      );
      break;
    case FBSDKLoginErrorSystemAccountAppDisabled:
      localizedDescription =
      NSLocalizedStringWithDefaultValue(
        @"LoginError.SystemAccount.Disabled",
        @"FacebookSDK",
        [FBSDKInternalUtility bundleForStrings],
        @"Access has not been granted to the Facebook account. Verify device settings.",
        @"The user facing error message when the app slider has been disabled and login fails."
      );
      break;
    case FBSDKLoginErrorSystemAccountUnavailable:
      localizedDescription =
      NSLocalizedStringWithDefaultValue(
        @"LoginError.SystemAccount.Unavailable",
        @"FacebookSDK",
        [FBSDKInternalUtility bundleForStrings],
        @"The Facebook account has not been configured on the device.",
        @"The user facing error message when the device Facebook account is unavailable and login fails."
      );
      break;
    default:
      break;
  }

  [FBSDKTypeUtility dictionary:userInfo setObject:localizedDescription forKey:NSLocalizedDescriptionKey];
  [FBSDKTypeUtility dictionary:userInfo setObject:localizedDescription forKey:FBSDKErrorLocalizedDescriptionKey];

  return [NSError errorWithDomain:errorDomain
                             code:code
                         userInfo:userInfo];
}

+ (NSError *)fbErrorForSystemPasswordChange:(NSError *)innerError
{
  NSString *failureReasonAndDescription =
  NSLocalizedStringWithDefaultValue(
    @"LoginError.SystemAccount.PasswordChange",
    @"FacebookSDK",
    [FBSDKInternalUtility bundleForStrings],
    @"Your Facebook password has changed. To confirm your password, open Settings > Facebook and tap your name.",
    @"The user facing error message when the device Facebook account password is incorrect and login fails."
  );
  NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   failureReasonAndDescription, FBSDKErrorLocalizedDescriptionKey,
                                   failureReasonAndDescription, NSLocalizedDescriptionKey,
                                   nil];

  [FBSDKTypeUtility dictionary:userInfo setObject:innerError forKey:NSUnderlyingErrorKey];

  return [NSError errorWithDomain:FBSDKLoginErrorDomain
                             code:FBSDKLoginErrorPasswordChanged
                         userInfo:userInfo];
}

+ (NSError *)fbErrorFromReturnURLParameters:(NSDictionary *)parameters
{
  NSError *error = nil;

  NSMutableDictionary<NSString *, id> *userInfo = [NSMutableDictionary new];
  [FBSDKTypeUtility dictionary:userInfo setObject:[FBSDKTypeUtility dictionary:parameters objectForKey:@"error_message" ofType:NSString.class] forKey:FBSDKErrorDeveloperMessageKey];

  if (userInfo.count > 0) {
    [FBSDKTypeUtility dictionary:userInfo setObject:[FBSDKTypeUtility dictionary:parameters objectForKey:@"error" ofType:NSString.class] forKey:FBSDKErrorDeveloperMessageKey];
    [FBSDKTypeUtility dictionary:userInfo setObject:[FBSDKTypeUtility dictionary:parameters objectForKey:@"error_code" ofType:NSString.class] forKey:FBSDKGraphRequestErrorGraphErrorCodeKey];

    if (!userInfo[FBSDKErrorDeveloperMessageKey]) {
      [FBSDKTypeUtility dictionary:userInfo setObject:[FBSDKTypeUtility dictionary:parameters objectForKey:@"error_reason" ofType:NSString.class] forKey:FBSDKErrorDeveloperMessageKey];
    }

    [FBSDKTypeUtility dictionary:userInfo setObject:@(FBSDKGraphRequestErrorOther) forKey:FBSDKGraphRequestErrorKey];

    error = [NSError errorWithDomain:FBSDKErrorDomain
                                code:FBSDKErrorGraphRequestGraphAPI
                            userInfo:userInfo];
  }

  return error;
}

+ (NSError *)fbErrorFromServerError:(NSError *)serverError
{
  NSError *loginError = nil;

  if ([serverError.domain isEqualToString:FBSDKErrorDomain]) {
    NSDictionary *response = [FBSDKTypeUtility dictionaryValue:serverError.userInfo[FBSDKGraphRequestErrorParsedJSONResponseKey]];
    NSDictionary *body = [FBSDKTypeUtility dictionaryValue:response[@"body"]];
    NSDictionary *error = [FBSDKTypeUtility dictionaryValue:body[@"error"]];
    NSInteger subcode = [FBSDKTypeUtility integerValue:error[@"error_subcode"]];

    switch (subcode) {
      case FBSDKLoginErrorSubcodeUserCheckpointed:
        loginError = [self fbErrorForFailedLoginWithCode:FBSDKLoginErrorUserCheckpointed
                                              innerError:serverError];
        break;
      case FBSDKLoginErrorSubcodePasswordChanged:
        loginError = [self fbErrorForFailedLoginWithCode:FBSDKLoginErrorPasswordChanged
                                              innerError:serverError];
        break;
      case FBSDKLoginErrorSubcodeUnconfirmedUser:
        loginError = [self fbErrorForFailedLoginWithCode:FBSDKLoginErrorUnconfirmedUser
                                              innerError:serverError];
        break;
    }
  }

  return loginError;
}

+ (NSError *)fbErrorWithSystemAccountStoreDeniedError:(NSError *)accountStoreError
                                       isCancellation:(BOOL *)cancellation
{
  // The Accounts framework returns an ACErrorPermissionDenied error for both user denied errors,
  // Facebook denied errors, and other things. Unfortunately examining the contents of the
  // description is the only means available to determine the reason for the error.
  NSString *description = accountStoreError.userInfo[NSLocalizedDescriptionKey];
  NSError *err = nil;

  if (description) {
    // If a parenthetical error code exists, map it ot a Facebook server error
    FBSDKLoginError errorCode = FBSDKLoginErrorReserved;
    if ([description rangeOfString:@"(459)"].location != NSNotFound) {
      // The Facebook server could not fulfill this access request: Error validating access token:
      // You cannot access the app till you log in to www.facebook.com and follow the instructions given. (459)

      // The OAuth endpoint directs people to www.facebook.com when an account has been
      // checkpointed. If the web address is present, assume it's due to a checkpoint.
      errorCode = FBSDKLoginErrorUserCheckpointed;
    } else if ([description rangeOfString:@"(452)"].location != NSNotFound
               || [description rangeOfString:@"(460)"].location != NSNotFound) {
      // The Facebook server could not fulfill this access request: Error validating access token:
      // Session does not match current stored session. This may be because the user changed the password since
      // the time the session was created or Facebook has changed the session for security reasons. (452)or(460)

      // If the login failed due to the session changing, maybe it's due to the password
      // changing. Direct the user to update the password in the Settings > Facebook.
      err = [self fbErrorForSystemPasswordChange:accountStoreError];
    } else if ([description rangeOfString:@"(464)"].location != NSNotFound) {
      // The Facebook server could not fulfill this access request: Error validating access token:
      // Sessions for the user  are not allowed because the user is not a confirmed user. (464)
      errorCode = FBSDKLoginErrorUnconfirmedUser;
    }

    if (errorCode != FBSDKLoginErrorReserved) {
      err = [self fbErrorForFailedLoginWithCode:errorCode];
    }
  } else {
    // If there is no description, assume this is a user cancellation. No error object is
    // returned for a cancellation.
    if (cancellation != NULL) {
      *cancellation = YES;
    }
  }

  return err;
}

@end

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Catillaria hoeferi Körb.

### Remarks
null


text:
<?php
/**
 * Auto generated from PB_server_common.proto at 2018-01-24 16:26:41
 *
 * protos package
 */

namespace Protos {
/**
 * RouterPolicy enum embedded in PBS_ServerRegister message
 */
final class PBS_ServerRegister_RouterPolicy
{
    const RoundRobin = 1;

    /**
     * Returns defined enum values
     *
     * @return int[]
     */
    public function getEnumValues()
    {
        return array(
            'RoundRobin' => self::RoundRobin,
        );
    }
}
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi;

import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author cdr
 */
public interface PsiAnnotationOwner {
  /**
   * Returns the list of annotations syntactically contained in the element.
   *
   * @return the list of annotations.
   */
  PsiAnnotation @NotNull [] getAnnotations();

  /**
   * @return the list of annotations which are applicable to this owner
   *         (e.g. type annotations on method belong to its type element, not the method).
   */
  PsiAnnotation @NotNull [] getApplicableAnnotations();

  /**
   * Searches the owner for an annotation with the specified fully qualified name
   * and returns one if it is found.
   *
   * @param qualifiedName the fully qualified name of the annotation to find.
   * @return the annotation instance, or null if no such annotation is found.
   */
  @Nullable
  PsiAnnotation findAnnotation(@NotNull @NonNls String qualifiedName);

  /**
   * Searches the owner for an annotation with the specified fully qualified name
   * and returns {@code true} if it is found.
   * <p/>
   * This method is preferable over {@link #findAnnotation}
   * since implementations are free not to instantiate the {@link PsiAnnotation}.
   *
   * @param qualifiedName the fully qualified name of the annotation to find
   * @return {@code true} is such annotation is found, otherwise {@code false}
   */
  default boolean hasAnnotation(@NotNull @NonNls String qualifiedName) {
    //noinspection SSBasedInspection
    return findAnnotation(qualifiedName) != null;
  }

  /**
   * Adds a new annotation to this owner. The annotation class name will be shortened. No attributes will be defined.
   *
   * @param qualifiedName qualifiedName
   * @return newly added annotation
   */
  @NotNull
  PsiAnnotation addAnnotation(@NotNull @NonNls String qualifiedName);
}


text:
          <button class="search-term btn btn-default" type="button">Go!</button>

        <input type="text" class="term-search-text form-control" placeholder="Search for...">

          {{#terms}}

{{type}}

{{.}}

                            View Details

          {{/terms}}

    {{#show}}

        Previous

        Next

    {{/show}}

Reviews being compared

    <button type="button" class="btn btn-primary compare-button">Compare</button>


text:
/*			VERSION 20180311
TODO:--------------------------------------------------------------------------
-------------------------------------------------------------------------------
*/

const canvas = document.getElementById('gameCanvas');
const canvasContext = canvas.getContext('2d');
let ballX; // define these in ballReset() & paddleReset()
let ballY;
let ballSpeedX;
let ballSpeedY;
let paddleX;
const rainbowColors = [
	'#FF0000', '#E2571E', '#FF7F00', '#FFFF00', '#00FF00',
	'#96bf33', '#0000FF', '#4B0082', '#8B00FF', '#ffffff'
]; // rainbow color spectrum in hex codes
const ballRadius = 5;
const paddleDistanceFromSide = 60;
const paddleThickness = 12;
const paddleLength = 85;
const paddleY = canvas.height - paddleDistanceFromSide - paddleThickness;
const deflectionRate = 9;
const brickWidth = 50;
const brickHeight = 25;
const brickCols = 16;
const brickRows = 10;
const brickGap = 2;
const brickGrid = new Array(brickCols * brickRows);
let score;
let multiplier;
let lives;
let showStartScreen;
let showPauseScreen;
let showEndScreen;
let bricksLeft;
let timeLeft;

let leftArrowHeld;
let rightArrowHeld;

function ballReset() {
	ballX = canvas.width / 3;
	ballY = canvas.height * 3 / 5;
	ballSpeedX = 3;
	ballSpeedY = 3;
	paddleX = canvas.width / 2 - paddleLength / 2;

	if (lives > 0) {
		lives--;
	}
}

function paddleReset() {
	paddleX = canvas.width / 2 - paddleLength / 2;
}

function setup() {
	let i;
	showStartScreen = true;
	showPauseScreen = false;
	showEndScreen = false;

	leftArrowHeld = false;
	rightArrowHeld = false;

	ballReset();
	paddleReset();
	// score reset
	score = 0;
	multiplier = 0;
	// timer reset
	timeLeft = 7200; // 7200 frames -> 120 seconds at 60 fps
	// lives reset
	lives = 3;
	// brick setup
	bricksLeft = brickCols * brickRows;

	bricksLeft = brickRows * brickCols;

	for (i = 0; i < 3 * brickCols; i++) {
		brickGrid[i] = false;
		bricksLeft--;
	}

	for (; i < brickCols * brickRows; i++) { // set all bricks to true (visible)
		/*
			if(Math.random()>0.5){
				brickGrid[i] = true;
			}else{
				brickGrid[i] = false;
			}
		*/
		brickGrid[i] = true;
	}
}
/*
function calculateMousePos(event){
	var rect = canvas.getBoundingClientRect();
	var root = document.documentElement;
	mouseX = event.clientX - rect.left - root.scrollLeft;
	mouseY = event.clientY - rect.top - root.scrollTop;

	paddleX = mouseX - paddleLength/2;

}
*/
function handleKeyPress(event) {
	switch (event.keyCode) {
		case 32: // space
			if (showStartScreen) {
				setup();
				showStartScreen = false;
			} else if (showPauseScreen) {
				showPauseScreen = false;
			} else if (showEndScreen) {
				setup();
			}
			break;
		case 13: // return, enter
			if (showStartScreen) {
				setup();
				showStartScreen = false;
			} else if (showPauseScreen) {
				showPauseScreen = false;
			} else if (showEndScreen) {
				setup();
			}
			break;
		default:
	}
	if (!showStartScreen && !showEndScreen && !showPauseScreen) {
		switch (event.keyCode) {
			case 27: // Esc
				showPauseScreen = true;
				break;
			case 37: // left arrow
				leftArrowHeld = true;
				break;
			case 39: // right arrow
				rightArrowHeld = true;
				break;
			case 65: // a key
				leftArrowHeld = true;
				break;
			case 68: // d key
				rightArrowHeld = true;
				break;
			default:
		}
	}
}

function handleKeyUp(event) {
	if (!showStartScreen && !showEndScreen && !showPauseScreen) {
		switch (event.keyCode) {
			case 37: // left arrow
				leftArrowHeld = false;
				break;
			case 39: // right arrow
				rightArrowHeld = false;
				break;
			default:
		}

		if (event.keyCode === 37) { // Left arrow
			leftArrowHeld = false;
		}
		if (event.keyCode === 39) { // Right arrow
			rightArrowHeld = false;
		}
		if (event.keyCode === 65)	{	// a key
			leftArrowHeld = false;
		}
		if (event.keyCode === 68) {	// d key
			rightArrowHeld = false;
		}
	}
}

window.onload = function() {
	setup();
	const framesPerSecond = 60;

	setInterval(() => {
		moveEverything();
		drawEverything();
	}, 1000 / framesPerSecond);
	// canvas.addEventListener('mousemove', calculateMousePos);
	window.addEventListener('keydown', handleKeyPress);
	window.addEventListener('keyup', handleKeyUp);

	// add math methods radians and degree for conversion
	Math.radians = function(degrees) {
		return degrees * Math.PI / 180;
	};
	Math.degrees = function(radians) {
		return radians * 180 / Math.PI;
	};
};

function hitBrickScoring() {
	score -= multiplier ** 2; // remove old multiplier score
	multiplier += 1; // update multiplier
	score += multiplier ** 2; // add bigger score
}

function hitPaddleScoring() {
	multiplier = 0;
}

function ballMove() {
	ballX += ballSpeedX; // move ball
	ballY += ballSpeedY;

	if (ballX - ballRadius <= 0) { // left reflection
		ballSpeedX = -ballSpeedX;
	}
	if (ballX + ballRadius >= canvas.width) { // right reflection
		ballSpeedX = -ballSpeedX;
	}
	if (ballY - ballRadius <= 0) { // top reflection
		ballSpeedY = -ballSpeedY;
	}
	if (ballY - ballRadius >= canvas.height) { // ball is below the bottom side
		ballReset();
	}
}

function findColRowFromCoordinates(x, y) {
	// function to find the previous row and col of an x and y pair
	const pbx = x - ballSpeedX;
	const pby = y - ballSpeedY;
	const col = Math.floor(pbx / brickWidth);
	const row = Math.floor(pby / brickHeight);

	// use es6 notation https://eslint.org/docs/rules/object-shorthand
	return {
		col,
		row
	};
}

function ballBrickHandling() {
	for (let angle = 0; angle < 359; angle++) {
		const x = ballX + ballRadius * Math.cos(Math.radians(angle));
		const y = ballY + ballRadius * Math.sin(Math.radians(angle));

		const ballBrickCol = Math.floor(x / brickWidth);
		const ballBrickRow = Math.floor(y / brickHeight);

		const brickIndexUnderBall = rowColToArrayIndex(ballBrickCol, ballBrickRow);

		if (ballBrickCol >= 0 && ballBrickCol < brickCols &&
			ballBrickRow >= 0 && ballBrickRow < brickRows &&
			brickGrid[brickIndexUnderBall] === true) { // brick is activated
			brickGrid[brickIndexUnderBall] = false; // delete brick
			bricksLeft--;

			// brickGrid.every(function(bool){return bool == false;}) was used before
			if (bricksLeft === 0) { // Game finished
				showEndScreen = true;
			}

			// Check where the ball was before, and reflecting the ball accordingly
			const previousBallPosition = findColRowFromCoordinates(x, y);
			// 8 possibilities
			if (previousBallPosition.col < ballBrickCol && previousBallPosition.row < ballBrickRow || // DIAGONAL TOP LEFT
				previousBallPosition.col > ballBrickCol && previousBallPosition.row < ballBrickRow || // DIAGONAL TOP RIGHT
				previousBallPosition.col < ballBrickCol && previousBallPosition.row > ballBrickRow || // DIAGONAL BOTTOM LEFT
				previousBallPosition.col > ballBrickCol && previousBallPosition.row > ballBrickRow) { // DIAGONAL BOTTOM RIGHT
				// reflect
				ballSpeedY = -ballSpeedY;
				ballSpeedX = -ballSpeedX;
			}
			if (previousBallPosition.col !== ballBrickCol) { // LEFT OR RIGHT
				// reflect
				ballSpeedX = -ballSpeedX;
			}
			if (previousBallPosition.row !== ballBrickRow) { // TOP OR BOTTOM
				// reflect
				ballSpeedY = -ballSpeedY;
			}

			hitBrickScoring(); // scoring
		}
	}
}

function ballPaddleHandling() {
	for (let angle = 0; angle < 359; angle++) {
		const x = ballX + ballRadius * Math.cos(Math.radians(angle));
		const y = ballY + ballRadius * Math.sin(Math.radians(angle));

		// reflect the ball off the paddle
		if (y >= paddleY && // below top of paddle
			y <= paddleY + paddleThickness && // above bottom of paddle
			x >= paddleX && // right of the left side of the paddle
			x <= paddleX + paddleLength) { // left of the right side of the paddle
			const previousBallY = y - ballSpeedY;
			const previousBallX = x - ballSpeedX;

			if (previousBallX < paddleX || previousBallX > paddleX + paddleLength && // diagonal x
				previousBallY < paddleY || previousBallY > paddleY + paddleThickness) { // diagonal y
				ballSpeedY = -ballSpeedY;
				ballSpeedX = -ballSpeedX;
			} else if (previousBallY < paddleY || previousBallY > paddleY + paddleThickness) { // y off, collision top or bottom
				ballSpeedY = -ballSpeedY;
			}

			// changing the X-Speed before won't matter, because it gets reassigned here anyways
			// that is why it is not needed to check the x (left or right collision)

			const paddleCenterX = paddleX + paddleLength / 2; // make the X-Speed larger if the ball is hit further away from the center of the paddle
			const deltaX = x - paddleCenterX;
			ballSpeedX = deltaX / deflectionRate;

			hitPaddleScoring(); // scoring
		}
	}
}

function paddleMove() {
	if (leftArrowHeld && paddleX + paddleLength / 2 >= 0) { // paddle off screen
		paddleX -= 4;
	} else if (rightArrowHeld && paddleX + paddleLength / 2 <= canvas.width) {
		paddleX += 4;
	}
}

function moveEverything() {
	if (!showStartScreen && !showPauseScreen && !showEndScreen) { // game active
		paddleMove();
		ballMove();
		ballBrickHandling();
		ballPaddleHandling();

		if (timeLeft <= 0 || lives <= 0) {
			showEndScreen = true;
		} else {
			timeLeft -= 1;
		}
	}
}

function rowColToArrayIndex(col, row) {
	return col + brickCols * row; // function to return index of brick at a column and a row
}

function drawBricks() {
	for (let eachRow = 0; eachRow < brickRows; eachRow++) { // two for loops to iterate through drawing the cols and rows
		for (let eachCol = 0; eachCol < brickCols; eachCol++) { // eachRow and eachCol are the loop variables
			const arrayIndex = rowColToArrayIndex(eachCol, eachRow); // make a variable to map all bricks to an index
			if (brickGrid[arrayIndex]) {
				colorRect(brickWidth * eachCol + 1, brickHeight * eachRow, brickWidth - brickGap, brickHeight - brickGap, rainbowColors[eachRow - 3]); // drawEverything rainbowColors[i] to loop throught the array
			}
		}
	}
}

function drawEverything() {
	// black canvas background
	colorRect(0, 0, canvas.width, canvas.height, 'black');

	// game
	if (!showStartScreen && !showPauseScreen && !showEndScreen) {
		// ball
		colorCircle(ballX, ballY, ballRadius, 'white');
		// player paddle
		colorRect(paddleX, paddleY, paddleLength, paddleThickness, 'gray');
		// bricks
		drawBricks();
		// text bottom right score
		drawText(score, canvas.width - 20, canvas.height - 20, 'end', 'red', '40px arial black');
		// text bottom left lives
		drawText(lives, 20, canvas.height - 20, 'start', 'red', '40px arial black');
	}

	// start screen
	if (showStartScreen) {
		drawText('BRICK BREAKER', canvas.width / 2, canvas.height / 2, 'center', 'white', '80px comic sans ms');
		drawText('Press SPACE to play', canvas.width / 2, canvas.height / 4 * 3, 'center', 'white', '40px verdana');
	}
	// pause screen
	if (showPauseScreen) {
		drawText('Game Paused', canvas.width / 2, canvas.height / 2, 'center', 'white', '80px arial black');
		drawText('Press SPACE to continue playing', canvas.width / 2, canvas.height / 4 * 3, 'center', 'white', '20px arial');

		/*
		//score detailed
		drawText('Score: ' + score, canvas.width - 20, canvas.height - 20, 'end', 'red', '30px arial black')
		if(lives < 1){
			drawText('No more lives left!', 20, canvas.height - 20, 'start', 'red', '30px arial black')
		}else{
			drawText('Lives left: ' + lives, 20, canvas.height - 20, 'start', 'red', '30px arial black')
		}
		*/
	}

	if (showEndScreen) {
		drawText('Well done!', canvas.width / 2, canvas.height / 4, 'center', 'white', '25px arial black');
		drawText(score, canvas.width / 2, canvas.height / 4 * 3, 'center', 'magenta', '80px verdana');
	}
}

function colorRect(leftX, topY, width, height, drawColor) {
	canvasContext.fillStyle = drawColor;
	canvasContext.fillRect(leftX, topY, width, height);
}

function colorCircle(centerX, centerY, radius, drawColor) {
	canvasContext.fillStyle = drawColor;
	canvasContext.beginPath(); // prepare for filling
	canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true); // create arc
	canvasContext.fill(); // no .arcfill so this fill method
}

function drawText(text, X, Y, alignment, drawColor, font = '10px sans-serif') {
	canvasContext.font = font;
	canvasContext.fillStyle = drawColor;
	canvasContext.textAlign = alignment;
	canvasContext.fillText(text, X, Y);
}


text:
if defined?(::Rails)

require File.expand_path(File.join(File.dirname(__FILE__),'..','..','..','test_helper'))
require 'new_relic/agent/instrumentation/action_controller_subscriber'

class NewRelic::Agent::Instrumentation::ActionControllerSubscriberTest < Minitest::Test
  class TestController
    include NewRelic::Agent::Instrumentation::ControllerInstrumentation

    def self.controller_path
      'test'
    end

    def action_name
      'test'
    end

    newrelic_ignore :only => :ignored_action
    newrelic_ignore_apdex :only => :ignored_apdex
    newrelic_ignore_enduser :only => :ignored_enduser
  end

  def setup
    freeze_time
    @subscriber = NewRelic::Agent::Instrumentation::ActionControllerSubscriber.new
    NewRelic::Agent.instance.stats_engine.clear_stats
    @entry_payload = {
      :controller => TestController.to_s,
      :action => 'index',
      :format => :html,
      :method => 'GET',
      :path => '/tests',
      :params => { :controller => 'test_controller', :action => 'index' },
    }
    @exit_payload = @entry_payload.merge(:status => 200, :view_runtime => 5.0,
                                         :db_runtime => 0.5 )
    @stats_engine = NewRelic::Agent.instance.stats_engine
    @stats_engine.clear_stats
    NewRelic::Agent.manual_start
    NewRelic::Agent::TransactionState.tl_clear_for_testing
  end

  def teardown
    NewRelic::Agent.shutdown
    @stats_engine.clear_stats
  end

  def test_record_controller_metrics
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    advance_time(2)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    expected_values = { :call_count => 1, :total_call_time => 2.0 }
    assert_metrics_recorded(
      'Controller/test/index' => expected_values,
      'HttpDispatcher' => expected_values
    )
  end

  def test_record_apdex_metrics
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    advance_time(1.5)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    expected_values = { :apdex_f => 0, :apdex_t => 1, :apdex_s => 0 }
    assert_metrics_recorded(
      'Apdex/test/index' => expected_values,
      'Apdex' => expected_values
    )
  end

  def test_record_apdex_metrics_with_error
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    advance_time(1.5)

    error = StandardError.new("boo")
    @exit_payload[:exception] = error
    NewRelic::Agent.notice_error(error)

    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    expected_values = { :apdex_f => 1, :apdex_t => 0, :apdex_s => 0 }
    assert_metrics_recorded(
      'Apdex/test/index' => expected_values,
      'Apdex' => expected_values
    )
  end

  def test_records_scoped_metrics_for_evented_child_txn
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.start('process_action.action_controller', :id, @entry_payload \
                        .merge(:action => 'child', :path => '/child'))
    @subscriber.finish('process_action.action_controller', :id, @exit_payload \
                         .merge(:action => 'child', :path => '/child'))
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_metrics_recorded(
      ['Nested/Controller/test/child', 'Controller/test/child'] => { :call_count => 1 }
    )
  end

  def test_records_scoped_metrics_for_traced_child_txn
    controller = TestController.new
    controller.perform_action_with_newrelic_trace(:category => :controller,
                                                  :name => 'index',
                                                  :class_name => 'test') do
      @subscriber.start('process_action.action_controller', :id, @entry_payload \
                          .merge(:action => 'child', :path => '/child'))
      @subscriber.finish('process_action.action_controller', :id, @exit_payload \
                           .merge(:action => 'child', :path => '/child'))
    end

    assert_metrics_recorded(
      ['Nested/Controller/test/child', 'Controller/test/child'] => { :call_count => 1 }
    )
  end

  def test_sets_default_transaction_name_on_start
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    assert_equal 'Controller/test/index', NewRelic::Agent::Transaction.tl_current.best_name
  ensure
    @subscriber.finish('process_action.action_controller', :id, @entry_payload)
  end

  def test_sets_default_transaction_keeps_name_through_stop
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    txn = NewRelic::Agent::Transaction.tl_current
    @subscriber.finish('process_action.action_controller', :id, @entry_payload)
    assert_equal 'Controller/test/index', txn.best_name
  end

  def test_sets_transaction_name
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    NewRelic::Agent.set_transaction_name('something/else')
    assert_equal 'Controller/something/else', NewRelic::Agent::Transaction.tl_current.best_name
  ensure
    @subscriber.finish('process_action.action_controller', :id, @entry_payload)
  end

  def test_sets_transaction_name_holds_through_stop
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    txn = NewRelic::Agent::Transaction.tl_current
    NewRelic::Agent.set_transaction_name('something/else')
    @subscriber.finish('process_action.action_controller', :id, @entry_payload)
    assert_equal 'Controller/something/else', txn.best_name
  end

  def test_record_nothing_for_ignored_action
    @entry_payload[:action] = 'ignored_action'
    @exit_payload[:action] = 'ignored_action'
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_metrics_not_recorded([
      'Controller/test/ignored_action',
      'Apdex/test/ignored_action',
      'Apdex',
      'HttpDispatcher'
    ])
  end

  def test_record_no_apdex_metric_for_ignored_apdex_action
    @entry_payload[:action] = 'ignored_apdex'
    @exit_payload[:action] = 'ignored_apdex'
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_metrics_recorded(['Controller/test/ignored_apdex', 'HttpDispatcher'])
    assert_metrics_not_recorded(['Apdex', 'Apdex/test/ignored_apdex'])
  end

  def test_ignore_end_user
    @entry_payload[:action] = 'ignored_enduser'
    @exit_payload[:action] = 'ignored_enduser'
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    txn = NewRelic::Agent::Transaction.tl_current
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert txn.ignore_enduser?
  end

  def test_record_busy_time
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    advance_time(1)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)
    NewRelic::Agent::BusyCalculator.harvest_busy

    assert_metrics_recorded('Instance/Busy' => { :call_count => 1, :total_call_time => 1.0 })
  end

  def test_creates_transaction
    NewRelic::Agent.instance.transaction_sampler.reset!
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_equal('Controller/test/index',
                 NewRelic::Agent.instance.transaction_sampler \
                   .last_sample.params[:path])
    assert_equal('Controller/test/index',
                 NewRelic::Agent.instance.transaction_sampler \
                   .last_sample.root_segment.called_segments[0].metric_name)
  end

  def test_applies_txn_name_rules
    rule_specs = [{'match_expression' => 'test', 'replacement' => 'taste'}]

    with_transaction_renaming_rules(rule_specs) do
      @subscriber.start('process_action.action_controller', :id, @entry_payload)
      @subscriber.finish('process_action.action_controller', :id, @exit_payload)
    end

    assert_metrics_recorded(['Controller/taste/index'])
    assert_metrics_not_recorded(['Controller/test/index'])
  end

  def test_record_queue_time_metrics
    app = lambda do |env|
      @subscriber.start('process_action.action_controller', :id, @entry_payload)
      advance_time(2)
      @subscriber.finish('process_action.action_controller', :id, @exit_payload)
    end

    t0 = Time.now
    env = { 'HTTP_X_REQUEST_START' => (t0 - 5).to_f.to_s }
    ::NewRelic::Rack::AgentHooks.new(app).call(env)

    assert_metrics_recorded(
      'WebFrontend/QueueTime' => {
        :call_count => 1,
        :total_call_time => 5.0
      }
    )
  end

  def test_dont_record_queue_time_if_no_header
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_metrics_not_recorded('WebFrontend/QueueTime')
  end

  def test_dont_record_queue_time_in_nested_transaction
    app = lambda do |env|
      @subscriber.start('process_action.action_controller',  :id, @entry_payload)
      @subscriber.start('process_action.action_controller',  :id, @entry_payload)
      @subscriber.finish('process_action.action_controller', :id, @exit_payload)
      @subscriber.finish('process_action.action_controller', :id, @exit_payload)
    end

    t0 = Time.now
    env = { 'HTTP_X_REQUEST_START' => (t0 - 5).to_f.to_s }
    ::NewRelic::Rack::AgentHooks.new(app).call(env)

    assert_metrics_recorded(
      'WebFrontend/QueueTime' => {
        :call_count => 1,
        :total_call_time => 5.0
      }
    )
  end

  def test_records_request_params_in_txn
    NewRelic::Agent.instance.transaction_sampler.reset!
    @entry_payload[:params]['number'] = '666'
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_equal('666',
                 NewRelic::Agent.instance.transaction_sampler \
                   .last_sample.params[:request_params]['number'])
  end

  def test_records_filtered_request_params_in_txn
    NewRelic::Agent.instance.transaction_sampler.reset!
    @entry_payload[:params]['password'] = 'secret'
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_equal('[FILTERED]',
                 NewRelic::Agent.instance.transaction_sampler \
                   .last_sample.params[:request_params]['password'])
  end

  def test_records_custom_parameters_in_txn
    NewRelic::Agent.instance.transaction_sampler.reset!
    @subscriber.start('process_action.action_controller', :id, @entry_payload)
    NewRelic::Agent.add_custom_parameters('number' => '666')
    @subscriber.finish('process_action.action_controller', :id, @exit_payload)

    assert_equal('666',
                 NewRelic::Agent.instance.transaction_sampler \
                   .last_sample.params[:custom_params]['number'])
  end
end if ::Rails::VERSION::MAJOR.to_i >= 4

else
  puts "Skipping tests in #{__FILE__} because Rails is unavailable"
end


text:
<?xml version="1.0" encoding="utf-8"?>

<!--重要按钮字体颜色-->

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/color999999" android:state_enabled="false"/>

    <item android:color="@color/colorE7E7E7" android:state_pressed="true"/>

    <item android:color="@color/white"/>

</selector>


text:
"use strict";

var DrawingError = require('./DrawingError');

var ToolBox = function () {
  var toolbox = this;

  toolbox.tools = {
    P: require('./Point'),
    L: require('./Line'),
    R: require('./Rectangle'),
    O: require('./Circle'),
    B: require('./Bucket')
  };

  toolbox.createTool = function (identifier, args) {
    if (typeof toolbox.tools[identifier] === 'undefined') {
      throw new DrawingError('I don\'t know about that drawing tool');
    }

    return new toolbox.tools[identifier](args);
  }
};

module.exports = ToolBox;


text:
Dependency-Check Jenkins Plugin
==============================

Dependency-Check is a utility that identifies project dependencies and checks if there are any known, publicly disclosed, vulnerabilities. This tool can be part of the solution to the OWASP Top 10 2013: A9 - Using Components with Known Vulnerabilities. This plug-in can independently execute a Dependency-Check analysis and visualize results.

Dependency-Check is able to identify Java and Python components along with .NET assemblies. Once identified, Dependency-Check will automatically determine if those component have known, publicly disclosed, vulnerabilities.

The Dependency-Check Jenkins Plugin features the ability to perform a dependency analysis build and later view results post build. The plugin is built using [analysis-core] and features many of the same features that Jenkins static analysis plugins offer, including thresholds, charts and the ability to view vulnerability information should a dependency have one identified.

More information can be found on the [wiki].

Mailing List
------------

Subscribe: [dependency-check+subscribe@googlegroups.com] [subscribe]

Post: [dependency-check@googlegroups.com] [post]

Copyright & License
-------------------

Dependency-Check is Copyright (c) 2012-2015 Jeremy Long. All Rights Reserved.

Dependency-Check Jenkins Plugin is Copyright (c) 2013-2015 Steve Springett. All Rights Reserved.

Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt] [license] file for the full license.

Dependency-Check makes use of several other open source libraries. Please see the [NOTICE.txt] [notices] file for more information.

  [wiki]: https://wiki.jenkins-ci.org/display/JENKINS/OWASP+Dependency-Check+Plugin
  [analysis-core]: http://wiki.jenkins-ci.org/x/CwDgAQ
  [subscribe]: mailto:dependency-check+subscribe@googlegroups.com
  [post]: mailto:dependency-check@googlegroups.com
  [license]: https://github.com/jenkinsci/dependency-check-plugin/blob/master/LICENSE.txt
  [notices]: https://github.com/jenkinsci/dependency-check-plugin/blob/master/NOTICES.txt