text:
#ifndef LINALG_BACKEND_BASE_H__
#define LINALG_BACKEND_BASE_H__

#include <memory>
#include <shogun/io/SGIO.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/common.h>
#include <shogun/lib/config.h>
#include <shogun/mathematics/Math.h>
#include <shogun/mathematics/linalg/GPUMemoryBase.h>
#include <shogun/mathematics/linalg/LinalgEnums.h>
#include <shogun/mathematics/linalg/internal/Block.h>
#include <shogun/mathematics/linalg/LinalgMacros.h>

namespace shogun
{

	/** @brief Base interface of generic linalg methods
	 * and generic memory transfer methods.
	 */
	class LinalgBackendBase
	{
	public:
		virtual ~LinalgBackendBase() = default;

/**
 * Wrapper method of add operation the operation result = alpha*a + beta*b.
 *
 * @see linalg::add
 */
#define BACKEND_GENERIC_IN_PLACE_ADD(Type, Container)                          \
	virtual void add(                                                          \
	    const Container<Type>& a, const Container<Type>& b, Type alpha,        \
	    Type beta, Container<Type>& result) const                              \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_ADD, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_ADD, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_ADD

/**
 * Wrapper method of add column vector result = alpha*A.col(i) + beta*b.
 *
 * @see linalg::add_col_vec
 */
#define BACKEND_GENERIC_ADD_COL_VEC(Type, Container)                           \
	virtual void add_col_vec(                                                  \
	    const SGMatrix<Type>& A, index_t i, const SGVector<Type>& b,           \
	    Container<Type>& result, Type alpha, Type beta) const                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return;                                                                \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_COL_VEC, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_COL_VEC, SGMatrix)
#undef BACKEND_GENERIC_ADD_COL_VEC

/**
 * Wrapper method of add diagonal vector A.diagonal = alpha * A.diagonal +
 * beta * b.
 *
 * @see linalg::add_diag
 */
#define BACKEND_GENERIC_ADD_DIAG(Type, Container)                              \
	virtual void add_diag(                                                     \
	    SGMatrix<Type>& A, const SGVector<Type>& b, Type alpha, Type beta)     \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return;                                                                \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_DIAG, SGMatrix);
#undef BACKEND_GENERIC_ADD_DIAG

/**
 * Wrapper method of add diagonal vector A.diagonal = A.diagonal + beta * b.
 *
 * @see linalg::add_ridge
 */
#define BACKEND_GENERIC_ADD_RIDGE(Type, Container)                             \
	virtual void add_ridge(SGMatrix<Type>& A, Type beta) const                 \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return;                                                                \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_RIDGE, SGMatrix);
#undef BACKEND_GENERIC_ADD_RIDGE

/**
 * Wrapper method of add vector to each column of matrix.
 *
 * @see linalg::add_vector
 */
#define BACKEND_GENERIC_ADD_VECTOR(Type, Container)                            \
	virtual void add_vector(                                                   \
	    const SGMatrix<Type>& A, const SGVector<Type>& b,                      \
	    SGMatrix<Type>& result, Type alpha, Type beta) const                   \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return;                                                                \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_VECTOR, SGMatrix)
#undef BACKEND_GENERIC_ADD_VECTOR

/**
 * Wrapper method of add scalar operation.
 *
 * @see linalg::add_scalar
 */
#define BACKEND_GENERIC_ADD_SCALAR(Type, Container)                            \
	virtual void add_scalar(Container<Type>& a, Type b) const                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_SCALAR, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ADD_SCALAR, SGMatrix)
#undef BACKEND_GENERIC_ADD_SCALAR

/**
 * Wrapper method of center matrix operation.
 *
 * @see linalg::center_matrix
 */
#define BACKEND_GENERIC_CENTER_MATRIX(Type, Container)                         \
	virtual void center_matrix(Container<Type>& A) const                       \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_CENTER_MATRIX, SGMatrix)
#undef BACKEND_GENERIC_CENTER_MATRIX

/**
 * Wrapper method of Cholesky decomposition.
 *
 * @see linalg::cholesky_factor
 */
#define BACKEND_GENERIC_CHOLESKY_FACTOR(Type, Container)                       \
	virtual Container<Type> cholesky_factor(                                   \
	    const Container<Type>& A, const bool lower) const                      \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_CHOLESKY_FACTOR, SGMatrix)
#undef BACKEND_GENERIC_CHOLESKY_FACTOR

/**
 * Wrapper triangular solver with Choleksy decomposition.
 *
 * @see linalg::cholesky_solver
 */
#define BACKEND_GENERIC_CHOLESKY_SOLVER(Type, Container)                       \
	virtual SGVector<Type> cholesky_solver(                                    \
	    const Container<Type>& L, const SGVector<Type>& b, const bool lower)   \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_CHOLESKY_SOLVER, SGMatrix)
#undef BACKEND_GENERIC_CHOLESKY_SOLVER

/**
 * Wrapper for rank one update of Cholesky decomposition
 *
 * @see linalg::cholesky_factor
 */
#define BACKEND_GENERIC_CHOLESKY_RANK_UPDATE(Type, Container)                  \
	virtual void cholesky_rank_update(                                         \
	    Container<Type>& L, const SGVector<Type>& b, Type alpha,               \
	    const bool lower) const                                                \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_REAL_PTYPE(BACKEND_GENERIC_CHOLESKY_RANK_UPDATE, SGMatrix)
#undef BACKEND_GENERIC_CHOLESKY_RANK_UPDATE

/**
 * Wrapper for rank one update of a square matrix
 */
#define BACKEND_GENERIC_RANK_UPDATE(Type, Container)                           \
	virtual void rank_update(                                                  \
	    Container<Type>& A, const SGVector<Type>& b, Type alpha) const         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_RANK_UPDATE, SGMatrix)
#undef BACKEND_GENERIC_RANK_UPDATE

/**
 * Wrapper method of LDLT Cholesky decomposition
 *
 * @see linalg::ldlt_factor
 */
#define BACKEND_GENERIC_LDLT_FACTOR(Type, Container)                           \
	virtual void ldlt_factor(                                                  \
	    const Container<Type>& A, Container<Type>& L, SGVector<Type>& d,       \
	    SGVector<index_t>& p, const bool lower) const                          \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_LDLT_FACTOR, SGMatrix)
#undef BACKEND_GENERIC_LDLT_FACTOR

/**
 * Wrapper method of pseudo inverse for self adjoint matrices
 *
 * @see linalg::pinvh
 */
#define BACKEND_GENERIC_PINVH(Type, Container)                                 \
	virtual void pinvh(const SGMatrix<Type>& A, SGMatrix<Type>& result) const  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_PINVH, SGMatrix)
#undef BACKEND_GENERIC_PINVH

/**
 * Wrapper method of pseudo inverse
 *
 * @see linalg::pinvh
 */
#define BACKEND_GENERIC_PINV(Type, Container)                                  \
	virtual void pinv(const SGMatrix<Type>& A, SGMatrix<Type>& result) const   \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_PINV, SGMatrix)
#undef BACKEND_GENERIC_PINV

/**
 * Wrapper method of LDLT Cholesky solver
 *
 * @see linalg::ldlt_solver
 */
#define BACKEND_GENERIC_LDLT_SOLVER(Type, Container)                           \
	virtual SGVector<Type> ldlt_solver(                                        \
	    const Container<Type>& L, const SGVector<Type>& d,                     \
	    const SGVector<index_t>& p, const SGVector<Type>& b, const bool lower) \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_LDLT_SOLVER, SGMatrix)
#undef BACKEND_GENERIC_LDLT_SOLVER

/**
 * Wrapper method of cross entropy.
 *
 * @see linalg::cross_entropy
 */
#define BACKEND_GENERIC_CROSS_ENTROPY(Type, Container)                         \
	virtual Type cross_entropy(                                                \
	    const Container<Type>& P, const Container<Type>& Q) const              \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_CROSS_ENTROPY, SGMatrix)
#undef BACKEND_GENERIC_CROSS_ENTROPY

/**
 * Wrapper method of vector dot-product that works with generic vectors.
 *
 * @see linalg::dot
 */
#define BACKEND_GENERIC_DOT(Type, Container)                                   \
	virtual Type dot(const Container<Type>& a, const Container<Type>& b) const \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_DOT, SGVector)
#undef BACKEND_GENERIC_DOT

/**
 * Wrapper method of vector dot-product that works with generic vectors.
 *
 * @see linalg::dot
 */
#define BACKEND_GENERIC_DOT(Type, Container)                                   \
	virtual linalg::promote<float64_t, Type>::type dot(                        \
	    const Container<float64_t>& a, const Container<Type>& b) const         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE_EXCEPT_FLOAT64(BACKEND_GENERIC_DOT, SGVector)
#undef BACKEND_GENERIC_DOT

/**
 * Wrapper method of eigenvalues and eigenvectors computation.
 *
 * @see linalg::eigen_solver
 */
#define BACKEND_GENERIC_EIGEN_SOLVER(Type, Container)                          \
	virtual void eigen_solver(                                                 \
	    const Container<Type>& A, SGVector<Type>& eigenvalues,                 \
	    SGMatrix<Type>& eigenvectors) const                                    \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_EIGEN_SOLVER, SGMatrix)
#undef BACKEND_GENERIC_EIGEN_SOLVER

/**
 * Wrapper method of eigenvalues and eigenvectors computation
 * for symmetric matrices.
 *
 * @see linalg::eigen_solver_symmetric
 */
#define BACKEND_GENERIC_EIGEN_SOLVER_SYMMETRIC(Type, Container)                \
	virtual void eigen_solver_symmetric(                                       \
	    const Container<Type>& A, SGVector<Type>& eigenvalues,                 \
	    SGMatrix<Type>& eigenvectors, index_t k) const                         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(
		    BACKEND_GENERIC_EIGEN_SOLVER_SYMMETRIC, SGMatrix)
