text:
'use strict';

var UserKeystroke = require('./../Library/UserKeystroke')
/*
* Raptor.js - Node framework
* Controlador ES6
*
*
*/
class KDynamics extends R.Controller {

	configure() {
		$injector('Bio').service.testUser=this.serviceTestUser
	}

	/**
	 *
	 * @param {*} options
	 */
	static bioMiddleware(options) {

		var none=function(req,res,next){

			next()
		}
		if(R.options.database.state=='off' || !R.options.database.state){
			console.log('bio require una conexión activa con la base de datos.')
			return none;
		}

		if(!options.passwordField)
			options.passwordField='password'

		if(!options.bioSession){
			console.error("bio Middleware error: configure un nombre para el parametro bioSession")
			return none
		}

		if(!options.getActiveUser){
			console.error("bio Middleware error: configure la funcion getActiveUser para devolver el nombre del usuario autenticado")
			return none
		}

		var self = this;
		options.hasNewPassword=function(req,bio,field,done){

			done(bio!==field)
		};

		/**(function (push) {
			R.app._router.stack.__push = push
			R.app._router.stack.push = function () {
				return this.unshift.apply(this, arguments);
			};
		})(R.app._router.stack.push);
		R.app.all('/mioooooooo',function(){});
		(function (push) {

			R.app._router.stack.push = function () {
				return push.apply(this, arguments);
			};
		})(R.app._router.stack.__push);

		console.log(R.app._router.stack)*/
		if(options.frontLogin)
			R.on('sendresponse',function(req){

				if(req.res.statusCode==401 && new RegExp(options.frontLogin).test(req.url)){

					req.res.render('bio:login', {
						name: options.passwordField
					}, function (err, str) {
						req.viewPlugin.set('after_response_body', str)
					})
				}

			})
		$injector('Bio').watch.push({
			name: options.bioSession,
			field: options.passwordField
		})

		return function (req, res, next) {

			options.logout=function logout(){
				delete req.session[options.bioSession+"kb10"]
				delete req.session[options.bioSession]
			}
			if(options.init)
				options.init.apply(options,arguments)

			//Verificar si esta autenticado biometricamente, dejarlo entrar si es true
			if (req.session[options.bioSession+"kb10"]) {

				next()
			} else {

				options.getActiveUser.apply(options, [req, res, function (username) {
					R.getModels('bio').biouser
						.findOne({
							where: {
								username: options.bioSession+"*:"+username
							}
						})
						.then(function (bio) {
							if (!bio){
								req.session[options.bioSession] = {
									username: username,
									state: 0
								}
								req.session.save(function () {
									res.render('bio:samples.ejs',{
										name: options.bioSession
									})
								})
							}else {
								if (req.session[options.bioSession]) {
									res.render("bio:auth.ejs",{
										name: options.bioSession,
										hint:''
									})
								} else {

									if (req.session.biomarker && req.session.biomarker[options.passwordField]) {

										var passwordField=req.session.biomarker[options.passwordField].pass;
										var sample=JSON.parse(req.session.biomarker[options.passwordField].bio);

										delete req.session.biomarker[options.passwordField];

										var currentPass = ''
										JSON.parse(bio.data).samples[0].forEach(function (val) {
											currentPass += val.key
										})
										options.hasNewPassword.apply(this, [req, currentPass,passwordField, function (result) {
											if (!result) {

												req.session[options.bioSession] = {
													username: username,
													state: 1
												}
												req.session.save(function () {
													//verificar aqui mismo si existe un bio y consumir servicio

													$injector('Bio').service.testUser(req, options.bioSession, bio, sample, function(result){
														res.redirect(req.url)
													})
												})
											} else {
												R.getModels('bio').biouser
													.destroy({
														where: {
															username: options.bioSession+"*:"+username
														}
													})
													.then(function (user) {
														req.session[options.bioSession] = {
															username: username,
															state: 0
														}
														req.session.save(function () {
															res.redirect(req.url)
														})
													})
													.catch(function () {
														req.session[options.bioSession] = {
															username: username,
															state: 0
														}
														req.session.save(function () {
															res.redirect(req.url)
														})
													})
											}
										}])
									} else {
										//error
										req.session[options.bioSession] = {
											username: username,
											state: 1
										}
										req.session.save(function () {
											res.render("bio:auth.ejs",{
												name: options.bioSession,
												hint:''
											})
										})
									}
								}
							}

						})
				}])

			}
		}
	}

	serviceTestUser(req, name, biouser, sample, callback) {

		if (biouser) {
			var userKeystroke = new UserKeystroke();
			userKeystroke.setData(JSON.parse(biouser.data))
			if (userKeystroke.testSample(sample)) {
				userKeystroke.train(sample)

				req.session[name+"kb10"] = true

				biouser.update({
					data: JSON.stringify(userKeystroke.getData())
				})
				.then(function () {
					req.session.save(function () {
						callback.apply(this,['ok'])
					})
				})

			} else {
				var percentDiv = userKeystroke.umbral / 100;
				var diff = userKeystroke.lastscore - userKeystroke.umbral;
				var hint = ''

				if (percentDiv * 25 > diff)
					hint = 'Uhhhh, buen intento !!, sigue probando suerte'
				if (percentDiv * 25 < diff && percentDiv * 200 > diff)
					hint = 'Ummm, pareces cansado !!, concentrate y teclea como siempre'
				if (percentDiv * 200 < diff && percentDiv * 400 > diff)
					hint = 'Noup, Noup, Noup !!'
				if (percentDiv * 400 < diff && percentDiv * 700 > diff)
					hint = 'Ehhhh !!'
				if (percentDiv * 700 < diff)
					hint = 'Si quieres acceder creo que será mejor contactar con el usuario original, no crees?'

				callback.apply(this,[hint])
			}
		}else{
			callback.apply(this,['404'])
		}

	}

}

module.exports = KDynamics;


text:
import {DTYPE_ENUM_TO_NAME} from '../tf_dtypes';
import {DebugTensorValue, TensorDebugMode} from './debugger_types';

export interface RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode;
  array: null | number[];
}

export interface RawDebugTensorValueNoTensor extends RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode.NO_TENSOR;
  array: null;
}

export interface RawDebugTensorValueCurtHealth extends RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode.CURT_HEALTH;
  array: [
    number, // Tensor ID.
    number // 0-1 indicator for the presence of inf/nan.
  ];
}

export interface RawDebugTensorValueConciseHealth extends RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode.CURT_HEALTH;
  array: [
    number, // Tensor ID.
    number, // Element count (size).
    number, // -inf count.
    number, // +inf count.
    number // nan count.
  ];
}

export interface RawDebugTensorValueShape extends RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode.SHAPE;
  array: [
    number, // Tensor ID.
    number, // DType enum value.
    number, // Rank.
    number, // Size.
    number, // Shape truncated at head to a maximum length of 6.
    number,
    number,
    number,
    number,
    number
  ];
}

export interface RawDebugTensorValueFullHealth extends RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode.FULL_HEALTH;
  array: [
    number, // Tensor ID.
    number, // Device ID.
    number, // DType enum value.
    number, // Rank.
    number, // Size.
    number, // -inf count.
    number, // +inf count.
    number, // nan count.
    number, // -finite count.
    number, // zero count.
    number // +finite count.
  ];
}

export interface RawDebugTensorValueFullTensor extends RawDebugTensorValue {
  tensorDebugMode: TensorDebugMode.FULL_HEALTH;
  array: null;
}

/**
 * Parse a number array that represents debugging summary of an instrumented
 * tensor value.
 *
 * @param tensorDebugMode and the array of number that represents various
 *   aspect of the instrumented tensor. The semantics of the numbers are
 *   determined by `tensorDebugMode`.
 * @returns A DebugTensorValue object with the same information as
 *   carried by `array`, but represented in a more explicit fashion.
 *   For numbers that represent breakdown of numeric values by type
 *   (e.g., counts of -inf, +inf and nan), the corresponding fields
 *   in the returned object will be defined only if the count is non-zero.
 */