#undef BACKEND_GENERIC_EIGEN_SOLVER_SYMMETRIC

/**
 * Wrapper method of in-place vector elementwise product.
 *
 * @see linalg::element_prod
 */
#define BACKEND_GENERIC_IN_PLACE_VECTOR_ELEMENT_PROD(Type, Container)          \
	virtual void element_prod(                                                 \
	    const Container<Type>& a, const Container<Type>& b,                    \
	    Container<Type>& result) const                                         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_IN_PLACE_VECTOR_ELEMENT_PROD, SGVector)
#undef BACKEND_GENERIC_IN_PLACE_VECTOR_ELEMENT_PROD

/**
 * Wrapper method of in-place matrix elementwise product.
 *
 * @see linalg::element_prod
 */
#define BACKEND_GENERIC_IN_PLACE_MATRIX_ELEMENT_PROD(Type, Container)          \
	virtual void element_prod(                                                 \
	    const Container<Type>& a, const Container<Type>& b,                    \
	    Container<Type>& result, bool transpose_A, bool transpose_B) const     \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_IN_PLACE_MATRIX_ELEMENT_PROD, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_MATRIX_ELEMENT_PROD

/**
 * Wrapper method of in-place matrix block elementwise product.
 *
 * @see linalg::element_prod
 */
#define BACKEND_GENERIC_IN_PLACE_BLOCK_ELEMENT_PROD(Type, Container)           \
	virtual void element_prod(                                                 \
	    const linalg::Block<Container<Type>>& a,                               \
	    const linalg::Block<Container<Type>>& b, Container<Type>& result,      \
	    bool transpose_A, bool transpose_B) const                              \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_IN_PLACE_BLOCK_ELEMENT_PROD, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_BLOCK_ELEMENT_PROD

/**
 * Wrapper method of in-place vector elementwise division.
 *
 * @see linalg::element_div
 */
#define BACKEND_GENERIC_IN_PLACE_VECTOR_ELEMENT_DIV(Type, Container)          \
	virtual void element_div(                                                 \
	    const Container<Type>& a, const Container<Type>& b,                    \
	    Container<Type>& result) const                                         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_IN_PLACE_VECTOR_ELEMENT_DIV, SGVector)
#undef BACKEND_GENERIC_IN_PLACE_VECTOR_ELEMENT_DIV

/**
 * Wrapper method of in-place matrix elementwise division.
 *
 * @see linalg::element_div
 */
#define BACKEND_GENERIC_IN_PLACE_MATRIX_ELEMENT_DIV(Type, Container)          \
	virtual void element_div(                                                 \
	    const Container<Type>& a, const Container<Type>& b,                    \
	    Container<Type>& result) const     \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_IN_PLACE_MATRIX_ELEMENT_DIV, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_MATRIX_ELEMENT_DIV

/**
 * Wrapper method of in-place exponent method.
 *
 * @see linalg::exponent
 */
#define BACKEND_GENERIC_EXPONENT(Type, Container)                              \
	virtual void exponent(const Container<Type>& a, Container<Type>& result)   \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_EXPONENT, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_EXPONENT, SGMatrix)
#undef BACKEND_GENERIC_EXPONENT

/**
 * Wrapper method of in-place log method.
 *
 * @see linalg::log
 */
#define BACKEND_GENERIC_LOG(Type, Container)                              \
	virtual void log(const Container<Type>& a, Container<Type>& result)   \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_LOG, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_LOG, SGMatrix)
#undef BACKEND_GENERIC_LOG

/**
 * Wrapper method of in-place sin method.
 *
 * @see linalg::sin
 */
#define BACKEND_GENERIC_SIN(Type, Container)                              \
	virtual void sin(const Container<Type>& a, Container<Type>& result)   \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SIN, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SIN, SGMatrix)
#undef BACKEND_GENERIC_SIN

/**
 * Wrapper method of in-place cos method.
 *
 * @see linalg::cos
 */
#define BACKEND_GENERIC_COS(Type, Container)                              \
	virtual void cos(const Container<Type>& a, Container<Type>& result)   \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_COS, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_COS, SGMatrix)
#undef BACKEND_GENERIC_COS

/**
 * Wrapper method of set matrix to identity.
 *
 * @see linalg::identity
 */
#define BACKEND_GENERIC_IDENTITY(Type, Container)                              \
	virtual void identity(Container<Type>& identity_matrix) const              \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return;                                                                \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IDENTITY, SGMatrix)
#undef BACKEND_GENERIC_IDENTITY

/**
 * Wrapper method of logistic function f(x) = 1/(1+exp(-x))
 *
 * @see linalg::logistic
 */
#define BACKEND_GENERIC_LOGISTIC(Type, Container)                              \
	virtual void logistic(const Container<Type>& a, Container<Type>& result)   \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_LOGISTIC, SGMatrix)
#undef BACKEND_GENERIC_LOGISTIC

/**
 * Wrapper method of matrix product method.
 *
 * @see linalg::matrix_prod
 */
#define BACKEND_GENERIC_IN_PLACE_MATRIX_PROD(Type, Container)                  \
	virtual void matrix_prod(                                                  \
	    const SGMatrix<Type>& a, const Container<Type>& b,                     \
	    Container<Type>& result, bool transpose_A, bool transpose_B) const     \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_MATRIX_PROD, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_MATRIX_PROD, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_MATRIX_PROD

/**
 * Wrapper method of max method. Return the largest element in a vector or
 * matrix.
 *
 * @see linalg::max
 */
#define BACKEND_GENERIC_MAX(Type, Container)                                   \
	virtual Type max(const Container<Type>& a) const                           \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_MAX, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_MAX, SGMatrix)
#undef BACKEND_GENERIC_MAX

/**
 * Wrapper method that computes mean of SGVectors and SGMatrices
 * that are composed of real numbers.
 *
 * @see linalg::mean
 */
#define BACKEND_GENERIC_REAL_MEAN(Type, Container)                             \
	virtual float64_t mean(const Container<Type>& a) const                     \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_COMPLEX_PTYPE(BACKEND_GENERIC_REAL_MEAN, SGVector)
		DEFINE_FOR_NON_COMPLEX_PTYPE(BACKEND_GENERIC_REAL_MEAN, SGMatrix)
#undef BACKEND_GENERIC_REAL_MEAN

/**
 * Wrapper method that computes mean of SGVectors and SGMatrices
 * that are composed of complex numbers.
 *
 * @see linalg::mean
 */
#define BACKEND_GENERIC_COMPLEX_MEAN(Container)                                \
	virtual complex128_t mean(const Container<complex128_t>& a) const          \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		BACKEND_GENERIC_COMPLEX_MEAN(SGVector)
		BACKEND_GENERIC_COMPLEX_MEAN(SGMatrix)
#undef BACKEND_GENERIC_COMPLEX_MEAN

/**
 * Wrapper method that computes mean of SGVectors and SGMatrices
 * that are composed of real numbers.
 *
 * @see linalg::std_deviation
 */
#define BACKEND_GENERIC_REAL_STD(Type, Container)                              \
	virtual SGVector<Type> std_deviation(                                      \
	    const Container<Type>& a, bool colwise) const                          \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_COMPLEX_PTYPE(BACKEND_GENERIC_REAL_STD, SGMatrix)
#undef BACKEND_GENERIC_REAL_STD

/**
 * Wrapper method of multiply_by_logistic_derivative function f(x) =
 * 1/(1+exp(-x))
 *
 * @see linalg::multiply_by_logistic_derivative
 */
#define BACKEND_GENERIC_MULTIPLY_BY_LOGISTIC_DERIV(Type, Container)            \
	virtual void multiply_by_logistic_derivative(                              \
	    const Container<Type>& a, Container<Type>& result) const               \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_MULTIPLY_BY_LOGISTIC_DERIV, SGMatrix)
#undef BACKEND_GENERIC_MULTIPLY_BY_LOGISTIC_DERIV

/**
 * Wrapper method of multiply_by_rectified_linear_derivative
 *
 * @see linalg::multiply_by_rectified_linear_derivative
 */
#define BACKEND_GENERIC_MULTIPLY_BY_RECTIFIED_LINEAR_DERIV(Type, Container)    \
	virtual void multiply_by_rectified_linear_derivative(                      \
	    const Container<Type>& a, Container<Type>& result) const               \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(
		    BACKEND_GENERIC_MULTIPLY_BY_RECTIFIED_LINEAR_DERIV, SGMatrix)
#undef BACKEND_GENERIC_MULTIPLY_BY_RECTIFIED_LINEAR_DERIV

/**
 * Wrapper method that range fills a vector of matrix.
 *
 * @see linalg::range_fill
 */
#define BACKEND_GENERIC_RANGE_FILL(Type, Container)                            \
	virtual void range_fill(Container<Type>& a, const Type start) const        \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_RANGE_FILL, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_RANGE_FILL, SGMatrix)
#undef BACKEND_GENERIC_RANGE_FILL

/**
 * Wrapper method of rectified_linear method f(x) = max(0, x)
 *
 * @see linalg::rectified_linear
 */
#define BACKEND_GENERIC_RECTIFIED_LINEAR(Type, Container)                      \
	virtual void rectified_linear(                                             \
	    const Container<Type>& a, Container<Type>& result) const               \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_RECTIFIED_LINEAR, SGMatrix)
#undef BACKEND_GENERIC_RECTIFIED_LINEAR

/**
 * Wrapper method that solves a system of linear equations
 * using QR decomposition.
 *
 * @see linalg::qr_solver
 */
#define BACKEND_GENERIC_QR_SOLVER(Type, Container)                             \
	virtual Container<Type> qr_solver(                                         \
	    const SGMatrix<Type>& A, const Container<Type>& b) const               \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_QR_SOLVER, SGVector)
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_QR_SOLVER, SGMatrix)
#undef BACKEND_GENERIC_QR_SOLVER