export function parseDebugTensorValue(
  raw: RawDebugTensorValue
): DebugTensorValue {
  const {tensorDebugMode, array} = raw;
  switch (tensorDebugMode) {
    case TensorDebugMode.NO_TENSOR: {
      if (array !== null) {
        throw new Error(
          'Unexpectedly received non-null debug-tensor-value array ' +
            'under NO_TENSOR mode'
        );
      }
      return {};
    }
    case TensorDebugMode.CURT_HEALTH: {
      if (array === null || array.length !== 2) {
        throw new Error(
          `Under CURT_HEALTH mode, expected debug-tensor-value array ` +
            `to have length 2, but got ${JSON.stringify(array)}`
        );
      }
      return {
        hasInfOrNaN: Boolean(array[1]),
      };
    }
    case TensorDebugMode.CONCISE_HEALTH: {
      if (array === null || array.length !== 5) {
        throw new Error(
          `Under CONCISE_HEALTH mode, expected debug-tensor-value array ` +
            `to have length 5, but got ${JSON.stringify(array)}`
        );
      }
      const value: DebugTensorValue = {
        size: array[1],
      };
      if (array[2] > 0) {
        value.numNegativeInfs = array[2];
      }
      if (array[3] > 0) {
        value.numPositiveInfs = array[3];
      }
      if (array[4] > 0) {
        value.numNaNs = array[4];
      }
      return value;
    }
    case TensorDebugMode.SHAPE: {
      if (array === null || array.length !== 10) {
        throw new Error(
          `Under SHAPE mode, expected debug-tensor-value array ` +
            `to have length 10, but got ${JSON.stringify(array)}`
        );
      }
      const rank = array[2];
      let shape: number[] = array.slice(4, Math.min(4 + rank, array.length));
      if (shape.length < rank) {
        // The SHAPE mode truncates the shape at head.
        shape = new Array<number>(rank - shape.length).concat(shape);
      }
      return {
        dtype: DTYPE_ENUM_TO_NAME[array[1]],
        rank,
        size: array[3],
        shape,
      };
    }
    case TensorDebugMode.FULL_HEALTH: {
      if (array === null || array.length !== 11) {
        throw new Error(
          `Under FULL_HEALTH mode, expected debug-tensor-value array ` +
            `to have length 11, but got ${JSON.stringify(array)}`
        );
      }
      const rank = array[3];
      const value: DebugTensorValue = {
        dtype: DTYPE_ENUM_TO_NAME[array[2]],
        rank,
        size: array[4],
      };
      if (array[5] > 0) {
        value.numNegativeInfs = array[5];
      }
      if (array[6] > 0) {
        value.numPositiveInfs = array[6];
      }
      if (array[7] > 0) {
        value.numNaNs = array[7];
      }
      if (array[8] > 0) {
        value.numNegativeFinites = array[8];
      }
      if (array[9] > 0) {
        value.numZeros = array[9];
      }
      if (array[10] > 0) {
        value.numPositiveFinites = array[10];
      }
      return value;
    }
    case TensorDebugMode.FULL_TENSOR: {
      // Under FULL_TENSOR mode, the full tensor value is supplied via
      // separate means. No summary values are provided for the tensor value.
      if (array !== null) {
        throw new Error(
          'Unexpectedly received non-null debug-tensor-value array ' +
            'under FULL_TENSOR mode'
        );
      }
      return {};
    }
    default: {
      throw new Error(`Unrecognized tensorDebugMode: ${tensorDebugMode}`);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace doris {
namespace segment_v2 {

class BinaryPlainPageTest : public testing::Test {
public:
    BinaryPlainPageTest() {}

    virtual ~BinaryPlainPageTest() {
    }

    template <class PageBuilderType, class PageDecoderType>
    void TestBinarySeekByValueSmallPage() {
        std::vector<Slice> slices;
        slices.emplace_back("Hello");
        slices.emplace_back(",");
        slices.emplace_back("Doris");

        PageBuilderOptions options;
        options.data_page_size = 256 * 1024;
        PageBuilderType page_builder(options);
        size_t count = slices.size();

        Slice *ptr = &slices[0];
        Status ret = page_builder.add(reinterpret_cast<const uint8_t *>(ptr), &count);

        Slice s = page_builder.finish();
        PageDecoderOptions decoder_options;
        PageDecoderType page_decoder(s, decoder_options);
        Status status = page_decoder.init();
        ASSERT_TRUE(status.ok());

        //test1

        size_t size = 3;

        Arena arena;

        Slice* values = reinterpret_cast<Slice*>(arena.Allocate(size * sizeof(Slice)));
        uint8_t* null_bitmap = reinterpret_cast<uint8_t*>(arena.Allocate(BitmapSize(size)));
        ColumnBlock block(get_type_info(OLAP_FIELD_TYPE_VARCHAR), (uint8_t*)values, null_bitmap, &arena);
        ColumnBlockView column_block_view(&block);

        status = page_decoder.next_batch(&size, &column_block_view);
        ASSERT_TRUE(status.ok());

        Slice* value = reinterpret_cast<Slice*>(values);
        ASSERT_EQ (3, size);
        ASSERT_EQ ("Hello", value[0].to_string());
        ASSERT_EQ (",", value[1].to_string());
        ASSERT_EQ ("Doris", value[2].to_string());

        Slice* values2 = reinterpret_cast<Slice*>(arena.Allocate(size * sizeof(Slice)));
        ColumnBlock block2(get_type_info(OLAP_FIELD_TYPE_VARCHAR), (uint8_t*)values2, null_bitmap, &arena);
        ColumnBlockView column_block_view2(&block2);

        size_t fetch_num = 1;
        page_decoder.seek_to_position_in_page(2);
        status = page_decoder.next_batch(&fetch_num, &column_block_view2);
        ASSERT_TRUE(status.ok());
        Slice* value2 = reinterpret_cast<Slice*>(values2);
        ASSERT_EQ (1, fetch_num);
        ASSERT_EQ ("Doris", value2[0].to_string());
    }
};

TEST_F(BinaryPlainPageTest, TestBinaryPlainPageBuilderSeekByValueSmallPage) {
    TestBinarySeekByValueSmallPage<BinaryPlainPageBuilder, BinaryPlainPageDecoder>();
}

}
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
#pragma once

#include <cassert>
#include "thrust/host_vector.h"
#include "backend/evaluation.cuh"
#include "backend/weights.cuh"
#ifdef MPI_VERSION
#include "backend/mpi_vector.h"
#include "backend/mpi_evaluation.h"
#include "backend/mpi_precon.h"
#endif//MPI_VERSION
#include "geometry/geometry_traits.h"
#include "geometry/cartesian.h"
#include "geometry/cylindrical.h"
#ifdef MPI_VERSION
#include "geometry/mpi_grids.h"
#endif//MPI_VERSION

/*!@file
 *
 * geometry functions
 */

namespace dg{

/*! @brief Geometry routines
 *
 * @ingroup geometry
 * Only those routines that are actually called need to be implemented.
 * Don't forget to specialize in the dg namespace.
 */
namespace geo{
///@addtogroup geometry
///@{

/**
 * @brief Multiply the input with the volume element without the dG weights!
 *
 * Computes \f$ f = \sqrt{g}f\f$
 * @tparam container container class
 * @tparam Geometry Geometry class
 * @param inout input (contains result on output)
 * @param g the geometry object
 */
template<class container, class Geometry>
void multiplyVolume( container& inout, const Geometry& g)
{
    dg::geo::detail::doMultiplyVolume( inout, g, typename dg::GeometryTraits<Geometry>::metric_category());
}

/**
 * @brief Divide the input vector with the volume element without the dG weights
 *
 * Computes \f$ v = v/ \sqrt{g}\f$
 * @tparam container container class
 * @tparam Geometry Geometry class
 * @param inout input (contains result on output)
 * @param g the geometry object
 */
template<class container, class Geometry>
void divideVolume( container& inout, const Geometry& g)
{
    dg::geo::detail::doDivideVolume( inout, g, typename dg::GeometryTraits<Geometry>::metric_category());
}

/**
 * @brief Raises the index of a covariant vector in 2d
 *
 * Computes \f$ v^i = g^{ij}v_j\f$ for \f$ i,j\in \{1,2\}\f$ in the two dimensions of a 2x1 product space
 * @tparam container the container class
 * @tparam Geometry the geometry class
 * @param covX (input) covariant first component (may get destroyed!!)
 * @param covY (input) covariant second component (may get destroyed!!)
 * @param contraX (output) contravariant first component
 * @param contraY (output) contravariant second component
 * @param g The geometry object
 * @note covX, covY, contraX and contraY may not be the same
 */
template<class container, class Geometry>
void raisePerpIndex( container& covX, container& covY, container& contraX, container& contraY, const Geometry& g)
{
    assert( &covX != &contraX);
    assert( &covY != &contraY);
    assert( &covY != &covX);
    dg::geo::detail::doRaisePerpIndex( covX, covY, contraX, contraY, g, typename dg::GeometryTraits<Geometry>::metric_category());

}
/**
 * @brief Raises the index of a covariant vector in 2d and multiplies the perpendicular volume
 *
 * Computes \f$ v^i = \sqrt{g/g_{zz}} g^{ij}v_j\f$ for \f$ i,j\in \{1,2\}\f$ in the two dimensions of a 2x1 product space. This special
 * form occurs in the discretization of elliptic operators which is why it get's a special function.
 * @tparam container the container class
 * @tparam Geometry the geometry class
 * @param covX (input) covariant first component (may get destroyed!!)
 * @param covY (input) covariant second component (may get destroyed!!)
 * @param contraX (output) contravariant first component
 * @param contraY (output) contravariant second component
 * @param g The geometry object
 * @note covX, covY, contraX and contraY may not be the same
 */
template<class container, class Geometry>
void volRaisePerpIndex( container& covX, container& covY, container& contraX, container& contraY, const Geometry& g)
{
    assert( &covX != &contraX);
    assert( &covY != &contraY);
    assert( &covY != &covX);
    dg::geo::detail::doVolRaisePerpIndex( covX, covY, contraX, contraY, g, typename dg::GeometryTraits<Geometry>::metric_category());

}

/**
 * @brief Multiplies the two-dimensional volume element
 *
 * Computes \f$ f = \sqrt{g/g_{zz}}f\f$ on a 2x1 product space
 * @tparam container the container class
 * @tparam Geometry the geometry class
 * @param inout input (contains result on output)
 * @param g The geometry object
 */
template<class container, class Geometry>
void multiplyPerpVolume( container& inout, const Geometry& g)
{
    dg::geo::detail::doMultiplyPerpVolume( inout, g, typename dg::GeometryTraits<Geometry>::metric_category());
}

/**
 * @brief Divides the two-dimensional volume element
 *
 * Computes \f$ f = f /\sqrt{g/g_{zz}}\f$ on a 2x1 product space
 * @tparam container the container class
 * @tparam Geometry the geometry class
 * @param inout input (contains result on output)
 * @param g The geometry object
 */
template<class container, class Geometry>
void dividePerpVolume( container& inout, const Geometry& g)
{
    dg::geo::detail::doDividePerpVolume( inout, g, typename dg::GeometryTraits<Geometry>::metric_category());
}

/**
 * @brief Push forward a vector from cylindrical or Cartesian to a new coordinate system
 *
 * Computes \f[ v^x(x,y) = x_R (x,y) v^R(R(x,y), Z(x,y)) + x_Z v^Z(R(x,y), Z(x,y)) \\
               v^y(x,y) = y_R (x,y) v^R(R(x,y), Z(x,y)) + y_Z v^Z(R(x,y), Z(x,y)) \f]
   where \f$ x_R = \frac{\partial x}{\partial R}\f$, ...
 * @tparam Geometry The Geometry class
 * @param vR input R-component in cylindrical coordinates
 * @param vZ input Z-component in cylindrical coordinates
 * @param vx x-component of vector (gets properly resized)
 * @param vy y-component of vector (gets properly resized)
 * @param g The geometry object
 */
template<class Functor1, class Functor2, class Geometry>
void pushForwardPerp( Functor1 vR, Functor2 vZ,
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& vx,
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& vy,
        const Geometry& g)
{
    dg::geo::detail::doPushForwardPerp( vR, vZ, vx, vy, g, typename GeometryTraits<Geometry>::metric_category() );
}

///@cond
template<class Geometry>
void pushForwardPerp(
        double(fR)(double,double,double), double(fZ)(double, double, double),
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& out1,
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& out2,
        const Geometry& g)
{
    pushForwardPerp<double(double, double, double), double(double, double, double), Geometry>( fR, fZ, out1, out2, g);
}
///@endcond

/**
 * @brief Push forward a symmetric 2d tensor from cylindrical or Cartesian to a new coordinate system
 *
 * Computes \f[
 \chi^{xx}(x,y) = x_R x_R \chi^{RR} + 2x_Rx_Z \chi^{RZ} + x_Zx_Z\chi^{ZZ} \\
 \chi^{xy}(x,y) = x_R x_R \chi^{RR} + (x_Ry_Z+y_Rx_Z) \chi^{RZ} + x_Zx_Z\chi^{ZZ} \\
 \chi^{yy}(x,y) = y_R y_R \chi^{RR} + 2y_Ry_Z \chi^{RZ} + y_Zy_Z\chi^{ZZ} \\
               \f]
   where \f$ x_R = \frac{\partial x}{\partial R}\f$, ...
 * @tparam Geometry The Geometry class
 * @param chiRR input RR-component in cylindrical coordinates
 * @param chiRZ input RZ-component in cylindrical coordinates
 * @param chiZZ input ZZ-component in cylindrical coordinates
 * @param chixx xx-component of tensor (gets properly resized)
 * @param chixy xy-component of tensor (gets properly resized)
 * @param chiyy yy-component of tensor (gets properly resized)
 * @param g The geometry object
 */
template<class FunctorRR, class FunctorRZ, class FunctorZZ, class Geometry>
void pushForwardPerp( FunctorRR chiRR, FunctorRZ chiRZ, FunctorZZ chiZZ,
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& chixx,
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& chixy,
        typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector& chiyy,
        const Geometry& g)
{
    dg::geo::detail::doPushForwardPerp( chiRR, chiRZ, chiZZ, chixx, chixy, chiyy, g, typename GeometryTraits<Geometry>::metric_category() );
}

///@}
}//namespace geo

namespace create{
///@addtogroup geometry
///@{

/**
 * @brief Create the volume element on the grid (including weights!!)
 *
 * This is the same as the weights multiplied by the volume form \f$ \sqrt{g}\f$
 * @tparam Geometry Geometry class
 * @param g Geometry object
 *
 * @return  The volume form
 */
template< class Geometry>
typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector volume( const Geometry& g)
{
    return detail::doCreateVolume( g, typename GeometryTraits<Geometry>::metric_category());
}

/**
 * @brief Create the inverse volume element on the grid (including weights!!)
 *
 * This is the same as the inv_weights divided by the volume form \f$ \sqrt{g}\f$
 * @tparam Geometry Geometry class
 * @param g Geometry object
 *
 * @return  The inverse volume form
 */
template< class Geometry>
typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector inv_volume( const Geometry& g)
{
    return detail::doCreateInvVolume( g, typename GeometryTraits<Geometry>::metric_category());
}

///@}
}//namespace create

/**
 * @brief This function pulls back a function defined in cartesian coordinates to the curvilinear coordinate system
 *
 * @ingroup geometry
 * i.e. F(x,y) = f(R(x,y), Z(x,y)) in 2d
 * @tparam Functor The (binary or ternary) function object
 * @param f The function defined in cartesian coordinates
 * @param g The grid
 * @note Template deduction will fail if you overload functions with different dimensionality (e.g. double sine( double x) and double sine(double x, double y) )
 * You will want to rename those uniquely
 *
 * @return A set of points representing F
 */
template< class Functor, class Geometry>
typename HostVec< typename GeometryTraits<Geometry>::memory_category>::host_vector
    pullback( Functor f, const Geometry& g)
{
    return dg::detail::doPullback( f, g, typename GeometryTraits<Geometry>::metric_category(), typename GeometryTraits<Geometry>::dimensionality(), typename GeometryTraits<Geometry>::memory_category() );
}

}//namespace dg


text:
package fundamentals.tree.dfs.preorder.lc331_verifypreorderserializationofabinarytree;

import java.util.Stack;

/**
 * One way to serialize a binary tree is to use pre-order traversal.
 * When we encounter a non-null node, we record the node's value.
 * If it is a null node, we record using a sentinel value such as #.
 *
 *       _9_
 *      /   \
 *     3     2
 *    / \   / \
 *   4   1  #  6
 *  / \ / \   / \
 *  # # # #   # #
 *
 * For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#",
 * where # represents a null node. Given a string of comma separated values,
 * verify whether it is a correct preorder traversal serialization of a binary tree.
 * Find an algorithm without reconstructing the tree.
 * Each comma separated value in the string must be either an integer or a character '#' representing null pointer.
 * You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".
 * Example 1: "9,3,4,#,#,1,#,#,2,#,6,#,#". Return true.
 * Example 2: "1,#". Return false.
 * Example 3: "9,#,#,1". Return false.
 */
public class Solution {

    public static void main(String[] args) {
        System.out.println(new Solution().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"));
    }

    // 1) non-null node contributes 2 outdegree and 1 indegree (2 children and 1 parent), except root
    // 2) all null node contributes 0 outdegree and 1 indegree (0 child and 1 parent).
    // If a serialization is correct, diff should never be negative and diff will be zero when finished
    public boolean isValidSerialization(String preorder) {
        int diff = 1; // a "virtual" indegree for root
        for (String node : preorder.split(",")) {
            if (--diff < 0) return false;
            if (!"#".equals(node)) diff += 2;
        }
        return diff == 0;
    }

    // 3AC still use stack
    public boolean isValidSerialization_stack(String preorder) {
        String[] tree = preorder.split(",");
        int i = 0, stack = 0;
        for (; i < tree.length - 1; i++) {
            if ("#".equals(tree[i])) {
                if (stack == 0) break;
                stack--;
            } else {
                stack++;
            }
        }
        return stack == 0 && i == tree.length - 1 && "#".equals(tree[i]);
    }

    // Neat and smart solution from dietpepsi!
    // Check if outdegree = indegree along the preorder path
    // which means every subtree must follow that rule
    public boolean isValidSerialization_degree(String preorder) {
        int diff = 1;   // a "virtual" indegree for root
        for (String node : preorder.split(",")) {
            if (--diff < 0) {
                return false;
            }
            diff += "#".equals(node) ? 0 : 2;
        }
        return diff == 0;
    }

    // My 2AC: use a variable stack (or called depth)
    public boolean isValidSerialization2(String preorder) {
        String[] nodes = preorder.split(",");
        int stack = 0, i = 0;
        for (; i < nodes.length; i++) {
            if ("#".equals(nodes[i])) {
                if (stack == 0) {
                    break;
                }
                stack--;
            } else {
                stack++;
            }
        }
        return stack == 0 && i == nodes.length - 1 && "#".equals(nodes[i]);
    }

    // My 1AC: a real stack is overkill here.
    public boolean isValidSerialization1(String preorder) {
        Stack<String> stack = new Stack<>();
        String[] serial = preorder.split(",");

        int i = 0;
        while (i < serial.length && (!stack.isEmpty() || !serial[i].equals("#"))) {
            if (!serial[i].equals("#")) {
                stack.push(serial[i]);
                i++;
            } else { // stack must not be empty
                stack.pop();
                i++;
            }
        }
        // Stack is empty && i points to last && last is "#" => true!
        return (i == serial.length - 1);
    }

}


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>StartupBridge</name>
    </assembly>
    <members>
        <member name="T:StartupBridge.Helper.LocalSettingsAccessor">
            <summary>
            Accessor to LocalSettings
            </summary>
            <remarks>
            Usable value types are almost identical to types shown in:
            https://msdn.microsoft.com/en-us/library/br205768.aspx
            excluding Uri and void but including byte[] and Enum.
            </remarks>
        </member>
        <member name="T:StartupBridge.PlatformInfo">
            <summary>
            Platform information
            </summary>
        </member>
        <member name="P:StartupBridge.PlatformInfo.IsPackaged">
            <summary>
            Whether this assembly is packaged in AppX package
            </summary>
        </member>
        <member name="T:StartupBridge.StartupData">
            <summary>
            Startup data
            </summary>
        </member>
        <member name="P:StartupBridge.StartupData.LastStartTime">
            <summary>
            Last start time of application
            </summary>
            <remarks>The underlying value of this property will be updated when accessed the first time.</remarks>
        </member>
        <member name="T:StartupBridge.StartupTaskBroker">
            <summary>
            StartupTask broker
            </summary>
        </member>
        <member name="M:StartupBridge.StartupTaskBroker.CanEnable(System.String)">
            <summary>
            Whether the startup task for a specified AppX package can be enabled
            </summary>
            <param name="taskId">Id of startup task</param>
            <returns>True if the startup task can be enabled</returns>
        </member>
        <member name="M:StartupBridge.StartupTaskBroker.IsEnabled(System.String)">
            <summary>
            Whether the startup task for a specified AppX package is enabled
            </summary>
            <param name="taskId">Id of startup task</param>
            <returns>True if the startup task is enabled</returns>
        </member>
        <member name="M:StartupBridge.StartupTaskBroker.Enable(System.String)">
            <summary>
            Enables the startup task for a specified AppX package.
            </summary>
            <param name="taskId">Id of startup task</param>
            <returns>True if the startup task is enabled</returns>
        </member>
        <member name="M:StartupBridge.StartupTaskBroker.Disable(System.String)">
            <summary>
            Disables the startup task for a specified AppX package.
            </summary>
            <param name="taskId">Id of startup task</param>
        </member>
    </members>
</doc>


text:
package com.xpfriend.fixture.cast.temp;

import java.text.ParseException;

/**
 * @author Ototadana
 *
 */
public class UnsupportedTypeException extends ParseException {

	private static final long serialVersionUID = 1L;

	public UnsupportedTypeException(Class<?> type) {
		super(type.getName(), 0);
	}

}


text:
package main

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"github.com/thingful/httpmock"

	"google.golang.org/appengine"
	"google.golang.org/appengine/aetest"
	"google.golang.org/appengine/datastore"
	"google.golang.org/appengine/urlfetch"
)

/**
 * 削除イベント:グループ、ルーム(同じ扱いなのでテストはひとつ)
 */
func TestLeaveGroup(t *testing.T) {
	opt := aetest.Options{StronglyConsistentDatastore: true} //データストアに即反映
	instance, err := aetest.NewInstance(&opt)
	if err != nil {
		t.Fatalf("Failed to create aetest instance: %v", err)
	}
	defer instance.Close()

	// 評価する値
	expectedMid := "C00000000000000000000000000000000" //グループなので先頭は"C"
	expectedName := "テストグループ"
	expectedType := "leave"

	// http.Requestを生成
	param := url.Values{
		"mid":  {expectedMid},
		"type": {expectedType},
	}
	req, err := instance.NewRequest("POST", "/task/leave", strings.NewReader(param.Encode()))
	if err != nil {
		t.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded") //必須

	// Contextとhttp.Clientは、テストコード側でインスタンス化する(モックと共通のインスタンスを使う必要があるため)
	ctx := appengine.NewContext(req)
	client := urlfetch.Client(ctx)

	// 削除される購読者エンティティを用意しておく
	entity := subscriber{
		MID:         expectedMid,
		DisplayName: expectedName,
	}
	key := datastore.NewKey(ctx, "Subscriber", expectedMid, 0, nil)
	if _, err = datastore.Put(ctx, key, &entity); err != nil {
		t.Fatal(err)
	}

	// execute
	res := httptest.NewRecorder()
	leaveWithContext(ctx, client, res, req) //モックと同じhttp.Clientインスタンスを渡す

	// リクエストは正常終了していること
	if res.Code != http.StatusOK {
		t.Errorf("Non-expected status code: %v\n\tbody: %v", res.Code, res.Body)
	}

	// データストアの内容を確認(購読者エンティティ)
	subscribers := []subscriber{}
	_, err = datastore.NewQuery("Subscriber").GetAll(ctx, &subscribers)
	if err != nil {
		t.Fatal(err)
	}
	if len(subscribers) != 0 {
		t.Fatal("Subscriber entity is not remove")
	}

	// データストアの内容を確認(ログエンティティ)
	logSubscribers := []logSubscriber{}
	_, err = datastore.NewQuery("LogSubscriber").GetAll(ctx, &logSubscribers)
	if err != nil {
		t.Fatal(err)
	}
	if len(logSubscribers) != 1 {
		t.Fatal("LogSubscriber entity was not put")
	}
	if logSubscribers[0].MID != expectedMid {
		t.Errorf("Invalid posted LogSubscriber entity. MID='%v'", logSubscribers[0].MID)
	}
	if logSubscribers[0].DisplayName != expectedName {
		t.Errorf("Invalid posted LogSubscriber entity. DisplayName='%v'", logSubscribers[0].DisplayName)
	}
	if logSubscribers[0].EventType != expectedType {
		t.Errorf("Invalid posted LogSubscriber entity. EventType='%v'", logSubscribers[0].EventType)
	}
}

/**
 * 削除イベント:ユーザ
 */
func TestLeaveUser(t *testing.T) {
	opt := aetest.Options{StronglyConsistentDatastore: true} //データストアに即反映
	instance, err := aetest.NewInstance(&opt)
	if err != nil {
		t.Fatalf("Failed to create aetest instance: %v", err)
	}
	defer instance.Close()

	// 評価する値
	expectedMid := "U00000000000000000000000000000000" //ユーザなので先頭は"U"
	expectedName := "LINE taro"
	expectedType := "unfollow"

	// http.Requestを生成
	param := url.Values{
		"mid":  {expectedMid},
		"type": {expectedType},
	}
	req, err := instance.NewRequest("POST", "/task/leave", strings.NewReader(param.Encode()))
	if err != nil {
		t.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded") //必須

	// Contextとhttp.Clientは、テストコード側でインスタンス化する(モックと共通のインスタンスを使う必要があるため)
	ctx := appengine.NewContext(req)
	client := urlfetch.Client(ctx)

	// 外部アクセスはないはずだが、抑止のためにhttpmockを有効化
	httpmock.ActivateNonDefault(client)
	defer httpmock.DeactivateAndReset()

	// 削除される購読者エンティティを用意しておく
	entity := subscriber{
		MID:         expectedMid,
		DisplayName: expectedName,
	}
	key := datastore.NewKey(ctx, "Subscriber", expectedMid, 0, nil)
	if _, err = datastore.Put(ctx, key, &entity); err != nil {
		t.Fatal(err)
	}

	// execute
	res := httptest.NewRecorder()
	leaveWithContext(ctx, client, res, req) //モックと同じhttp.Clientインスタンスを渡す

	// リクエストは正常終了していること
	if res.Code != http.StatusOK {
		t.Errorf("Non-expected status code: %v\n\tbody: %v", res.Code, res.Body)
	}

	// スタブがすべて呼ばれたことを検証
	if err = httpmock.AllStubsCalled(); err != nil {
		t.Errorf("Not all stubs were called: %s", err)
	}

	// データストアの内容を確認(購読者エンティティ)
	subscribers := []subscriber{}
	_, err = datastore.NewQuery("Subscriber").GetAll(ctx, &subscribers)
	if err != nil {
		t.Fatal(err)
	}
	if len(subscribers) != 0 {
		t.Errorf("Subscriber entity is not remove")
	}

	// データストアの内容を確認(ログエンティティ)
	logSubscribers := []logSubscriber{}
	_, err = datastore.NewQuery("LogSubscriber").GetAll(ctx, &logSubscribers)
	if err != nil {
		t.Fatal(err)
	}
	if len(logSubscribers) != 1 {
		t.Fatal("LogSubscriber entity was not put")
	}
	if logSubscribers[0].MID != expectedMid {
		t.Errorf("Invalid posted LogSubscriber entity. MID='%v'", logSubscribers[0].MID)
	}
	if logSubscribers[0].DisplayName != expectedName {
		t.Errorf("Invalid posted LogSubscriber entity. DisplayName='%v'", logSubscribers[0].DisplayName)
	}
	if logSubscribers[0].EventType != expectedType {
		t.Errorf("Invalid posted LogSubscriber entity. EventType='%v'", logSubscribers[0].EventType)
	}
}


text:
using J2N.Threading;
using J2N.Threading.Atomic;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;

namespace Lucene.Net.Search.Spell
{

    /// <summary>
    /// Spell checker test case
    /// </summary>
    public class TestSpellChecker : LuceneTestCase
    {
        private SpellCheckerMock spellChecker;
        private Directory userindex, spellindex;
        internal static ConcurrentBag<IndexSearcher> searchers;

        public override void SetUp()
        {
            base.SetUp();

            //create a user index
            userindex = NewDirectory();
            IndexWriter writer = new IndexWriter(userindex, new IndexWriterConfig(
                TEST_VERSION_CURRENT, new MockAnalyzer(Random)));

            for (int i = 0; i < 1000; i++)
            {
                Document doc = new Document();
                doc.Add(NewTextField("field1", English.Int32ToEnglish(i), Field.Store.YES));
                doc.Add(NewTextField("field2", English.Int32ToEnglish(i + 1), Field.Store.YES)); // + word thousand
                doc.Add(NewTextField("field3", "fvei" + (i % 2 == 0 ? " five" : ""), Field.Store.YES)); // + word thousand
                writer.AddDocument(doc);
            }
            {
                Document doc = new Document();
                doc.Add(NewTextField("field1", "eight", Field.Store.YES)); // "eight" in
                                                                           // the index
                                                                           // twice
                writer.AddDocument(doc);
            }
            {
                Document doc = new Document();
                doc
                    .Add(NewTextField("field1", "twenty-one twenty-one", Field.Store.YES)); // "twenty-one" in the index thrice
                writer.AddDocument(doc);
            }
            {
                Document doc = new Document();
                doc.Add(NewTextField("field1", "twenty", Field.Store.YES)); // "twenty"
                                                                            // in the
                                                                            // index
                                                                            // twice
                writer.AddDocument(doc);
            }

            writer.Dispose();
            searchers = new ConcurrentBag<IndexSearcher>();
            // create the spellChecker
            spellindex = NewDirectory();
            spellChecker = new SpellCheckerMock(spellindex);
        }

        public override void TearDown()
        {
            userindex.Dispose();
            if (!spellChecker.IsDisposed)
                spellChecker.Dispose();
            spellindex.Dispose();
            base.TearDown();
        }

        [Test]
        public void TestBuild()
        {
            using (IndexReader r = DirectoryReader.Open(userindex))
            {
                spellChecker.ClearIndex();

                Addwords(r, spellChecker, "field1");
                int num_field1 = this.NumDoc();

                Addwords(r, spellChecker, "field2");
                int num_field2 = this.NumDoc();

                assertEquals(num_field2, num_field1 + 1);

                AssertLastSearcherOpen(4);

                CheckCommonSuggestions(r);
                CheckLevenshteinSuggestions(r);

                spellChecker.StringDistance = (new JaroWinklerDistance());
                spellChecker.Accuracy = (0.8f);
                CheckCommonSuggestions(r);
                CheckJaroWinklerSuggestions();
                // the accuracy is set to 0.8 by default, but the best result has a score of 0.925
                string[] similar = spellChecker.SuggestSimilar("fvie", 2, 0.93f);
                assertTrue(similar.Length == 0);
                similar = spellChecker.SuggestSimilar("fvie", 2, 0.92f);
                assertTrue(similar.Length == 1);

                similar = spellChecker.SuggestSimilar("fiv", 2);
                assertTrue(similar.Length > 0);
                assertEquals(similar[0], "five");

                spellChecker.StringDistance = (new NGramDistance(2));
                spellChecker.Accuracy = (0.5f);
                CheckCommonSuggestions(r);
                CheckNGramSuggestions();

            }
        }

        [Test]
        public void TestComparer()
        {
            using (Directory compIdx = NewDirectory())
            {
                SpellChecker compareSP = new SpellCheckerMock(compIdx, new LevensteinDistance(), new SuggestWordFrequencyComparer());
                try
                {
                    using (IndexReader r = DirectoryReader.Open(userindex))
                    {

                        Addwords(r, compareSP, "field3");

                        string[] similar = compareSP.SuggestSimilar("fvie", 2, r, "field3",
                            SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
                        assertTrue(similar.Length == 2);
                        //five and fvei have the same score, but different frequencies.
                        assertEquals("fvei", similar[0]);
                        assertEquals("five", similar[1]);
                    }
                }
                finally
                {
                    if (!compareSP.IsDisposed)
                        compareSP.Dispose();
                }
            }
        }

        [Test]
        public void TestBogusField()
        {
            using (Directory compIdx = NewDirectory())
            {
                SpellChecker compareSP = new SpellCheckerMock(compIdx, new LevensteinDistance(), new SuggestWordFrequencyComparer());
                try
                {
                    using (IndexReader r = DirectoryReader.Open(userindex))
                    {

                        Addwords(r, compareSP, "field3");

                        string[] similar = compareSP.SuggestSimilar("fvie", 2, r,
                            "bogusFieldBogusField", SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
                        assertEquals(0, similar.Length);
                    }
                }
                finally
                {
                    if (!compareSP.IsDisposed)
                        compareSP.Dispose();
                }
            }
        }

        [Test]
        public void TestSuggestModes()
        {
            using (IndexReader r = DirectoryReader.Open(userindex))
            {
                spellChecker.ClearIndex();
                Addwords(r, spellChecker, "field1");

                {
                    string[] similar = spellChecker.SuggestSimilar("eighty", 2, r, "field1",
                        SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
                    assertEquals(1, similar.Length);
                    assertEquals("eighty", similar[0]);
                }

                {
                    string[] similar = spellChecker.SuggestSimilar("eight", 2, r, "field1",
                        SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
                    assertEquals(1, similar.Length);
                    assertEquals("eight", similar[0]);
                }

                {
                    string[] similar = spellChecker.SuggestSimilar("eighty", 5, r, "field1",
                        SuggestMode.SUGGEST_MORE_POPULAR);
                    assertEquals(5, similar.Length);
                    assertEquals("eight", similar[0]);
                }

                {
                    string[] similar = spellChecker.SuggestSimilar("twenty", 5, r, "field1",
                        SuggestMode.SUGGEST_MORE_POPULAR);
                    assertEquals(1, similar.Length);
                    assertEquals("twenty-one", similar[0]);
                }

                {
                    string[] similar = spellChecker.SuggestSimilar("eight", 5, r, "field1",
                        SuggestMode.SUGGEST_MORE_POPULAR);
                    assertEquals(0, similar.Length);
                }

                {
                    string[] similar = spellChecker.SuggestSimilar("eighty", 5, r, "field1",
                        SuggestMode.SUGGEST_ALWAYS);
                    assertEquals(5, similar.Length);
                    assertEquals("eight", similar[0]);
                }

                {
                    string[] similar = spellChecker.SuggestSimilar("eight", 5, r, "field1",
                        SuggestMode.SUGGEST_ALWAYS);
                    assertEquals(5, similar.Length);
                    assertEquals("eighty", similar[0]);
                }
            }
        }
        private void CheckCommonSuggestions(IndexReader r)
        {
            string[]
            similar = spellChecker.SuggestSimilar("fvie", 2);
            assertTrue(similar.Length > 0);
            assertEquals(similar[0], "five");

            similar = spellChecker.SuggestSimilar("five", 2);
            if (similar.Length > 0)
            {
                assertFalse(similar[0].Equals("five", StringComparison.Ordinal)); // don't suggest a word for itself
            }

            similar = spellChecker.SuggestSimilar("fiv", 2);
            assertTrue(similar.Length > 0);
            assertEquals(similar[0], "five");

            similar = spellChecker.SuggestSimilar("fives", 2);
            assertTrue(similar.Length > 0);
            assertEquals(similar[0], "five");

            assertTrue(similar.Length > 0);
            similar = spellChecker.SuggestSimilar("fie", 2);
            assertEquals(similar[0], "five");

            //  test restraint to a field
            similar = spellChecker.SuggestSimilar("tousand", 10, r, "field1",
                SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
            assertEquals(0, similar.Length); // there isn't the term thousand in the field field1

            similar = spellChecker.SuggestSimilar("tousand", 10, r, "field2",
                SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
            assertEquals(1, similar.Length); // there is the term thousand in the field field2
        }

        private void CheckLevenshteinSuggestions(IndexReader r)
        {
            // test small word
            string[]
            similar = spellChecker.SuggestSimilar("fvie", 2);
            assertEquals(1, similar.Length);
            assertEquals(similar[0], "five");

            similar = spellChecker.SuggestSimilar("five", 2);
            assertEquals(1, similar.Length);
            assertEquals(similar[0], "nine");     // don't suggest a word for itself

            similar = spellChecker.SuggestSimilar("fiv", 2);
            assertEquals(1, similar.Length);
            assertEquals(similar[0], "five");

            similar = spellChecker.SuggestSimilar("ive", 2);
            assertEquals(2, similar.Length);
            assertEquals(similar[0], "five");
            assertEquals(similar[1], "nine");

            similar = spellChecker.SuggestSimilar("fives", 2);
            assertEquals(1, similar.Length);
            assertEquals(similar[0], "five");

            similar = spellChecker.SuggestSimilar("fie", 2);
            assertEquals(2, similar.Length);
            assertEquals(similar[0], "five");
            assertEquals(similar[1], "nine");

            similar = spellChecker.SuggestSimilar("fi", 2);
            assertEquals(1, similar.Length);
            assertEquals(similar[0], "five");

            // test restraint to a field
            similar = spellChecker.SuggestSimilar("tousand", 10, r, "field1",
                SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
            assertEquals(0, similar.Length); // there isn't the term thousand in the field field1

            similar = spellChecker.SuggestSimilar("tousand", 10, r, "field2",
                SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
            assertEquals(1, similar.Length); // there is the term thousand in the field field2

            similar = spellChecker.SuggestSimilar("onety", 2);
            assertEquals(2, similar.Length);
            assertEquals(similar[0], "ninety");
            assertEquals(similar[1], "one");
            try
            {
                similar = spellChecker.SuggestSimilar("tousand", 10, r, null,
                    SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);
            }
            catch (NullReferenceException /*e*/)
            {
                assertTrue("threw an NPE, and it shouldn't have", false);
            }
        }

        private void CheckJaroWinklerSuggestions()
        {
            string[]
            similar = spellChecker.SuggestSimilar("onety", 2);
            assertEquals(2, similar.Length);
            assertEquals(similar[0], "one");
            assertEquals(similar[1], "ninety");
        }

        private void CheckNGramSuggestions()
        {
            string[]
            similar = spellChecker.SuggestSimilar("onety", 2);
            assertEquals(2, similar.Length);
            assertEquals(similar[0], "one");
            assertEquals(similar[1], "ninety");
        }

        private void Addwords(IndexReader r, SpellChecker sc, string field)
        {
            long time = Environment.TickCount;
            sc.IndexDictionary(new LuceneDictionary(r, field), NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false);
            time = Environment.TickCount - time;
            //System.out.println("time to build " + field + ": " + time);
        }

        private int NumDoc()
        {
            IndexReader rs = DirectoryReader.Open(spellindex);
            int num = rs.NumDocs;
            assertTrue(num != 0);
            //System.out.println("num docs: " + num);
            rs.Dispose();
            return num;
        }

        [Test]
        public void TestClose()
        {
            using (IndexReader r = DirectoryReader.Open(userindex))
            {
                spellChecker.ClearIndex();
                string field = "field1";
                Addwords(r, spellChecker, "field1");
                int num_field1 = this.NumDoc();
                Addwords(r, spellChecker, "field2");
                int num_field2 = this.NumDoc();
                assertEquals(num_field2, num_field1 + 1);
                CheckCommonSuggestions(r);
                AssertLastSearcherOpen(4);
                spellChecker.Dispose();
                AssertSearchersClosed();
                // LUCENENET NOTE: Per MSDN, calling Dispose() multiple times
                // should be a safe operation. http://stackoverflow.com/a/5306896/181087
                // Certainly, there shouldn't be a problem with calling Dispose() within
                // a using block if you decide to free up resources early.
                //try
                //{
                //    spellChecker.Dispose();
                //    fail("spellchecker was already closed");
                //}
                //catch (ObjectDisposedException e)
                //{
                //    // expected
                //}
                try
                {
                    CheckCommonSuggestions(r);
                    fail("spellchecker was already closed");
                }
                catch (ObjectDisposedException /*e*/)
                {
                    // expected
                }

                try
                {
                    spellChecker.ClearIndex();
                    fail("spellchecker was already closed");
                }
                catch (ObjectDisposedException /*e*/)
                {
                    // expected
                }

                try
                {
                    spellChecker.IndexDictionary(new LuceneDictionary(r, field), NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false);
                    fail("spellchecker was already closed");
                }
                catch (ObjectDisposedException /*e*/)
                {
                    // expected
                }

                try
                {
                    spellChecker.SetSpellIndex(spellindex);
                    fail("spellchecker was already closed");
                }
                catch (ObjectDisposedException /*e*/)
                {
                    // expected
                }
                assertEquals(4, searchers.Count);
                AssertSearchersClosed();
            }
        }

        /*
         * tests if the internally shared indexsearcher is correctly closed
         * when the spellchecker is concurrently accessed and closed.
         */
        [Test]
        public void TestConcurrentAccess()
        {
            assertEquals(1, searchers.Count);
            using (IndexReader r = DirectoryReader.Open(userindex))
            {
                spellChecker.ClearIndex();
                assertEquals(2, searchers.Count);
                Addwords(r, spellChecker, "field1");
                assertEquals(3, searchers.Count);
                int num_field1 = this.NumDoc();
                Addwords(r, spellChecker, "field2");
                assertEquals(4, searchers.Count);
                int num_field2 = this.NumDoc();
                assertEquals(num_field2, num_field1 + 1);
                int numThreads = 5 + Random.nextInt(5);
                SpellCheckWorker[] workers = new SpellCheckWorker[numThreads];
                var stop = new AtomicBoolean(false);
                for (int i = 0; i < numThreads; i++)
                {
                    SpellCheckWorker spellCheckWorker = new SpellCheckWorker(this, r, stop);
                    workers[i] = spellCheckWorker;
                    spellCheckWorker.Start();
                }
                int iterations = 5 + Random.nextInt(5);
                for (int i = 0; i < iterations; i++)
                {
                    Thread.Sleep(100);
                    // concurrently reset the spell index
                    spellChecker.SetSpellIndex(this.spellindex);
                    // for debug - prints the internal open searchers
                    // showSearchersOpen();
                }

                spellChecker.Dispose();
                stop.Value = true;

                // wait for 60 seconds - usually this is very fast but coverage runs could take quite long
                //executor.awaitTermination(60L, TimeUnit.SECONDS);
                foreach (SpellCheckWorker worker in workers)
                {
                    worker.Join((long)TimeSpan.FromSeconds(60).TotalMilliseconds);
                }

                for (int i = 0; i < workers.Length; i++)
                {
                    assertFalse(string.Format(CultureInfo.InvariantCulture, "worker thread {0} failed \n" + workers[i].Error, i), workers[i].Error != null);
                    assertTrue(string.Format(CultureInfo.InvariantCulture, "worker thread {0} is still running but should be terminated", i), workers[i].terminated);
                }
                // 4 searchers more than iterations
                // 1. at creation
                // 2. clearIndex()
                // 2. and 3. during addwords
                assertEquals(iterations + 4, searchers.Count);
                AssertSearchersClosed();
            }
        }

        private void AssertLastSearcherOpen(int numSearchers)
        {
            assertEquals(numSearchers, searchers.Count);

            // LUCENENET NOTE: The ConcurrentBag.Add() method adds each item to the
            // beginning of the list, so we end up with a reverse order array.
            // We can correct that here, since this is the only part of the
            // test that cares about the order.
            IndexSearcher[] searcherArray = searchers.Reverse().ToArray();

            for (int i = 0; i < searcherArray.Length; i++)
            {
                if (i == searcherArray.Length - 1)
                {
                    assertTrue("expected last searcher open but was closed",
                        searcherArray[i].IndexReader.RefCount > 0);
                }
                else
                {
                    assertFalse("expected closed searcher but was open - Index: " + i,
                        searcherArray[i].IndexReader.RefCount > 0);
                }
            }
        }

        private void AssertSearchersClosed()
        {
            foreach (IndexSearcher searcher in searchers)
            {
                assertEquals(0, searcher.IndexReader.RefCount);
            }
        }

        // For debug
        //  private void showSearchersOpen() {
        //    int count = 0;
        //    for (IndexSearcher searcher : searchers) {
        //      if(searcher.getIndexReader().getRefCount() > 0)
        //        ++count;
        //    }
        //    System.out.println(count);
        //  }

        private class SpellCheckWorker : ThreadJob
        {
            private readonly TestSpellChecker outerInstance;

            private readonly IndexReader reader;
            private readonly AtomicBoolean stop;
            private volatile Exception error;
            internal volatile bool terminated = false;

            public SpellCheckWorker(TestSpellChecker outerInstance, IndexReader reader, AtomicBoolean stop)
            {
                this.outerInstance = outerInstance;
                this.reader = reader;
                this.stop = stop;
            }

            public Exception Error => error;

            public override void Run()
            {
#if FEATURE_THREAD_PRIORITY
                Priority += 1;
#endif
                try
                {
                    while (!stop)
                    {
                        try
                        {
                            outerInstance.CheckCommonSuggestions(reader);

                            Thread.Sleep(10);// don't starve refresh()'s CPU, which sleeps every 50 bytes for 1 ms
                        }
                        catch (ObjectDisposedException /*e*/)
                        {
                            return;
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            error = e;
                            return;
                        }
                    }
                }
                finally
                {
                    terminated = true;
                }
            }
        }

        /// <summary>
        /// Grab the stack trace into a string since the exception was thrown in a thread and we want the assert
        /// outside the thread to show the stack trace in case of failure.
        /// </summary>
        private string stackTraceStr(Exception error)
        {
            if (error == null)
            {
                return "";
            }

            error.printStackTrace();
            return error.StackTrace;
        }

        internal class SpellCheckerMock : SpellChecker
        {
            public SpellCheckerMock(Directory spellIndex)
                : base(spellIndex)
            {
            }

            public SpellCheckerMock(Directory spellIndex, IStringDistance sd)
                    : base(spellIndex, sd)
            {
            }

            public SpellCheckerMock(Directory spellIndex, IStringDistance sd, IComparer<SuggestWord> comparer)
                    : base(spellIndex, sd, comparer)
            {
            }

            internal override IndexSearcher CreateSearcher(Directory dir)
            {
                IndexSearcher searcher = base.CreateSearcher(dir);
                TestSpellChecker.searchers.Add(searcher);
                return searcher;
            }
        }
    }
}


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("@uifabric/utilities/lib/index"));

//# sourceMappingURL=Utilities.js.map


text:
var _ = require('underscore'),
	request = require('request');

// fetching Google Translate
// http://translate.google.com
var url = 'http://translate.google.cn/translate_a/t',
	base = {
		client: 't',
		hl: 'en',
		sc: 2,
		ie: 'UTF-8',
		oe: 'UTF-8',
		oc: 1,
		otf: 2,
		rom: 1,
		ssel: 5,
		tsel: 5
	};

exports.create = function(options) {
	return new Translator().defaults(options);
}

function Translator() {
	this._defaults = {
		sl: 'en', // source language
		tl: 'zh-CN' // target language
	};
}
Translator.prototype.defaults = function(_options) {
	// pick `from / to` for `sl / tl`
	var options = {};
	if (_options.from) options.sl = _options.from;
	if (_options.to) options.tl = _options.to;
	_.extend(this._defaults, options);
	return this;
}

// .get(text, [options], callback)
// options: from, to
Translator.prototype.get = function(text, options, callback) {
	// overload method
	if (_.isFunction(options)) {
		callback = options;
		options = null;
	}

	var params = _.extend({
		q: text
	}, base, this._defaults, options);

	request(url, {
		qs: params
	}, function(err, res, body) {
		if (err) {
			return callback(err);
		}
		var result;

		// replace `,+` to `,`
		// amazing trap made by Google
		body = body.replace(/(\s*,\s*)+/g, ',');

		try {
			var arr = JSON.parse(body);
			// get the key we need
			result = arr[0][0][0];
		} catch (err) {
			return callback(new Error('can not parse the result'));
		}
		callback(null, result || '');
	});

	return this;
}


text:
/****************************
 * Request 'get tree' [GET]. Returns a module dependency tree in JSON form.
 *
 * @author GlaDos
 * @since 09.09.17
 ****************************/

"use strict";

/***
 * Imports.
 */
const
	constants   = require("../../global/constants"),
	nodeStorage = require("../../storage/nodeStorage");

/***
 * Constants.
 */
const
	TEXT_PLAIN               = constants.TEXT_PLAIN,
	STATUS_CODE_OK           = constants.STATUS_CODE_OK,
	STATUS_CODE_BAD_REQUEST  = constants.STATUS_CODE_BAD_REQUEST,
	URL_PARAM_MODULE_SUBJECT = "subject";

/**
 * The request itself. Returns a node tree packed in JSON.
 *
 * @param {function(int, string, string)} response reply inject function to put request answer in
 * @param {dictionary} params url parameters
 * @return {null} nothing
 */
const getTree = (response, params) => {
	const moduleSubject = params[URL_PARAM_MODULE_SUBJECT];

	if (nodeStorage.containsNode(moduleSubject))
		response(STATUS_CODE_OK, TEXT_PLAIN, nodeStorage.getTree(params[URL_PARAM_MODULE_SUBJECT]).extractJSON());
	else
		response(STATUS_CODE_BAD_REQUEST, TEXT_PLAIN, `No module with subject "${moduleSubject}" found`);
};

/**
 * Exports.
 */
exports = module.exports = getTree;


text:
package com.sun.tools.ws.wsdl.parser;

import com.sun.tools.ws.api.wsdl.TWSDLExtensible;
import com.sun.tools.ws.api.wsdl.TWSDLParserContext;
import com.sun.tools.ws.resources.ModelerMessages;
import com.sun.tools.ws.resources.WsdlMessages;
import com.sun.tools.ws.util.xml.XmlUtil;
import com.sun.tools.ws.wscompile.ErrorReceiver;
import com.sun.tools.ws.wsdl.document.Fault;
import com.sun.tools.ws.wsdl.document.Input;
import com.sun.tools.ws.wsdl.document.Output;
import com.sun.xml.ws.addressing.W3CAddressingMetadataConstants;
import com.sun.xml.ws.addressing.v200408.MemberSubmissionAddressingConstants;
import com.sun.xml.ws.api.addressing.AddressingVersion;
import org.w3c.dom.Element;
import org.xml.sax.Locator;

import javax.xml.namespace.QName;
import java.util.Map;

/**
 * @author Arun Gupta
 */
public class MemberSubmissionAddressingExtensionHandler extends W3CAddressingExtensionHandler {

    private ErrorReceiver errReceiver;
    private boolean extensionModeOn;

    public MemberSubmissionAddressingExtensionHandler(Map<String, AbstractExtensionHandler> extensionHandlerMap, ErrorReceiver env, boolean extensionModeOn) {
        super(extensionHandlerMap, env);
        this.errReceiver = env;
        this.extensionModeOn = extensionModeOn;
    }

    @Override
    public String getNamespaceURI() {
        return AddressingVersion.MEMBER.wsdlNsUri;
    }

    @Override
    protected QName getWSDLExtensionQName() {
        return AddressingVersion.MEMBER.wsdlExtensionTag;
    }

    @Override
    @SuppressWarnings({"deprecation"})
    public boolean handlePortExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
        // ignore any extension elements
        return false;
    }

    @Override
    @SuppressWarnings({"deprecation"})
    public boolean handleInputExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
        if (extensionModeOn) {
            warn(context.getLocation(e));
            String actionValue = XmlUtil.getAttributeNSOrNull(e, MemberSubmissionAddressingConstants.WSA_ACTION_QNAME);
            if (actionValue == null || actionValue.equals("")) {
                return warnEmptyAction(parent, context.getLocation(e));
            }
            ((Input) parent).setAction(actionValue);
            return true;
        } else {
            return fail(context.getLocation(e));
        }
    }

    private boolean fail(Locator location) {
        errReceiver.warning(location,
                ModelerMessages.WSDLMODELER_INVALID_IGNORING_MEMBER_SUBMISSION_ADDRESSING(
                        AddressingVersion.MEMBER.nsUri, W3CAddressingMetadataConstants.WSAM_NAMESPACE_NAME));
        return false;
    }

    private void warn(Locator location) {
        errReceiver.warning(location,
                ModelerMessages.WSDLMODELER_WARNING_MEMBER_SUBMISSION_ADDRESSING_USED(
                        AddressingVersion.MEMBER.nsUri, W3CAddressingMetadataConstants.WSAM_NAMESPACE_NAME));
    }

    @Override
    @SuppressWarnings({"deprecation"})
    public boolean handleOutputExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
        if (extensionModeOn) {
            warn(context.getLocation(e));
            String actionValue = XmlUtil.getAttributeNSOrNull(e, MemberSubmissionAddressingConstants.WSA_ACTION_QNAME);
            if (actionValue == null || actionValue.equals("")) {
                return warnEmptyAction(parent, context.getLocation(e));
            }
            ((Output) parent).setAction(actionValue);
            return true;
        } else {
            return fail(context.getLocation(e));
        }
    }

    @Override
    @SuppressWarnings({"deprecation"})
    public boolean handleFaultExtension(TWSDLParserContext context, TWSDLExtensible parent, Element e) {
        if (extensionModeOn) {
            warn(context.getLocation(e));
            String actionValue = XmlUtil.getAttributeNSOrNull(e, MemberSubmissionAddressingConstants.WSA_ACTION_QNAME);
            if (actionValue == null || actionValue.equals("")) {
                errReceiver.warning(context.getLocation(e), WsdlMessages.WARNING_FAULT_EMPTY_ACTION(parent.getNameValue(), parent.getWSDLElementName().getLocalPart(), parent.getParent().getNameValue()));
                return false; // keep compiler happy
            }
            ((Fault) parent).setAction(actionValue);
            return true;
        } else {
            return fail(context.getLocation(e));
        }
    }

    @SuppressWarnings({"deprecation"})
    private boolean warnEmptyAction(TWSDLExtensible parent, Locator pos) {
        errReceiver.warning(pos, WsdlMessages.WARNING_INPUT_OUTPUT_EMPTY_ACTION(parent.getWSDLElementName().getLocalPart(), parent.getParent().getNameValue()));
        return false;
    }
}


text:
package com.brajagopal.rmend.data.beans;

import org.apache.commons.collections4.MapUtils;

import java.util.Map;

/**
 * @author <bxr4261>
 */
public class RelationsBean extends BaseContent {

    private String careerType;
    private String status;

    public RelationsBean() {
        this(ContentType.DISCARDED);
    }

    private RelationsBean(ContentType _contentType) {
        super(_contentType);
    }

    @Override
    public void process(Map<String, ? extends Object> _value) {
        this.type = MapUtils.getString(_value, "_type", null);
        this.forEndUserDisplay = MapUtils.getBoolean(_value, "forenduserdisplay", false);
        this.careerType = MapUtils.getString(_value, "careertype", null);
        this.status = MapUtils.getString(_value, "status", null);
    }

    @Override
    public BaseContent getInstance() {
        return new RelationsBean();
    }

    @Override
    public double getScore() {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return "RelationsBean {" +
                "contentType=" + getContentType() +
                ", type='" + getType() + '\'' +
                ", forEndUserDisplay=" + isForEndUserDisplay() +
                ", careerType='" + getCareerType() + '\'' +
                ", status='" + getStatus() + '\'' +
                '}';
    }

    @Override
    public String getName() {
        throw new UnsupportedOperationException("getName() not supported by "+getClass());
    }

    public String getCareerType() {
        return careerType;
    }

    public String getStatus() {
        return status;
    }
}


text:
/** @jsx React.DOM */

var React = require("react/addons");
var TestUtils = React.addons.TestUtils;
var TakeSurveyItem = require("../../../../client/app/components/take_survey_item");

var renderElem = function(props) {
  var view = TakeSurveyItem(props);
  return TestUtils.renderIntoDocument(view);
};

describe("Survey", function(){

  var elem = null;
  var props = {
    item: {
      type: "yes_no",
      meta: {
        label: "Label",
        value: null
      }
    }
  };

  describe("rendering", function() {
    beforeEach(function() {
      elem = renderElem(props);
    });

    it("should render", function(){
      expect(TestUtils.isCompositeComponent(elem)).toBe(true);
      var found = TestUtils.findRenderedDOMComponentWithClass(elem, 'survey-item');
      expect(found).toNotBe(null);
    });
  });

  describe("user input", function() {

    var callbacks = {};
    var props = {};
    var id = "123";

    beforeEach(function() {
      callbacks = {
        onCompleted: function() {}
      };
      spyOn(callbacks, "onCompleted");

      props.onCompleted = callbacks.onCompleted;
      props.item = {
        id: id,
        type: "yes_no",
        meta: {
          label: "label",
          value: null
        }
      };

      elem = renderElem(props);
    });

    afterEach(function() {
      callbacks = {};
      props = {};
    });

    it("responds to user input", function() {
      var value = "Yes";
      elem.handleItemCompleted(value);
      expect(callbacks.onCompleted).toHaveBeenCalledWith(jasmine.objectContaining({
        id: id,
        value: value
      }));
    });
  });
});


text:
package org.nkjmlab.twitter.model;

import java.util.Date;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import net.sf.persist.annotations.Column;
import net.sf.persist.annotations.Table;
import twitter4j.Query;

@Table(name = QueryLog.TABLE_NAME)
public class QueryLog {

	public static final String TABLE_NAME = "QUERY";
	private long id;
	private Date created;
	private String tableName;
	private Long tweetId;
	private String query;
	private long maxId;
	private long sinceId;
	private String since;
	private String until;

	public QueryLog(Query query, String tableName, Long tweetId) {
		this.tableName = tableName;
		this.tweetId = tweetId;
		this.query = query.getQuery();
		this.maxId = query.getMaxId();
		this.since = query.getSince();
		this.sinceId = query.getSinceId();
		this.until = query.getUntil();
	}

	public static String getSchema() {
		return TABLE_NAME + "(id bigint primary key auto_increment, "
				+ "created TIMESTAMP AS CURRENT_TIMESTAMP NOT NULL, " + "table_name varchar, "
				+ "tweet_id bigint,"
				+ "query varchar, " + "max_id bigint, " + "since_id bigint, "
				+ "since varchar, " + "until varchar)";
	}

	@Column(autoGenerated = true)
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

	public long getMaxId() {
		return maxId;
	}

	public void setMaxId(long maxId) {
		this.maxId = maxId;
	}

	public Long getTweetId() {
		return tweetId;
	}

	public void setTweetId(Long tweetId) {
		this.tweetId = tweetId;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public String getSince() {
		return since;
	}

	public void setSince(String since) {
		this.since = since;
	}

	public long getSinceId() {
		return sinceId;
	}

	public void setSinceId(long sinceId) {
		this.sinceId = sinceId;
	}

	public String getUntil() {
		return until;
	}

	public void setUntil(String until) {
		this.until = until;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}


text:
package org.apache.sshd.netty;

import java.util.Objects;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoConnector;
import org.apache.sshd.common.io.IoHandler;
import org.apache.sshd.common.io.IoServiceEventListener;
import org.apache.sshd.common.io.IoServiceFactory;
import org.apache.sshd.common.util.closeable.AbstractCloseable;

/**
 * @author Julien Viet
 * @author Apache MINA SSHD Project
 */
public class NettyIoServiceFactory extends AbstractCloseable implements IoServiceFactory {

    protected final EventLoopGroup eventLoopGroup;
    protected final boolean closeEventLoopGroup;
    protected final FactoryManager manager;

    private IoServiceEventListener eventListener;

    public NettyIoServiceFactory(FactoryManager manager) {
        this(manager, null);
    }

    public NettyIoServiceFactory(FactoryManager manager, EventLoopGroup group) {
        this.manager = Objects.requireNonNull(manager, "FactoryManager must be set");
        this.eventLoopGroup = (group != null) ? group : new NioEventLoopGroup();
        this.closeEventLoopGroup = group == null;
    }

    @Override
    public IoServiceEventListener getIoServiceEventListener() {
        return eventListener;
    }

    @Override
    public void setIoServiceEventListener(IoServiceEventListener listener) {
        eventListener = listener;
    }

    @Override
    public IoConnector createConnector(IoHandler handler) {
        return new NettyIoConnector(this, handler);
    }

    @Override
    public IoAcceptor createAcceptor(IoHandler handler) {
        return new NettyIoAcceptor(this, handler);
    }

    @Override
    protected CloseFuture doCloseGracefully() {
        if (closeEventLoopGroup) {
            Future<?> shutdownFuture = eventLoopGroup.shutdownGracefully();
            shutdownFuture.addListener(fut -> closeFuture.setClosed());
        } else {
            closeFuture.setClosed();
        }
        return closeFuture;
    }

    @Override
    protected void doCloseImmediately() {
        doCloseGracefully();
        super.doCloseImmediately();
    }
}


text:
@implementation NSImage (MGCropExtensions)

- (void)drawInRect:(NSRect)dstRect operation:(NSCompositingOperation)op fraction:(float)delta method:(MGImageResizingMethod)resizeMethod
{
	float sourceWidth = [self size].width;
    float sourceHeight = [self size].height;
    float targetWidth = dstRect.size.width;
    float targetHeight = dstRect.size.height;
    BOOL cropping = !(resizeMethod == MGImageResizeScale);

    // Calculate aspect ratios
    float sourceRatio = sourceWidth / sourceHeight;
    float targetRatio = targetWidth / targetHeight;

    // Determine what side of the source image to use for proportional scaling
    BOOL scaleWidth = (sourceRatio <= targetRatio);
    // Deal with the case of just scaling proportionally to fit, without cropping
    scaleWidth = (cropping) ? scaleWidth : !scaleWidth;

    // Proportionally scale source image
    float scalingFactor, scaledWidth, scaledHeight;
    if (scaleWidth) {
        scalingFactor = 1.0 / sourceRatio;
        scaledWidth = targetWidth;
        scaledHeight = round(targetWidth * scalingFactor);
    } else {
        scalingFactor = sourceRatio;
        scaledWidth = round(targetHeight * scalingFactor);
        scaledHeight = targetHeight;
    }
    float scaleFactor = scaledHeight / sourceHeight;

    // Calculate compositing rectangles
    NSRect sourceRect;
    if (cropping) {
        float destX = 0, destY = 0;
        if (resizeMethod == MGImageResizeCrop) {
            // Crop center
            destX = round((scaledWidth - targetWidth) / 2.0);
            destY = round((scaledHeight - targetHeight) / 2.0);
        } else if (resizeMethod == MGImageResizeCropStart) {
            // Crop top or left (prefer top)
            if (scaleWidth) {
				// Crop top
				destX = round((scaledWidth - targetWidth) / 2.0);
				destY = round(scaledHeight - targetHeight);
            } else {
				// Crop left
                destX = 0.0;
				destY = round((scaledHeight - targetHeight) / 2.0);
            }
        } else if (resizeMethod == MGImageResizeCropEnd) {
            // Crop bottom or right
            if (scaleWidth) {
				// Crop bottom
				destX = 0.0;
				destY = 0.0;
            } else {
				// Crop right
				destX = round(scaledWidth - targetWidth);
				destY = round((scaledHeight - targetHeight) / 2.0);
            }
        }
        sourceRect = NSMakeRect(destX / scaleFactor, destY / scaleFactor,
                                targetWidth / scaleFactor, targetHeight / scaleFactor);
    } else {
        sourceRect = NSMakeRect(0, 0, sourceWidth, sourceHeight);
		dstRect.origin.x += (targetWidth - scaledWidth) / 2.0;
		dstRect.origin.y += (targetHeight - scaledHeight) / 2.0;
		dstRect.size.width = scaledWidth;
		dstRect.size.height = scaledHeight;
    }

    [self drawInRect:dstRect fromRect:sourceRect operation:op fraction:delta];
}

- (NSImage *)imageToFitSize:(NSSize)size method:(MGImageResizingMethod)resizeMethod
{
    NSImage *result = [[NSImage alloc] initWithSize:size];

    // Composite image appropriately
    [result lockFocus];
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
	[self drawInRect:NSMakeRect(0,0,size.width,size.height) operation:NSCompositeSourceOver fraction:1.0 method:resizeMethod];
    [result unlockFocus];

    return [result autorelease];
}

- (NSImage *)imageCroppedToFitSize:(NSSize)size
{
    return [self imageToFitSize:size method:MGImageResizeCrop];
}

- (NSImage *)imageScaledToFitSize:(NSSize)size
{
    return [self imageToFitSize:size method:MGImageResizeScale];
}

@end


text:
export const GET_CARS = 'GET_CARS';
export const ADD_ITEM_TO_CART = 'ADD_ITEM_TO_CART';
export const REMOVE_ITEM_FROM_CART = 'REMOVE_ITEM_FROM_CART';
export const REMOVE_ALL_ITEMS_FROM_CART = 'REMOVE_ALL_ITEMS_FROM_CART';
export const PAGINATIONS = 'PAGINATIONS';


text:
import React from 'react';
import { connect } from 'dva';
import MyLayout from '../components/MyLayout';

function HomePage({ children }) {
  return (
    <div>
      <MyLayout>
         {children}
      </MyLayout>
    </div>
  );
}

function mapStateToProps() {
  return {};
}

export default connect(mapStateToProps)(HomePage);


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Error_Type__c</name>
    <help>Het type fout dat is opgetreden.</help>
    <label>Type fout</label>
</CustomFieldTranslation>


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ArreglandoClinicas2 extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::table('clinicas',function(Blueprint $tabla)
        {
            $tabla->string('distrito');
        });
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
	}

}


text:
package io.fixprotocol.silverflash.transport;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.KeyStore;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

import javax.net.ssl.SSLSession;

import io.fixprotocol.silverflash.buffer.BufferSupplier;

/**
 * @author Don Mendelson
 *
 */
class TlsTcpClientTransport extends AbstractTlsChannel {

  public TlsTcpClientTransport(Selector selector, SocketChannel socketChannel, KeyStore keystore,
      KeyStore truststore, char[] storePassphrase) {
    super(selector, keystore, truststore, storePassphrase, false);
    this.socketChannel = socketChannel;
  }

  public CompletableFuture<? extends Transport> open(BufferSupplier buffers,
      TransportConsumer consumer) {
    Objects.requireNonNull(buffers);
    Objects.requireNonNull(consumer);
    this.buffers = buffers;
    this.consumer = consumer;

    CompletableFuture<TlsTcpClientTransport> future = new CompletableFuture<>();

    SSLSession session = engine.getSession();
    peerNetData = ByteBuffer.allocateDirect(session.getPacketBufferSize())
        .order(ByteOrder.nativeOrder());
    peerAppData = ByteBuffer.allocateDirect(session.getApplicationBufferSize())
        .order(ByteOrder.nativeOrder());
    netData = ByteBuffer.allocateDirect(session.getPacketBufferSize())
        .order(ByteOrder.nativeOrder());
    peerAppData.position(peerAppData.limit());
    netData.position(netData.limit());
    try {
      configureChannel();
      register(0);
      engine.beginHandshake();
      hsStatus = engine.getHandshakeStatus();
      initialHandshake = true;
      doHandshake();
      future.complete(this);
    } catch (IOException ex) {
      future.completeExceptionally(ex);
    }

    return future;
  }

}


text:
namespace NLP { namespace CCG {

double
DerivsDecoder::best_score(const SuperCat *sc){
  double score = sc->score;

  if(sc->left){
    const SuperCat *b = best_equiv(sc->left);
    score += b->score;

    if(sc->right){
      const SuperCat *b = best_equiv(sc->right);
      score += b->score;
    }
  }
  return sc->score = score;
}

} }


text:
import BinaryStream from '../../common/binarystream';
import TokenStream from './tokenstream';

export const enum WrapMode {
  RepeatBoth = 0,
  WrapWidth = 1,
  WrapHeight = 2,
  WrapBoth = 3,
}

/**
 * A texture.
 */
export default class Texture {
  replaceableId = 0;
  path = '';
  wrapMode = WrapMode.RepeatBoth;

  readMdx(stream: BinaryStream): void {
    this.replaceableId = stream.readUint32();
    this.path = stream.read(260);
    this.wrapMode = stream.readUint32();
  }

  writeMdx(stream: BinaryStream): void {
    stream.writeUint32(this.replaceableId);
    stream.skip(260 - stream.write(this.path));
    stream.writeUint32(this.wrapMode);
  }

  readMdl(stream: TokenStream): void {
    for (const token of stream.readBlock()) {
      if (token === 'Image') {
        this.path = stream.read();
      } else if (token === 'ReplaceableId') {
        this.replaceableId = stream.readInt();
      } else if (token === 'WrapWidth') {
        this.wrapMode |= WrapMode.WrapWidth;
      } else if (token === 'WrapHeight') {
        this.wrapMode |= WrapMode.WrapHeight;
      } else {
        throw new Error(`Unknown token in Texture: "${token}"`);
      }
    }
  }

  writeMdl(stream: TokenStream): void {
    stream.startBlock('Bitmap');

    if (this.path.length) {
      stream.writeStringAttrib('Image', this.path);
    }

    if (this.replaceableId !== 0) {
      stream.writeNumberAttrib('ReplaceableId', this.replaceableId);
    }

    if (this.wrapMode & WrapMode.WrapWidth) {
      stream.writeFlag(`WrapWidth`);
    }

    if (this.wrapMode & WrapMode.WrapHeight) {
      stream.writeFlag(`WrapHeight`);
    }

    stream.endBlock();
  }
}


text:
package convenientadditions.api.item;

import net.minecraft.item.ItemStack;

public interface IFuelItem {
    boolean isFuelItem(ItemStack item);

    int getFuelTime(ItemStack item);
}


text:
package com.adaptris.core.util;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ArgsTest extends Args {

  @Before
  public void setUp() throws Exception {}

  @After
  public void tearDown() throws Exception {}

  @Test
  public void testNotNull() {
    try {
      notNull(null, "");
    } catch (IllegalArgumentException expected) {

    }
    notNull("", "");
  }

  @Test
  public void testNotEmpty() {
    try {
      notEmpty(null, "");
    } catch (IllegalArgumentException expected) {

    }
    notEmpty("xxx", "");
  }

  @Test
  public void testNotBlank() {
    try {
      notBlank("", "");
    } catch (IllegalArgumentException expected) {

    }
    notBlank("xxx", "");
  }

}


text:
<Alloy>
	<Model src="letterModel" />
	<Model src="hotspotModel" />

	<Window id="newsfeedWindow" navBarHidden="false" onClose="closeFeedWindow">
		<View id="newsfeedView" class="container"></View>
		<Widget src="menu" name="widget"></Widget>
	</Window>
</Alloy>


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<SEMAPHORE>
    <PARAMETERS>
        <PARAMETER NAME="template">service.xml</PARAMETER>
        <PARAMETER NAME="q">content_type:om_structure_xml</PARAMETER>
        <PARAMETER NAME="service">structure</PARAMETER>
        <PARAMETER NAME="language">en</PARAMETER>
        <PARAMETER NAME="tbdb">IPSV</PARAMETER>
        <PARAMETER NAME="tbdb">IPSV</PARAMETER>
        <PARAMETER NAME="version">1</PARAMETER>
        <PARAMETER NAME="wt">sesOmStructureXML</PARAMETER>
        <PARAMETER NAME="structure">XML</PARAMETER>
        <PARAMETER NAME="command">structure</PARAMETER>
    </PARAMETERS>
    <OM_STRUCTURE>
        <TERM_CLASSES>
            <TERM_CLASS ID="http://www.w3.org/2004/02/skos/core#Concept" PARENT_ID="0">Concept</TERM_CLASS>
            <TERM_CLASS ID="http://www.w3.org/2004/02/skos/core#ConceptScheme" PARENT_ID="0">Concept Scheme</TERM_CLASS>
        </TERM_CLASSES>
        <TERM_FACETS>
            <FIELD ID="ca792b9a-f0ca-4fd9-ba45-a6fd65392a81" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO758">Information and communication
            </FIELD>
            <FIELD ID="6d13260c-642e-4ec2-9294-e5cbcefc3369" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO642">Life in the community
            </FIELD>
            <FIELD ID="30b6deb0-bd17-4dec-ae5e-9935a16a84a3" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO981">Employment, jobs and careers
            </FIELD>
            <FIELD ID="321eeb1e-b211-4e8e-8bee-4f8381b6f36e" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO439">Education and skills
            </FIELD>
            <FIELD ID="6b7db970-af6c-4a2e-9256-ae06211edc4b" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO564">Public order, justice and rights
            </FIELD>
            <FIELD ID="e41d67e2-48bb-42bf-ba46-df7065ed0285" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO652">Science, technology and innovation
            </FIELD>
            <FIELD ID="715a57f8-d84e-472d-9c02-ef2bbce0b9ef" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO616">Leisure and culture
            </FIELD>
            <FIELD ID="10612c03-a3ee-4272-ab88-6e403821700c" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO760">Government, politics and public administration
            </FIELD>
            <FIELD ID="675b8390-72ad-45d1-bfab-77b6c2ac7420" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO557">Health, well-being and care
            </FIELD>
            <FIELD ID="bc565469-cdd8-4c66-8c33-ee6d986f0328" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO6999">People and organisations
            </FIELD>
            <FIELD ID="729c064f-166c-4924-b1b7-ffe38484142d" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO692">Business and industry
            </FIELD>
            <FIELD ID="1be8ca5e-cc5a-4eef-ba7b-9966cada9905" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO460">Housing
            </FIELD>
            <FIELD ID="6acfdac2-7486-4e6b-83c8-b91908d6f45c" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO521">Transport and infrastructure
            </FIELD>
            <FIELD ID="d761553a-d378-4e99-9712-c3d888465e29" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO499">Environment
            </FIELD>
            <FIELD ID="776f8bac-c573-4d2e-9bf0-903326fc6eb5" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO911">International affairs and defence
            </FIELD>
            <FIELD ID="a9b4fe02-746a-438a-9e7c-2c95da345f1a" NAME="term"
                   URI="http://smartlogic.com/conceptScheme#OMITERMO726">Economics and finance
            </FIELD>
        </TERM_FACETS>
        <TERM_ATTRIBUTES>
            <TERM_ATTRIBUTE ID="http://smartlogic.com/attributeType#Internal_no_class" NAME="Internal"/>
        </TERM_ATTRIBUTES>
        <TERM_NOTES>
            <TERM_NOTE ID="http://www.w3.org/2004/02/skos/core#URI" NAME="URI"/>
            <TERM_NOTE ID="http://www.w3.org/2004/02/skos/core#editorialNote" NAME="editorial note"/>
            <TERM_NOTE ID="http://www.w3.org/2004/02/skos/core#historyNote" NAME="history note"/>
            <TERM_NOTE ID="http://www.w3.org/2004/02/skos/core#scopeNote" NAME="scope note"/>
            <TERM_NOTE ID="http://www.w3.org/2000/01/rdf-schema#comment" NAME="comment"/>
            <TERM_NOTE ID="http://www.w3.org/2004/02/skos/core#definition" NAME="definition"/>
            <TERM_NOTE ID="http://www.w3.org/2004/02/skos/core#note" NAME="note"/>
        </TERM_NOTES>
        <TERM_METADATA/>
        <EQUIVALENCE_RELATIONS>
            <RELATION_DEF ABRV="UF" FWD_DISP_NAME="alternative label" ID="http://www.w3.org/2008/05/skos-xl#altLabel"
                          NAME="Use For" REV_ABRV="UF" REV_DISP_NAME="alternative label" REV_NAME="Use For"
                          SCOPE_NOTE="" SYMMETRIC="true"/>
        </EQUIVALENCE_RELATIONS>
        <HIERARCHICAL_RELATIONS>
            <RELATION_DEF ABRV="NT" FWD_DISP_NAME="has narrower" ID="http://www.w3.org/2004/02/skos/core#broader"
                          NAME="Narrower Term" REV_ABRV="BT" REV_DISP_NAME="has broader" REV_NAME="Broader Term"
                          SCOPE_NOTE="" SYMMETRIC="false"/>
            <RELATION_DEF ABRV="HAS NARROWER MATCH" FWD_DISP_NAME="has narrower match"
                          ID="http://www.w3.org/2004/02/skos/core#broadMatch" NAME="has narrower match"
                          REV_ABRV="HAS BROADER MATCH" REV_DISP_NAME="has broader match" REV_NAME="has broader match"
                          SCOPE_NOTE="" SYMMETRIC="false"/>
        </HIERARCHICAL_RELATIONS>
        <ASSOCIATIVE_RELATIONS>
            <RELATION_DEF ABRV="RT" FWD_DISP_NAME="has related" ID="http://www.w3.org/2004/02/skos/core#related"
                          NAME="Related To" REV_ABRV="RT" REV_DISP_NAME="has related" REV_NAME="Related To"
                          SCOPE_NOTE="" SYMMETRIC="true"/>
            <RELATION_DEF ABRV="HAS RELATED MATCH" FWD_DISP_NAME="has related match"
                          ID="http://www.w3.org/2004/02/skos/core#relatedMatch" NAME="has related match"
                          REV_ABRV="HAS RELATED MATCH" REV_DISP_NAME="has related match" REV_NAME="has related match"
                          SCOPE_NOTE="" SYMMETRIC="true"/>
        </ASSOCIATIVE_RELATIONS>
        <INDEX_METADATA>
            <PUBLISH_DATE>2020-11-02T18:25:53.64Z</PUBLISH_DATE>
        </INDEX_METADATA>
    </OM_STRUCTURE>
    <MODELS>
        <MODEL>
            <NAME>IPSV</NAME>
        </MODEL>
    </MODELS>
</SEMAPHORE>


text:
package cn.wizzer.modules.services.cms;

import cn.wizzer.common.base.Service;
import cn.wizzer.modules.models.cms.Cms_link;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;

/**
 * Created by Wizzer on 2016/7/18.
 */
@IocBean(args = {"refer:dao"})
public class CmsLinkService extends Service<Cms_link> {
    public CmsLinkService(Dao dao) {
        super(dao);
    }
}


text:
layout: post
title: On a Completely Unrelated Topic...
date: 2006-01-27 16:50
author: admin
comments: true
categories: [Life]
---
An Excerpt from the article "Great Design: What is Design?" by Joel Spolsky; or as I like to call it "The Mute Button".

"How could a mute button on a sound system hurt?" After all, if you don't want to waste time learning about the mute button, you can just ignore it completely, right?

No. Because at some point, someone will hit it by mistake, and no sound will come out of the speakers, and if they don't know about "mute," they'll start trying to turn up the volume knob all the way, so when they do finally unmute the thing, the speakers will blow out with an ear-shattering boom that creates permanent, concave warps in each of the walls of the room where the sound system was installed (and a matching hump in the floor of the apartment upstairs).

And since the mute button takes up space on the control panel, now all the other control panel buttons have to be a bit smaller, making them harder to read, and there are more buttons, so the whole interface looks scarier. I swear, it's gotten to the point where I don't dare try to use the clock radio in a hotel room to wake me up. With all the options they have I can never quite tell if I'm setting the alarm clock to wake me up in time for my Very Important Meeting, or programming the damn thing to download the latest news from Mongolia on the half-hour.

This hit me just right today.  I broke out laughing at work =)