/**
 * Wrapper method of scale operation the operation result = alpha*A.
 *
 * @see linalg::scale
 */
#define BACKEND_GENERIC_IN_PLACE_SCALE(Type, Container)                        \
	virtual void scale(                                                        \
	    const Container<Type>& a, Type alpha, Container<Type>& result) const   \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_SCALE, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_SCALE, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_SCALE

/**
 * Wrapper method that scales every matrix column with respective coefficient.
 *
 * @see linalg::scale
 */
#define BACKEND_GENERIC_IN_PLACE_COLWISE_SCALE(Type, Container)                \
	virtual void scale(                                                        \
	    const Container<Type>& a, const SGVector<Type>& alphas,                \
	    Container<Type>& result) const                                         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_COLWISE_SCALE, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_COLWISE_SCALE

/**
 * Wrapper method that sets const values to vectors or matrices.
 *
 * @see linalg::set_const
 */
#define BACKEND_GENERIC_SET_CONST(Type, Container)                             \
	virtual void set_const(Container<Type>& a, const Type value) const         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SET_CONST, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SET_CONST, SGMatrix)
#undef BACKEND_GENERIC_SET_CONST

/**
 * Wrapper method of sum that works with generic vectors or matrices.
 *
 * @see linalg::sum
 */
#define BACKEND_GENERIC_SUM(Type, Container)                                   \
	virtual Type sum(const Container<Type>& a, bool no_diag) const             \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SUM, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SUM, SGMatrix)
#undef BACKEND_GENERIC_SUM

/**
 * Wrapper method of softmax method.
 *
 * @see linalg::softmax
 */
#define BACKEND_GENERIC_SOFTMAX(Type, Container)                               \
	virtual void softmax(Container<Type>& a) const                             \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SOFTMAX, SGMatrix)
#undef BACKEND_GENERIC_SOFTMAX

/** Implementation of @see LinalgBackendBase::sqrt */
#define BACKEND_GENERIC_IN_PLACE_SQRT(Type, Container)                         \
	virtual void sqrt(                                                         \
	    const Container<Type>& a, Container<Type>& result) const               \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                     \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_SQRT, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_IN_PLACE_SQRT, SGMatrix)
#undef BACKEND_GENERIC_IN_PLACE_SQRT

/**
 * Wrapper method of squared error method.
 *
 * @see linalg::squared_error
 */
#define BACKEND_GENERIC_SQUARED_ERROR(Type, Container)                         \
	virtual Type squared_error(                                                \
	    const Container<Type>& P, const Container<Type>& Q) const              \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SQUARED_ERROR, SGMatrix)
#undef BACKEND_GENERIC_SQUARED_ERROR

/**
 * Wrapper method of sum that works with matrix blocks.
 *
 * @see linalg::sum
 */
#define BACKEND_GENERIC_BLOCK_SUM(Type, Container)                             \
	virtual Type sum(const linalg::Block<Container<Type>>& a, bool no_diag)    \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_BLOCK_SUM, SGMatrix)
#undef BACKEND_GENERIC_BLOCK_SUM

/**
 * Wrapper method of sum that works with symmetric matrices.
 *
 * @see linalg::sum_symmetric
 */
#define BACKEND_GENERIC_SYMMETRIC_SUM(Type, Container)                         \
	virtual Type sum_symmetric(const Container<Type>& a, bool no_diag) const   \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SYMMETRIC_SUM, SGMatrix)
#undef BACKEND_GENERIC_SYMMETRIC_SUM

/**
 * Wrapper method of sum that works with symmetric matrix blocks.
 *
 * @see linalg::sum
 */
#define BACKEND_GENERIC_SYMMETRIC_BLOCK_SUM(Type, Container)                   \
	virtual Type sum_symmetric(                                                \
	    const linalg::Block<Container<Type>>& a, bool no_diag) const           \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_SYMMETRIC_BLOCK_SUM, SGMatrix)
#undef BACKEND_GENERIC_SYMMETRIC_BLOCK_SUM

/**
 * Wrapper method of matrix rowwise sum that works with dense matrices.
 *
 * @see linalg::colwise_sum
 */
#define BACKEND_GENERIC_COLWISE_SUM(Type, Container)                           \
	virtual SGVector<Type> colwise_sum(const Container<Type>& a, bool no_diag) \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_COLWISE_SUM, SGMatrix)
#undef BACKEND_GENERIC_COLWISE_SUM

/**
 * Wrapper method of matrix colwise sum that works with dense matrices.
 *
 * @see linalg::colwise_sum
 */
#define BACKEND_GENERIC_BLOCK_COLWISE_SUM(Type, Container)                     \
	virtual SGVector<Type> colwise_sum(                                        \
	    const linalg::Block<Container<Type>>& a, bool no_diag) const           \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_BLOCK_COLWISE_SUM, SGMatrix)
#undef BACKEND_GENERIC_BLOCK_COLWISE_SUM

/**
 * Wrapper method of matrix rowwise sum that works with dense matrices.
 *
 * @see linalg::rowwise_sum
 */
#define BACKEND_GENERIC_ROWWISE_SUM(Type, Container)                           \
	virtual SGVector<Type> rowwise_sum(const Container<Type>& a, bool no_diag) \
	    const                                                                  \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ROWWISE_SUM, SGMatrix)
#undef BACKEND_GENERIC_ROWWISE_SUM

/**
 * Wrapper method of matrix rowwise sum that works with dense matrices.
 *
 * @see linalg::rowwise_sum
 */
#define BACKEND_GENERIC_BLOCK_ROWWISE_SUM(Type, Container)                     \
	virtual SGVector<Type> rowwise_sum(                                        \
	    const linalg::Block<Container<Type>>& a, bool no_diag) const           \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_BLOCK_ROWWISE_SUM, SGMatrix)
#undef BACKEND_GENERIC_BLOCK_ROWWISE_SUM

/**
 * Wrapper method of svd computation.
 *
 * @see linalg::svd
 */
#define BACKEND_GENERIC_SVD(Type, Container)                                   \
	virtual void svd(                                                          \
	    const Container<Type>& A, SGVector<Type> s, SGMatrix<Type> U,          \
	    bool thin_U, linalg::SVDAlgorithm alg) const                           \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(BACKEND_GENERIC_SVD, SGMatrix)
#undef BACKEND_GENERIC_SVD

/**
 * Wrapper method of trace computation.
 *
 * @see linalg::trace
 */
#define BACKEND_GENERIC_TRACE(Type, Container)                                 \
	virtual Type trace(const Container<Type>& A) const                         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_TRACE, SGMatrix)
#undef BACKEND_GENERIC_TRACE

/**
 * Wrapper method of trace computation.
 *
 * @see linalg::transpose_matrix
 */
#define BACKEND_GENERIC_TRANSPOSE_MATRIX(Type, Container)                      \
	virtual Container<Type> transpose_matrix(const Container<Type>& A) const   \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_TRANSPOSE_MATRIX, SGMatrix)
#undef BACKEND_GENERIC_TRANSPOSE_MATRIX

/**
 * Wrapper method of triangular solver.
 *
 * @see linalg::triangular_solver
 */
#define BACKEND_GENERIC_TRIANGULAR_SOLVER(Type, Container)                     \
	virtual Container<Type> triangular_solver(                                 \
	    const SGMatrix<Type>& L, const Container<Type>& b,                     \
	    const bool lower = true) const                                         \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_NON_INTEGER_PTYPE(
		    BACKEND_GENERIC_TRIANGULAR_SOLVER, SGVector)
		DEFINE_FOR_NON_INTEGER_PTYPE(
		    BACKEND_GENERIC_TRIANGULAR_SOLVER, SGMatrix)
#undef BACKEND_GENERIC_TRIANGULAR_SOLVER

/**
 * Wrapper method of set vector or matrix to zero.
 *
 * @see linalg::zero
 */
#define BACKEND_GENERIC_ZERO(Type, Container)                                  \
	virtual void zero(Container<Type>& a) const                                \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return;                                                                \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ZERO, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_ZERO, SGMatrix)
#undef BACKEND_GENERIC_ZERO

/**
 * Wrapper method of Transferring data to GPU memory.
 * Does nothing if no GPU backend registered.
 *
 * @see linalg::to_gpu
 */
#define BACKEND_GENERIC_TO_GPU(Type, Container)                                \
	virtual GPUMemoryBase<Type>* to_gpu(const Container<Type>&) const          \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
		return 0;                                                              \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_TO_GPU, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_TO_GPU, SGMatrix)
#undef BACKEND_GENERIC_TO_GPU

/**
 * Wrapper method of fetching data from GPU memory.
 *
 * @see linalg::from_gpu
 */
#define BACKEND_GENERIC_FROM_GPU(Type, Container)                              \
	virtual void from_gpu(const Container<Type>&, Type* data) const            \
	{                                                                          \
		not_implemented(SOURCE_LOCATION);;                                                    \
	}
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_FROM_GPU, SGVector)
		DEFINE_FOR_ALL_PTYPE(BACKEND_GENERIC_FROM_GPU, SGMatrix)
#undef BACKEND_GENERIC_FROM_GPU

#undef DEFINE_FOR_ALL_PTYPE
#undef DEFINE_FOR_NON_COMPLEX_PTYPE
#undef DEFINE_FOR_NON_INTEGER_PTYPE
	};
} // namespace shogun

#endif // LINALG_BACKEND_BASE_H__


text:
ACCEPTED

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

#### Published in
Schr. naturf. Ges. Leipzig 1: 114 (1822)

#### Original name
Tremella aurantia Schwein., 1822

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
function [X, iGoodChan, fs, indSegment] = get_data(Files, iGoodChan, TimeWindow, PassBand, WindowFcn, WinLength, WinOverlap)

% How many and which file type?
nFile = numel(Files);
[~, MatName] = in_bst(Files{1});
if strcmp(MatName,'F')
    ftype = 'data';
elseif strcmp(MatName,'Value')
    ftype = 'matrix';
end

% Get good channels (update on the fly, keep only the ones which are always good..)
for iFile = 1:nFile
    if strcmp(ftype,'data')
        sMat = in_bst_data(Files{iFile}, {'ChannelFlag', 'Time', 'Events'});
        iGoodChan = intersect(find(sMat.ChannelFlag == 1), iGoodChan)';
    else
        sMat = in_bst_matrix(Files{iFile});
    end
    % Get bad segments if any
    good{iFile} = ones(1, size(sMat.Time,2));
    if isfield(sMat,'Events')&&~isempty(sMat.Events)&&~isempty(sMat.Events(strcmp({sMat.Events.label}, 'BAD')))
        bad{iFile} = sMat.Events(strcmp({sMat.Events.label}, 'BAD')).samples;
        for iEp = 1:size(bad{iFile},2)
            if bad{iFile}(1,iEp)==0; bad{iFile}(1,iEp) = 1; end
            good{iFile}(bad{iFile}(1,iEp):bad{iFile}(2,iEp)) = 0;
        end
    else
        bad{iFile} = [];
    end
    if iFile==1
        iSample{1} = find((sMat.Time<TimeWindow(2))&(sMat.Time>TimeWindow(1)));
        t = sMat.Time;
        fs = round(1/(t(2)-t(1)));
    else
        if isempty(WinLength)&&(length(iSample{1}) ~= length(find((sMat.Time<TimeWindow(2))&(sMat.Time>TimeWindow(1)))))
            error('Make sure all trials have same time definition');
        end
        if fs ~= round(1/(sMat.Time(2)-sMat.Time(1)))
            error('Make sure all trials have same sampling rate');
        end
        iSample{iFile} = find((sMat.Time<TimeWindow(2))&(sMat.Time>TimeWindow(1)));
    end
end

% Window length and overlap
if ~isempty(WinLength)
    Lwin  = round(WinLength * fs);
    Loverlap = round(Lwin * WinOverlap / 100);
else
    Lwin = numel(iSample{1});
end

% Compute window function
if ~isempty(WindowFcn)
    win = bst_window(WindowFcn, Lwin)';
else
    win = ones(1,Lwin);
end

% Load data
X = zeros(numel(iGoodChan), Lwin, nFile); %%% todo: compute number of segments here
nBad = 0;
iSegment = 1;
for iFile = 1:numel(Files)
    [sMat, MatName] = in_bst(Files{iFile});
    Xtmp = sMat.(MatName)(iGoodChan, iSample{iFile});
    if ~isempty(WinLength)
        nTime = size(Xtmp,2);
        nWin = floor((nTime - Loverlap) ./ (Lwin - Loverlap));
        for iWin = 1:nWin
            iTimes = (1:Lwin) + (iWin-1)*(Lwin - Loverlap);
            % Check if this segment is outside of ALL the bad segments (either entirely before or entirely after)
            if ~isempty(bad{iFile}) && (~all((iTimes(end) < bad{iFile}(1,:)) | (iTimes(1) > bad{iFile}(2,:))))
                disp(sprintf('BST> Skipping window #%d because it contains a bad segment.', iWin));
                nBad = nBad + 1;
                continue;
            end
            % subtract mean before windowing
            Xtmp2 = bsxfun(@minus, Xtmp(:,iTimes), mean(Xtmp(:,iTimes),2));
            X(:,:,iSegment) = bst_bsxfun(@times, Xtmp2, win);
            iSegment = iSegment + 1;
        end
        % make index for files and windows
        tmpindex = iSegment-nWin+nBad:iSegment-1;
        indSegment(tmpindex,:) = [1:nWin-nBad; repmat(iFile,1,nWin-nBad)]';
    else
        X(:,:,iFile) = bst_bsxfun(@times, Xtmp, win);
        indSegment(iFile,:) = [1 iFile];
    end
end

if ~isempty(PassBand)
    for iSegment = 1:size(X,3)
        X(:,:,iSegment) = process_bandpass('Compute', X(:,:,iSegment), fs, PassBand(1), PassBand(2), 'bst-fft-fir', 1);
    end
end

% Zero-out bad segments..
if isempty(WinLength)
    for iFile = 1:numel(Files)
        X(:,good{iFile}(iSample{iFile})<1,iFile) = 0;
    end
end

end


text:
<!-- This file was autogenerated via cilium cmdref, do not edit manually-->

## cilium policy delete

Delete policy rules

### Synopsis

Delete policy rules

```
cilium policy delete [<labels>] [flags]
```

### Options

```
      --all             Delete all policies
  -h, --help            help for delete
  -o, --output string   json| jsonpath='{}'
```

### Options inherited from parent commands

```
      --config string   config file (default is $HOME/.cilium.yaml)
  -D, --debug           Enable debug messages
  -H, --host string     URI to server-side API
```

### SEE ALSO

* [cilium policy](../cilium_policy)	 - Manage security policies


text:
require 'spec_helper'

describe HostsController do
  before(:each) do
    @host = Factory.create(:host)
    @host.person.update_attribute(:ldap_id, 'host')
    @event = @host.event
    Event.stub(:find).and_return(@event)
    @admin = Factory.create(:person, :ldap_id => 'admin', :role => 'administrator')
    RubyCAS::Filter.fake('admin')
  end

  describe 'GET index' do
    it 'assigns to @event the given Event' do
      get :index, :event_id => @event.id
      assigns[:event].should == @event
    end

    it "assigns to @roles a list of the Event's Hosts sorted by Name" do
      hosts = Array.new(3) {Host.new}
      @event.stub(:hosts).and_return(hosts)
      get :index, :event_id => @event.id
      assigns[:roles].should == hosts
    end

    it 'renders the index template' do
      get :index, :event_id => @event.id
      response.should render_template('index')
    end
  end

  describe 'GET show' do
    it 'assigns to @event the given Event' do
      get :show, :event_id => @event.id, :id => @host.id
      assigns[:event].should == @event
    end

    it 'assigns to @roles the given Host' do
      @event.stub_chain(:hosts, :find).and_return(@host)
      get :show, :event_id => @event.id, :id => @host.id
      assigns[:role].should == @host
    end

    it 'renders the show template' do
      get :show, :event_id => @event.id, :id => @host.id
      response.should render_template('show')
    end
  end

  describe 'GET new' do
    it 'assigns to @people a list of People sorted by Name' do
      people = Array.new(3) {Person.new}
      Person.stub(:all).and_return(people)
      get :new, :event_id => @event.id
      assigns[:people].should == people
    end

    it 'assigns to @event the given Event' do
      get :new, :event_id => @event.id
      assigns[:event].should == @event
    end

    it 'assigns to @role a new Host' do
      get :new, :event_id => @event.id
      role = assigns[:role]
      role.should be_a_new_record
      role.should be_a_kind_of(Host)
      @event.hosts.should include(role)
    end

    it 'renders the new template' do
      get :new, :event_id => @event.id
      response.should render_template('new')
    end
  end

  describe 'GET join' do
    it 'assigns to @event the given Event' do
      get :join, :event_id => @event.id
      assigns[:event].should == @event
    end

    it 'renders the join template' do
      get :join, :event_id => @event.id
      response.should render_template('join')
    end
  end

  describe 'GET edit' do
    it 'assigns to @event the given Event' do
      get :edit, :event_id => @event.id, :id => @host.id
      assigns[:event].should == @event
    end

    it 'assigns to @role the given Host' do
      @event.stub_chain(:hosts, :find).and_return(@host)
      get :edit, :event_id => @event.id, :id => @host.id
      assigns[:role].should == @host
    end

    it 'renders the edit template' do
      get :edit, :event_id => @event.id, :id => @host.id
      response.should render_template('edit')
    end
  end

  describe 'GET delete' do
    it 'assigns to @event the given Event' do
      get :delete, :event_id => @event.id, :id => @host.id
      assigns[:event].should == @event
    end

    it 'assigns to @role the given Host' do
      @event.stub_chain(:hosts, :find).and_return(@host)
      get :delete, :event_id => @event.id, :id => @host.id
      assigns[:role].should == @host
    end

    it 'renders the edit template' do
      get :delete, :event_id => @event.id, :id => @host.id
      response.should render_template('delete')
    end
  end

  describe 'POST create' do
    before(:each) do
      @event.stub_chain(:hosts, :build).and_return(@host)
    end

    it 'assigns to @role a new Host with the given parameters' do
      @event.hosts.should_receive(:build).with('foo' => 'bar').and_return(@host)
      post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
      assigns[:role].should equal(@host)
    end

    it 'the new Host belongs to the given Event' do
      post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
      assigns[:role].event.should == @event
    end

    it 'saves the Host' do
      @host.should_receive(:save)
      post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
    end

    context 'when the Host is successfully saved' do
      before(:each) do
        @host.stub(:save).and_return(true)
      end

      it 'sets a flash[:notice] message' do
        post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
        flash[:notice].should == I18n.t('hosts.create.success')
      end

      it 'redirects to the View Hosts page' do
        post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
        response.should redirect_to(:action => 'index', :event_id => @event.id)
      end
    end

    context 'when the Host fails to be saved' do
      before(:each) do
        @host.stub(:save).and_return(false)
        @host.stub(:errors).and_return(:error => 'foo')
      end

      it 'assigns to @event the given Event' do
        post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
        assigns[:event].should == @event
      end

      it 'renders the new template' do
        post :create, :host => {'foo' => 'bar'}, :event_id => @event.id
        response.should render_template('new')
      end
    end
  end

  describe 'POST create_from_current_user' do
    context 'when signed in as a User who has not joined the Event' do
      before(:each) do
        @user = Factory.create(:person, :ldap_id => 'user', :role => 'user')
        Person.stub(:find).and_return(@user)
        RubyCAS::Filter.fake('user')
      end

      it 'adds the User as a verified Host of the Event' do
        @event.stub_chain(:hosts, :create)
        @event.hosts.should_receive(:create).with(:person => @user, :verified => true)
        post :create_from_current_user, :event_id => @event.id
      end

      it 'redirects to the view event page' do
        post :create_from_current_user, :event_id => @event.id
        response.should redirect_to event_url(@event)
      end
    end

    context 'when signed in as a User who has already joined the Event' do
      before(:each) do
        Person.stub(:find).and_return(@host.person)
        RubyCAS::Filter.fake('host')
      end

      it 'alerts the user that he has already joined the event'
    end
  end

  describe 'PUT update' do
    before(:each) do
      @event.stub_chain(:hosts, :find).and_return(@host)
    end

    it 'assigns to @role the given Role' do
      put :update, :host => {}, :event_id => @event.id, :id => @host.id
      assigns[:role].should equal(@host)
    end

    context 'when the Host is successfully updated' do
      before(:each) do
        @host.stub(:update_attributes).and_return(true)
      end

      context 'when signed in as the Host' do
        before(:each) do
          Person.stub(:find_by_ldap_id).and_return(@host.person)
          RubyCAS::Filter.fake('host')
        end

        it 'redirects to the show event page' do
          put :update, :host => {'foo' => 'bar'}, :event_id => @event.id, :id => @host.id
          response.should redirect_to(:controller => 'events', :action => 'show', :id => @event.id)
        end

        it 'sets a flash[:notice] message' do
          put :update, :host => {'foo' => 'bar'}, :event_id => @event.id, :id => @host.id
          flash[:notice].should == I18n.t('hosts.update.alt_success')
        end
      end

      context 'when signed in as someone other than the Host' do
        it 'sets a flash[:notice] message' do
          put :update, :host => {'foo' => 'bar'}, :event_id => @event.id, :id => @host.id
          flash[:notice].should == I18n.t('hosts.update.success')
        end

        it 'redirects to the View Hosts page' do
          put :update, :host => {'foo' => 'bar'}, :event_id => @event.id, :id => @host.id
          response.should redirect_to(:action => 'index', :event_id => @event.id)
        end
      end
    end

    context 'when the Host fails to be updated' do
      before(:each) do
        @host.stub(:update_attributes).and_return(false)
        @host.stub(:errors).and_return({:error => ''})
      end

      it 'assigns to @event the given Event' do
        put :update, :host => {'foo' => 'bar'}, :event_id => @event.id, :id => @host.id
        assigns[:event].should == @event
      end

      it 'renders the edit template' do
        put :update, :host => {'foo' => 'bar'}, :event_id => @event.id, :id => @host.id
        response.should render_template('edit')
      end
    end
  end

  describe 'DELETE destroy' do
    before(:each) do
      @event.stub_chain(:hosts, :find).and_return(@host)
    end

    it 'destroys the Host' do
      @host.should_receive(:destroy)
      delete :destroy, :event_id => @event.id, :id => @host.id
    end

    it 'sets a flash[:notice] message' do
      delete :destroy, :event_id => @event.id, :id => @host.id
      flash[:notice].should == I18n.t('hosts.destroy.success')
    end

    it 'redirects to the View Hosts page' do
      delete :destroy, :event_id => @event.id, :id => @host.id
      response.should redirect_to(:action => 'index', :event_id => @event.id)
    end
  end

  describe 'DELETE destroy_from_current_user' do
    context 'when signed in as a User who has joined the Event' do
      before(:each) do
        Person.stub(:find).and_return(@host.person)
        RubyCAS::Filter.fake('host')
        @event.stub_chain(:roles, :find_by_person_id).and_return(@host)
      end

      it 'unregisters the User from the Event' do
        @host.should_receive(:destroy)
        delete :destroy_from_current_user, :event_id => @event.id
      end
    end

    it 'redirects to the view event page' do
      delete :destroy_from_current_user, :event_id => @event.id
      response.should redirect_to event_url(@event)
    end
  end
end


text:
topic: "Heroku: Deploy button"
desc: "Setting up a button on a github repo to automatically deploy an app to Heroku"
layout: default
indent: true
---

TODO


text:
12.1 XML is all about data.
12.2 XML describes hierarchical structured data.
12.3 Covers the structure of an Atom XML feed.
12.4 Using the `ElementTree` module to parse XML.
12.5 Searching an XML tree.
12.6 ElementTree with the `libxml` parser.
12.7 Creating XML data.
12.8 Custom parsers to handle broken XML.

## 12.2 A 5-minute crash couse in XML
`xmlns` attribute to define a namespace.
Namespaces affect all child nodes.
Or use a prefix to explicitly declare namespace.
Put encoding information on first line: `<?xml version='1.0' encoding='utf-8'?>`
`xml:lang` to define language of all child elements.

## 12.4 Parsing XML

    >>> import xml.etree.ElementTree as etree
    >>> tree = etree.parse('feed.xml')
    >>> tree
    <xml.etree.ElementTree.ElementTree object at 0x0000000002C8DE80>
    >>> root = tree.getroot()
    >>> root
    <Element '{http://www.w3.org/2005/Atom}feed' at 0x0000000002EB7408>
    >>> root.tag
    '{http://www.w3.org/2005/Atom}feed'
    >>> len(root)
    8
    >>> root[0]
    <Element '{http://www.w3.org/2005/Atom}title' at 0x0000000002EB7318>
    >>> root[0].tag
    '{http://www.w3.org/2005/Atom}title'
    >>> for child in root:
    ...   print(child)
    ...
    <Element '{http://www.w3.org/2005/Atom}title' at 0x0000000002EB7318>
    <Element '{http://www.w3.org/2005/Atom}subtitle' at 0x0000000002EB73B8>
    <Element '{http://www.w3.org/2005/Atom}id' at 0x0000000002EB74F8>
    <Element '{http://www.w3.org/2005/Atom}updated' at 0x0000000002EB7548>
    <Element '{http://www.w3.org/2005/Atom}link' at 0x0000000002EB75E8>
    <Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7638>
    <Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7AE8>
    <Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7EA8>
    >>> root.attrib
    {'{http://www.w3.org/XML/1998/namespace}lang': 'en'}
    >>> root[4]
    <Element '{http://www.w3.org/2005/Atom}link' at 0x0000000002EB75E8>
    >>> root[4].attrib
    {'type': 'text/html', 'href': 'http://diveintomark.org/', 'rel': 'alternate'}
    >>> root[3]
    <Element '{http://www.w3.org/2005/Atom}updated' at 0x0000000002EB7548>
    >>> root[3].attrib
    {}

Elements act like lists which contain their direct children.
They also have attribute dictionaries.

## 12.5 Searching

    >>> root.findall('{http://www.w3.org/2005/Atom}entry')
    [<Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7638>, <Element '{http://www.w3.org/2005/Atom}entry' at
    0x0000000002EB7AE8>, <Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7EA8>]
    >>> root.tag
    '{http://www.w3.org/2005/Atom}feed'
    >>> root.findall(root.tag)
    []
    >>> root.findall('{http://www.w3.org/2005/Atom}author')
    []

`#findall` only looks at immediate children of the `root` element.
`#find` to find the first match.

    >>> tree.findall('{http://www.w3.org/2005/Atom}entry')
    [<Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7638>, <Element '{http://www.w3.org/2005/Atom}entry' at
    0x0000000002EB7AE8>, <Element '{http://www.w3.org/2005/Atom}entry' at 0x0000000002EB7EA8>]
    >>> tree.findall('{http://www.w3.org/2005/Atom}author')
    []
    >>> entries - tree.findall('{http://www.w3.org/2005/Atom}entry')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'entries' is not defined
    >>> entries = tree.findall('{http://www.w3.org/2005/Atom}entry')
    >>> len(entries)
    3
    >>> title_element = entries[0].find('{http://www.w3.org/2005/Atom}title')
    >>> title_element
    <Element '{http://www.w3.org/2005/Atom}title' at 0x0000000002EB77C8>
    >>> title_element.text
    'Dive into history, 2009 edition'
    >>> foo_element = entries[0].find('{http://www.w3.org/2005/Atom}foo')
    >>> foo_element
    >>> type(foo_element)
    <class 'NoneType'>

To use `find` in boolean context, do `if element.find(...) is not None`.
If you just do `if element.find(..)` you're actually testing whether or not that element has any children.
This is because it acts like a list and `[]` evaluates to `False`.
Add `//` to search descendant elements as well.

## 12.6 Going further with LXML
LXML has full XPath support, a faster parser, and support for more complicated expressions.

## 12.7 Generating XML

    >>> new_feed = etree.Element('{http://www.w3.org/2005/Atom}feed', attrib={'{http://www.w3.org/XML/1998/namespace}lang':
    'en'})
    >>> new_feed
    <Element '{http://www.w3.org/2005/Atom}feed' at 0x0000000002EB8458>
    >>> print(etree.tostring(new_feed))
    b'<ns0:feed xmlns:ns0="http://www.w3.org/2005/Atom" xml:lang="en" />'

Pass an element name (namespace and local name) to the `Element` class to create a new element.
Use LXML to set a default namespace. Just use LXML!

## 12.8 Parsing broken XML
XML has draconian error handling, as opposed to HTML.
Create a custom parser and pass the `recover` argument to overcome wellformedness errors.


text:
namespace content {
class BrowserContext;
}

class Profile;

class ExtensionInstallUIDefault : public extensions::ExtensionInstallUI {
 public:
  explicit ExtensionInstallUIDefault(content::BrowserContext* context);
  ~ExtensionInstallUIDefault() override;

  // ExtensionInstallUI:
  void OnInstallSuccess(const extensions::Extension* extension,
                        const SkBitmap* icon) override;
  void OnInstallFailure(const extensions::CrxInstallerError& error) override;
  void SetUseAppInstalledBubble(bool use_bubble) override;
  void OpenAppInstalledUI(const std::string& app_id) override;
  void SetSkipPostInstallUI(bool skip_ui) override;
  gfx::NativeWindow GetDefaultInstallDialogParent() override;

 private:
  Profile* profile_;

  // Whether or not to show the default UI after completing the installation.
  bool skip_post_install_ui_;

  // Used to undo theme installation.
  std::string previous_theme_id_;
  bool previous_using_system_theme_;

  // Whether to show an installed bubble on app install, or use the default
  // action of opening a new tab page.
  bool use_app_installed_bubble_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionInstallUIDefault);
};

#endif  // CHROME_BROWSER_UI_EXTENSIONS_EXTENSION_INSTALL_UI_DEFAULT_H_


text:
using System;

    class IsoscelesTriangle
    {
        static void Main()
        {
            //Write a program that prints an isosceles triangle of 9 copyright symbols ©
            //Note: The © symbol may be displayed incorrectly at the console so you may need to change the console character encoding to UTF-8 and assign a Unicode-friendly font in the console.
            //Note: Under old versions of Windows the © symbol may still be displayed incorrectly, regardless of how much effort you put to fix it.

            Console.WriteLine("           \u00A9");
            Console.WriteLine("        \u00A9     \u00A9");
            Console.WriteLine("      \u00A9         \u00A9");
            Console.WriteLine("    \u00A9    \u00A9   \u00A9   \u00A9");
        }
    }


text:
package org.apache.commons.vfs2.provider.http4;

import java.io.File;
import java.io.IOException;
import java.net.ProxySelector;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DurationUtils;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.UserAuthenticator;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;

/**
 * {@code FileProvider} implementation using HttpComponents HttpClient library.
 *
 * @since 2.3
 */
public class Http4FileProvider extends AbstractOriginatingFileProvider {

    /** Authenticator information. */
    static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES =
            {
            UserAuthenticationData.USERNAME,
            UserAuthenticationData.PASSWORD
            };

    /** FileProvider capabilities */
    static final Collection<Capability> CAPABILITIES =
            Collections.unmodifiableCollection(
                    Arrays.asList(
                            Capability.GET_TYPE,
                            Capability.READ_CONTENT,
                            Capability.URI,
                            Capability.GET_LAST_MODIFIED,
                            Capability.ATTRIBUTES,
                            Capability.RANDOM_ACCESS_READ,
                            Capability.DIRECTORY_READ_CONTENT
                            )
                    );

    /**
     * Constructs a new provider.
     */
    public Http4FileProvider() {
        setFileNameParser(Http4FileNameParser.getInstance());
    }

    private HttpClientConnectionManager createConnectionManager(final Http4FileSystemConfigBuilder builder,
        final FileSystemOptions fileSystemOptions, final SSLContext sslContext, final HostnameVerifier verifier) {
        final SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext, verifier);
        // @formatter:off
        final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslFactory)
            .register("http", new PlainConnectionSocketFactory())
            .build();
        // @formatter:on

        final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connManager.setMaxTotal(builder.getMaxTotalConnections(fileSystemOptions));
        connManager.setDefaultMaxPerRoute(builder.getMaxConnectionsPerHost(fileSystemOptions));

        // @formatter:off
        final SocketConfig socketConfig = SocketConfig
            .custom()
            .setSoTimeout(DurationUtils.toMillisInt(builder.getSoTimeoutDuration(fileSystemOptions)))
            .build();
        // @formatter:on

        connManager.setDefaultSocketConfig(socketConfig);

        return connManager;
    }

    private CookieStore createDefaultCookieStore(final Http4FileSystemConfigBuilder builder,
            final FileSystemOptions fileSystemOptions) {
        final CookieStore cookieStore = new BasicCookieStore();
        final Cookie[] cookies = builder.getCookies(fileSystemOptions);

        if (cookies != null) {
            Stream.of(cookies).forEach(cookieStore::addCookie);
        }

        return cookieStore;
    }

    private RequestConfig createDefaultRequestConfig(final Http4FileSystemConfigBuilder builder,
        final FileSystemOptions fileSystemOptions) {
        return RequestConfig.custom()
            .setConnectTimeout(DurationUtils.toMillisInt(builder.getConnectionTimeoutDuration(fileSystemOptions)))
            .build();
    }

    private HostnameVerifier createHostnameVerifier(final Http4FileSystemConfigBuilder builder,
        final FileSystemOptions fileSystemOptions) {
        return builder.isHostnameVerificationEnabled(fileSystemOptions) ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    }

    /**
     * Create an {@link HttpClient} object for an http4 file system.
     *
     * @param builder Configuration options builder for http4 provider
     * @param rootName The root path
     * @param fileSystemOptions The file system options
     * @return an {@link HttpClient} object
     * @throws FileSystemException if an error occurs.
     */
    protected HttpClient createHttpClient(final Http4FileSystemConfigBuilder builder, final GenericFileName rootName,
            final FileSystemOptions fileSystemOptions) throws FileSystemException {
        return createHttpClientBuilder(builder, rootName, fileSystemOptions).build();
    }

    /**
     * Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http4FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
     *
     * @param builder Configuration options builder for HTTP4 provider
     * @param rootName The root path
     * @param fileSystemOptions The FileSystem options
     * @return an {@link HttpClientBuilder} object
     * @throws FileSystemException if an error occurs
     */
    protected HttpClientBuilder createHttpClientBuilder(final Http4FileSystemConfigBuilder builder, final GenericFileName rootName,
            final FileSystemOptions fileSystemOptions) throws FileSystemException {
        final List<Header> defaultHeaders = new ArrayList<>();
        defaultHeaders.add(new BasicHeader(HTTP.USER_AGENT, builder.getUserAgent(fileSystemOptions)));

        final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions)
                ? DefaultConnectionReuseStrategy.INSTANCE
                : NoConnectionReuseStrategy.INSTANCE;
        final SSLContext sslContext = createSSLContext(builder, fileSystemOptions);
        final HostnameVerifier hostNameVerifier = createHostnameVerifier(builder, fileSystemOptions);
        final HttpClientBuilder httpClientBuilder =
                HttpClients.custom()
                .setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions))
                .setConnectionManager(createConnectionManager(builder, fileSystemOptions, sslContext, hostNameVerifier))
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(hostNameVerifier)
                .setConnectionReuseStrategy(connectionReuseStrategy)
                .setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions))
                .setDefaultHeaders(defaultHeaders)
                .setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions));

        if (!builder.getFollowRedirect(fileSystemOptions)) {
            httpClientBuilder.disableRedirectHandling();
        }

        return httpClientBuilder;
    }

    /**
     * Create an {@link HttpClientContext} object for an http4 file system.
     *
     * @param builder Configuration options builder for http4 provider
     * @param rootName The root path
     * @param fileSystemOptions The FileSystem options
     * @param authData The {@code UserAuthentiationData} object
     * @return an {@link HttpClientContext} object
     */
    protected HttpClientContext createHttpClientContext(final Http4FileSystemConfigBuilder builder,
            final GenericFileName rootName, final FileSystemOptions fileSystemOptions,
            final UserAuthenticationData authData) {

        final HttpClientContext clientContext = HttpClientContext.create();
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        clientContext.setCredentialsProvider(credsProvider);

        final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())));
        final String password = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())));

        if (!StringUtils.isEmpty(username)) {
            credsProvider.setCredentials(new AuthScope(rootName.getHostName(), rootName.getPort()),
                    new UsernamePasswordCredentials(username, password));
        }

        final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);

        if (proxyHost != null) {
            final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);

            if (proxyAuth != null) {
                final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth,
                    new UserAuthenticationData.Type[] {UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD});

                if (proxyAuthData != null) {
                    final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                            UserAuthenticatorUtils.toString(
                                    UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.USERNAME, null)),
                            UserAuthenticatorUtils.toString(
                                    UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.PASSWORD, null)));

                    credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()),
                            proxyCreds);
                }

                if (builder.isPreemptiveAuth(fileSystemOptions)) {
                    final AuthCache authCache = new BasicAuthCache();
                    final BasicScheme basicAuth = new BasicScheme();
                    authCache.put(proxyHost, basicAuth);
                    clientContext.setAuthCache(authCache);
                }
            }
        }

        return clientContext;
    }

    private HttpRoutePlanner createHttpRoutePlanner(final Http4FileSystemConfigBuilder builder,
            final FileSystemOptions fileSystemOptions) {
        final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);

        if (proxyHost != null) {
            return new DefaultProxyRoutePlanner(proxyHost);
        }

        return new SystemDefaultRoutePlanner(ProxySelector.getDefault());
    }

    /**
     * Create {@link SSLContext} for HttpClient. Invoked by {@link #createHttpClientBuilder(Http4FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
     *
     * @param builder Configuration options builder for HTTP4 provider
     * @param fileSystemOptions The FileSystem options
     * @return a {@link SSLContext} for HttpClient
     * @throws FileSystemException if an error occurs
     */
    protected SSLContext createSSLContext(final Http4FileSystemConfigBuilder builder,
            final FileSystemOptions fileSystemOptions) throws FileSystemException {
        try {
            final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            sslContextBuilder.setKeyStoreType(builder.getKeyStoreType(fileSystemOptions));

            File keystoreFileObject = null;
            final String keystoreFile = builder.getKeyStoreFile(fileSystemOptions);

            if (!StringUtils.isEmpty(keystoreFile)) {
                keystoreFileObject = new File(keystoreFile);
            }

            if (keystoreFileObject != null && keystoreFileObject.exists()) {
                final String keystorePass = builder.getKeyStorePass(fileSystemOptions);
                final char[] keystorePassChars = keystorePass != null ? keystorePass.toCharArray() : null;
                sslContextBuilder.loadTrustMaterial(keystoreFileObject, keystorePassChars, TrustAllStrategy.INSTANCE);
            } else {
                sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
            }

            return sslContextBuilder.build();
        } catch (final KeyStoreException e) {
            throw new FileSystemException("Keystore error. " + e.getMessage(), e);
        } catch (final KeyManagementException e) {
            throw new FileSystemException("Cannot retrieve keys. " + e.getMessage(), e);
        } catch (final NoSuchAlgorithmException e) {
            throw new FileSystemException("Algorithm error. " + e.getMessage(), e);
        } catch (final CertificateException e) {
            throw new FileSystemException("Certificate error. " + e.getMessage(), e);
        } catch (final IOException e) {
            throw new FileSystemException("Cannot open key file. " + e.getMessage(), e);
        }
    }

    @Override
    protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
            throws FileSystemException {
        final GenericFileName rootName = (GenericFileName) name;

        UserAuthenticationData authData = null;
        HttpClient httpClient;
        HttpClientContext httpClientContext;

        try {
            final Http4FileSystemConfigBuilder builder = Http4FileSystemConfigBuilder.getInstance();
            authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES);
            httpClientContext = createHttpClientContext(builder, rootName, fileSystemOptions, authData);
            httpClient = createHttpClient(builder, rootName, fileSystemOptions);
        } finally {
            UserAuthenticatorUtils.cleanup(authData);
        }

        return new Http4FileSystem(rootName, fileSystemOptions, httpClient, httpClientContext);
    }

    @Override
    public Collection<Capability> getCapabilities() {
        return CAPABILITIES;
    }

    @Override
    public FileSystemConfigBuilder getConfigBuilder() {
        return Http4FileSystemConfigBuilder.getInstance();
    }

    private HttpHost getProxyHttpHost(final Http4FileSystemConfigBuilder builder,
            final FileSystemOptions fileSystemOptions) {
        final String proxyHost = builder.getProxyHost(fileSystemOptions);
        final int proxyPort = builder.getProxyPort(fileSystemOptions);
        final String proxyScheme = builder.getProxyScheme(fileSystemOptions);

        if (!StringUtils.isEmpty(proxyHost) && proxyPort > 0) {
            return new HttpHost(proxyHost, proxyPort, proxyScheme);
        }

        return null;
    }

}


text:
extern crate toml;

use config::Config;
use errors::*;
use search_command::SearchCommand;
use std::fs::File;
use std::io::Read;
use std::process;

pub struct Workflow {
    search: SearchCommand,
}

impl Workflow {
    pub fn search(&self) -> &SearchCommand {
        &self.search
    }
}

pub fn new() -> Workflow {
    let config = match load_config() {
        Ok(c) => c,
        Err(e) => {
            error!("{}", e);
            process::exit(1);
        }
    };
    dbg!(&config);
    Workflow {
        search: SearchCommand { config },
    }
}

fn load_config() -> Result<Config> {
    let mut config_file = dirs::home_dir().unwrap();
    config_file.push(".jiraconfig");
    let mut file = File::open(&config_file).chain_err(|| "Missing .jiraconfig".to_string())?;

    let mut toml_string = String::new();
    file.read_to_string(&mut toml_string).unwrap();

    toml::from_str::<Config>(&toml_string).chain_err(|| "Invalid format {}".to_string())
}


text:
require_relative 'spec_helper'

module RTrail
  describe Project do
    context "Class methods" do
      describe "#all" do
        it "returns all Projects" do
          projects = Project.all
          expect(projects).to be_a_list_of(Project)
        end
      end

      describe "#by_name" do
        it "returns the Project with the given name if it exists" do
          project = Project.by_name("First Project")
          expect(project).to be_a(Project)
          expect(project.name).to eq("First Project")
        end

        it "raises RTrail::NotFound if no project exists with the given name" do
          expect {
            Project.by_name("Bogus Project Name")
          }.to raise_error(RTrail::NotFound, /not found in TestRail/)
        end
      end
    end

    context "Instance methods" do
      let(:project1) { Project.get(1) }
      let(:project2) { Project.get(2) }

      describe "#initialize" do
        it "gets the Project data" do
          expect(project1).to be_a(Project)
          expect(project1.id).to eq(1)
          expect(project1.name).to eq("First Project")
          expect(project2.id).to eq(2)
          expect(project2.name).to eq("Second Project")
        end
      end

      describe "#suite_by_name" do
        it "gets the Suite with the given name if it exists" do
          suite = project1.suite_by_name("First Suite")
          expect(suite).to be_a(Suite)
          expect(suite.name).to eq("First Suite")
        end

        it "raises RTrail::NotFound if no suite exists with the given name" do
          expect {
            project1.suite_by_name("Third Suite")
          }.to raise_error(RTrail::NotFound, /not found in project/)
          expect {
            project2.suite_by_name("First Suite")
          }.to raise_error(RTrail::NotFound, /not found in project/)
        end
      end

      describe "#suite" do
        it "returns a Suite by id" do
          suite = project1.suite(1)
          expect(suite).to be_a(Suite)
          expect(suite.id).to eq(1)
          expect(suite.name).to eq("First Suite")
        end

        it "returns a Suite by name" do
          suite = project1.suite("First Suite")
          expect(suite).to be_a(Suite)
          expect(suite.id).to eq(1)
          expect(suite.name).to eq("First Suite")
        end
      end

      describe "#suite_id" do
        it "returns the id for a Suite" do
          suite_id = project1.suite_id("First Suite")
          expect(suite_id).to eq(1)
        end
      end

      describe "#plans" do
        it "returns all Plans in the Project" do
          plans = project1.plans
          expect(plans).to be_a_list_of(Plan)
          expect(plans.count).to eq(1)
        end
      end

      describe "#runs" do
        it "returns all Runs in the Project" do
          runs = project1.runs
          expect(runs.count).to eq(2)
        end
      end

      describe "#suites" do
        it "returns all Suites in the project" do
          suites = project1.suites
          expect(suites.count).to eq(2)
        end
      end

      describe "#run" do
        it "returns an existing Run with the same name" do
          run = project1.run("First Suite", "First Run")
          expect(run).to be_a(Run)
          expect(run.id).to eq(1)
          expect(run.suite_id).to eq(1)
        end

        it "creates a new Run and returns it" do
          run = project1.run("First Suite", "New Run Name")
          expect(run).to be_a(Run)
          expect(run.suite_id).to eq(1)
        end
      end

      describe "#add_run" do
        it "returns the new Run" do
          run = project1.add_run("First Suite", :name => "New Run Name")
          expect(run).to be_a(Run)
          expect(run.suite_id).to eq(1)
        end
      end
    end

  end
end # module RTrail


text: <i-number-input v-model="value" :min="1" :max="10" placeholder="Enter a number.." />


text:
echo -n "Copying Atom settings.."
mv -f ~/.atom ~/dotfiles_old/
ln -s $HOME/dotfiles/atom ~/.atom
echo "done"

declare -a FILES_TO_SYMLINK=(

  'shell/aliases'
  'shell/bash_profile'

  'git/gitattributes'
  'git/gitconfig'
  'git/gitignore'

)

# backup existing dotfiles
for i in ${FILES_TO_SYMLINK[@]}; do
  echo "Moving any existing dotfiles from ~ to $dir_backup"
  mv ~/.${i##*/} ~/dotfiles_old/
done


text:
package org.conbere.irc

import java.net.InetSocketAddress
import com.typesafe.scalalogging.log4j.Logging

import akka.actor._
import akka.util.{ ByteString, ByteStringBuilder }

import scala.concurrent.ExecutionContext.Implicits.global

import Tokens._
import ControlChars._
import Messages._

case object Connected

class Client(serverName:String, port:Int, responder:ActorRef) extends Actor with Logging {
  val state = IO.IterateeRef.Map.async[IO.Handle]()(context.dispatcher)
  val address = new InetSocketAddress(serverName, port)

  var handle:Option[IO.SocketHandle] = None

  def utf8(bytes:ByteString) =
    bytes.decodeString("UTF-8").trim

  override def preStart {
    println("Connecting to: " + address)
    IOManager(context.system).connect(address)
  }

  def parseMessage(str:String) =
    Parser.apply(str) match {
      case Parser.Success(message, _) =>
        println("Received: " + message)
        Some(message)
      case _ =>
        logger.error("Could not parse: " + str)
        None
    }

  def receive = {
    case IO.Connected(socket, address) =>
      handle = Some(socket)

      responder ! Connected

      state(socket).flatMap(_ =>
        IO.repeat {
          IO.takeUntil(CRLF).map { in =>
            for ( message <- parseMessage(utf8(in))) {
              responder ! message
            }
          }
        }
      )

    case IO.Read(socket, bytes) =>
      state(socket)(IO.Chunk(bytes))

    case IO.Closed(socket, cause) =>
      state(socket)(IO.EOF)
      state -= socket
      handle = None

    case response:Response =>
      handle.foreach { socket =>
        socket.write(
          (new ByteStringBuilder ++= response.byteString ++= CRLF).result
        )
      }
  }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\user\Tests\UserTimeZoneTest.
 */

namespace Drupal\user\Tests;

use Drupal\simpletest\WebTestBase;

/**
 * Set a user time zone and verify that dates are displayed in local time.
 *
 * @group user
 */
class UserTimeZoneTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('node');

  /**
   * Tests the display of dates and time when user-configurable time zones are set.
   */
  function testUserTimeZone() {
    // Setup date/time settings for Los Angeles time.
    $this->config('system.date')
      ->set('timezone.user.configurable', 1)
      ->set('timezone.default', 'America/Los_Angeles')
      ->save();
    entity_load('date_format', 'medium')
      ->setPattern('Y-m-d H:i T')
      ->save();

    // Create a user account and login.
    $web_user = $this->drupalCreateUser();
    $this->drupalLogin($web_user);

    // Create some nodes with different authored-on dates.
    // Two dates in PST (winter time):
    $date1 = '2007-03-09 21:00:00 -0800';
    $date2 = '2007-03-11 01:00:00 -0800';
    // One date in PDT (summer time):
    $date3 = '2007-03-20 21:00:00 -0700';
    $this->drupalCreateContentType(array('type' => 'article'));
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
    $node3 = $this->drupalCreateNode(array('created' => strtotime($date3), 'type' => 'article'));

    // Confirm date format and time zone.
    $this->drupalGet('node/' . $node1->id());
    $this->assertText('2007-03-09 21:00 PST', 'Date should be PST.');
    $this->drupalGet('node/' . $node2->id());
    $this->assertText('2007-03-11 01:00 PST', 'Date should be PST.');
    $this->drupalGet('node/' . $node3->id());
    $this->assertText('2007-03-20 21:00 PDT', 'Date should be PDT.');

    // Change user time zone to Santiago time.
    $edit = array();
    $edit['mail'] = $web_user->getEmail();
    $edit['timezone'] = 'America/Santiago';
    $this->drupalPostForm("user/" . $web_user->id() . "/edit", $edit, t('Save'));
    $this->assertText(t('The changes have been saved.'), 'Time zone changed to Santiago time.');

    // Confirm date format and time zone.
    $this->drupalGet('node/' . $node1->id());
    $this->assertText('2007-03-10 02:00 CLST', 'Date should be Chile summer time; five hours ahead of PST.');
    $this->drupalGet('node/' . $node2->id());
    $this->assertText('2007-03-11 05:00 CLT', 'Date should be Chile time; four hours ahead of PST');
    $this->drupalGet('node/' . $node3->id());
    $this->assertText('2007-03-21 00:00 CLT', 'Date should be Chile time; three hours ahead of PDT.');
  }
}


text:
$[/myProject/preamble]

my $PROJECT_NAME = '$[/myProject/projectName]';
my $PLUGIN_NAME = '@PLUGIN_NAME@';
my $PLUGIN_KEY  = '@PLUGIN_KEY@';
use Data::Dumper;
use File::Spec;

$| = 1;

main();

sub main {
    my $wl = EC::WebLogic->new(
        project_name => $PROJECT_NAME,
        plugin_name  => $PLUGIN_NAME,
        plugin_key   => $PLUGIN_KEY
    );
    my $params = $wl->get_params_as_hashref(
        'configname',
        'cf_name',
        'jms_module_name',
    );
    my $cred = $wl->get_credentials($params->{configname});
    if ( $cred->{java_home} ) {
        $wl->out( 1, "JAVA_HOME was provided" );
    }

    my $render_params = {
        username     => $cred->{user},
        password     => $cred->{password},
        weblogic_url => $cred->{weblogic_url},
        admin_url    => $cred->{weblogic_url},
        %{$params}
    };

    my $wlst_path = $wl->get_wlst_path();

    #rewrite to map when get chance
    # $render_params->{$_} = $params->{$_} foreach keys %{ $params };

    my $template_path = '/myProject/jython/delete_connection_factory.jython';
    my $template = $wl->render_template_from_property( $template_path, $render_params );

    $wl->out(2, "Generated script:\n", $template);

    my $res = $wl->execute_jython_script(
        shell          => $wlst_path,
        script_path    => File::Spec->catfile($ENV{COMMANDER_WORKSPACE}, 'exec.jython'),
        script_content => $template,
    );
    $wl->process_response($res);
    return;
}


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

<rootTag>
  <Award>
    <AwardTitle>Doctoral Dissertation Research: American Property Taxes and Changing Social Structures</AwardTitle>
    <AwardEffectiveDate>08/01/2014</AwardEffectiveDate>
    <AwardExpirationDate>07/31/2015</AwardExpirationDate>
    <AwardAmount>25200</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      04050000
      <Directorate>
        <LongName>Direct For Social, Behav & Economic Scie</LongName>
      </Directorate>
      <Division>
        <LongName>Divn Of Social and Economic Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>jonathan gould</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>Tax rebellions do not occur in a social vacuum. Taxation offers a blueprint, in symbolic and concrete terms, for uncovering the fundamental structures of social, economic, and political life. This research will further understandings of how the legacies of past social hierarchies contribute to contemporary tax debates. <br/><br/>Utilizing ethnographic content analysis of archival data collected from historical societies and libraries, this project examines three case studies of rebellions against property taxes. Particular attention is placed on the relationship between changing social structures and property tax revolts in the United States. Primary data will be collected from a wide variety of documentary and media sources and analyzed with qualitative analytic computer software to test the central tenets of relevant theories.</AbstractNarration>
    <MinAmdLetterDate>07/30/2014</MinAmdLetterDate>
    <MaxAmdLetterDate>07/30/2014</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1424422</AwardID>
    <Investigator>
      <FirstName>David</FirstName>
      <LastName>Embrick</LastName>
      <EmailAddress>dembric@luc.edu</EmailAddress>
      <StartDate>07/30/2014</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Kasey</FirstName>
      <LastName>Henricks</LastName>
      <EmailAddress>khenricks@luc.edu</EmailAddress>
      <StartDate>07/30/2014</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Loyola University of Chicago</Name>
      <CityName>CHICAGO</CityName>
      <ZipCode>606601537</ZipCode>
      <PhoneNumber>7735082471</PhoneNumber>
      <StreetAddress>1032 W. Sheridan Road</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Illinois</StateName>
      <StateCode>IL</StateCode>
    </Institution>
    <ProgramElement>
      1372
      <Text>LAW AND SOCIAL SCIENCES</Text>
    </ProgramElement>
    <ProgramReference>
      9179
      <Text>GRADUATE INVOLVEMENT</Text>
    </ProgramReference>
    <ProgramReference>
      SMET
      <Text>SCIENCE, MATH, ENG & TECH EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
require "sinderella/version"
require "sinderella/data_store"
require 'crimp'

module Sinderella
  def self.transforms(data, till_midnight = 60)
    identifier  = Crimp.signature(data)
    cloned_data = deep_copy data
    transformed = yield cloned_data

    self.store({
      :id => identifier,
      :original => data,
      :transformed => transformed
    })

    self.check(identifier, till_midnight)

    identifier
  end

  def self.get(id)
    DataStore.instance.get(id)[:transformed]
  end

  def self.midnight(id)
    reset_data_at(id)
  end

  private

  def self.store(data)
    DataStore.instance.set(data)
  end

  def self.deep_copy(object)
    Marshal.load(Marshal.dump(object))
  end

  def self.check(id, seconds)
    Thread.new { sleep seconds; reset_data_at id }
  end

  def self.reset_data_at(id)
    DataStore.instance.reset(id)
  end
end


text:
using System;

namespace SquareRoot
{
    public class Square
    {
        public static void Main(string[] args)
        {
            int number = 12345;
            double result = Math.Sqrt(number);
            Console.WriteLine(result);
        }
    }
}


text:
package com.iamdilipkumar.movies.movies.utilities.network;

import com.iamdilipkumar.movies.movies.models.MoviesResult;
import com.iamdilipkumar.movies.movies.models.ReviewsResult;
import com.iamdilipkumar.movies.movies.models.TrailersResult;

import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

/**
 * Created on 15/04/17.
 *
 * @author dilipkumar4813
 * @version 1.0
 */

public interface MoviesInterface {

    @GET("{directory}")
    Observable<MoviesResult> getMovies(@Path("directory") String directory, @Query(NetworkUtils.MOVIES_PAGE) String pageNo);

    @GET("{movie_id}/reviews")
    Observable<ReviewsResult> getReviews(@Path("movie_id") String movieId);

    @GET("{movie_id}/videos")
    Observable<TrailersResult> getTrailers(@Path("movie_id") String movieId);
}


text:
package org.apache.solr.response.transform;

import org.apache.solr.common.params.ShardParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.request.SolrQueryRequest;

/**
 *
 * @since solr 4.0
 */
public class ShardAugmenterFactory extends TransformerFactory
{
  @Override
  public DocTransformer create(String field, SolrParams params, SolrQueryRequest req) {
    String v = req.getParams().get(ShardParams.SHARD_URL);
    if( v == null ) {
      if( req.getParams().getBool(ShardParams.IS_SHARD, false) ) {
        v = "[unknown]";
      }
      else {
        v = "[not a shard request]";
      }
    }
    return new ValueAugmenter( field, v );
  }
}


text:
package io.joynr.messaging;

import java.util.Properties;

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;

public class DummyApplicationModule extends AbstractModule {

    private Properties properties;

    public DummyApplicationModule(Properties properties) {
        this.properties = properties;
    }

    @Override
    protected void configure() {
        Names.bindProperties(binder(), properties);
    }

}


text:
Since version 0.7.0 - AliceBlue this package has support for TypeDefinition used in the global `__themeState__` object. In case the TypeScript code need to reference to this object somwhere.

To make use add the following import statement in your code.

In your web part code add the following line to your webpart or extension project.

```typescript
import uiFabricCSS from 'spfx-uifabric-themes';
```

After that you should see the following extensions on the window object.

![TypeScript themestate][TypeScript]
[TypeScript]: ./assets/typedefiniton-themestate.png


text:
{{
// Get the hyperlink field
var hyperlinkField = SPUtility.GetSPField('Hyperlink Field');

// Set the field to link (shamelessly) to SPUtility.js on codeplex
hyperlinkField.SetValue('http://sputility.codeplex.com', 'SPUtility.js');

// Gets the value of the hyperlink field as an array
var values = hyperlinkField.GetValue();
// values[0](0) = 'http://sputility.codeplex.com'
// values[1](1) = 'SPUtility.js'

// Make the hyperlink field read only, displays as a clickable hyperlink
hyperlinkField.MakeReadOnly();
// also there is the ability to display the text only (no hyperlink)
// will display as "http://sputility.codeplex.com, SPUtility.js"
hyperlinkField.MakeReadOnly( { TextOnly: true } );

// Hide the field
hyperlinkField.Hide();
}}