text:
/**
 * Models a simple solid sphere.
 * This class represents a Ball object. When combined with the GameArena class,
 * instances of the Ball class can be displayed on the screen.
 */
public class Ball
{
	// The following instance variables define the
	// information needed to represent a Ball
	// Feel free to more instance variables if you think it will
	// support your work...

	private double xPosition;			// The X coordinate of this Ball
	private double yPosition;			// The Y coordinate of this Ball
	private double size;				// The diameter of this Ball
	private String colour = "WHITE";	// The colour of this Ball

										// Permissable colours are 8 bit hexadecimal
                                        // RGB values in the format #RRGGBB. e.g.
                                        //
                                        // Pure red is FF0000
                                        // Pure green is 00FF00
                                        // Pure blue is 0000FF

	private double xSpeed;
	private double ySpeed;

    private double GRAVITY = 0.2;
    private double friction = 0.9;

	//ball state - whether this Ball has been eaten or not
	private boolean isEaten;
	public boolean inCollision = false;

	/**
	 * Obtains the current position of this Ball.
	 * @return the X coordinate of this Ball within the GameArena.
	 */
	public double getXPosition()
	{
		return xPosition;
	}

	/**
	 * Obtains the current position of this Ball.
	 * @return the Y coordinate of this Ball within the GameArena.
	 */
	public double getYPosition()
	{
		return yPosition;
	}

	/**
	 * Moves the current position of this Ball to the given co-ordinates
	 * @param x the new x co-ordinate of this Ball
	 */
	public void setXPosition(double x)
	{
		this.xPosition = x;
	}

	/**
	 * Moves the current position of this Ball to the given co-ordinates
	 * @param y the new y co-ordinate of this Ball
	 */
	public void setYPosition(double y)
	{
		this.yPosition = y;
	}

	/**
	 * Obtains the size of this Ball.
	 * @return the diameter of this Ball,in pixels.
	 */
	public double getSize()
	{
		return size;
	}
	/**
	 * Obtains the size of this Ball.
	 * @param size, the diameter of this Ball,in pixels.
	 */
	public void setSize(double size){
		this.size = size;
	}

	/**
	 * Obtains the colour of this Ball.
	 * @return a textual description of the colour of this Ball.
	 */
	public String getColour()
	{
		return colour;
	}
	/**
	sets the colour of this Ball
	@param colour, a String representing the colour.
	*/
	public void setColour(String colour){
		this.colour = colour;
	}

	/******************************************************/

	/**
	constructor for the Ball
	@param x, set the initial x-coordinate of the Ball
	@param y, set the initial y-coordinate of the Ball
	@param diameter, the diameter of the Ball in pixels
	@param col, a String representing the colour of the Ball
	*/
	public Ball(double x, double y, double diameter, String col)
	{
		xPosition = x;
		yPosition = y;
        xSpeed = 0;
        ySpeed = 0;

		size = diameter;
		colour = col;

		isEaten = false;
	}

	/**
	sets the x speed of this Ball
	@param speed, the speed of this Ball in pixels per frame
	*/
    public void setXSpeed(double speed)
    {
        xSpeed = speed;
    }

	/**
	sets the y speed of this Ball
	@param speed, the speed of this Ball in pixels per frame
	*/
    public void setYSpeed(double speed)
    {
        ySpeed = speed;
    }

	/**gets the x speed of this Ball
	@return the x speed
	*/
	public double getXSpeed(){
		return xSpeed;
	}
	/**gets the y speed of this Ball
	@return the y speed
	*/
	public double getYSpeed(){
		return ySpeed;
	}

	/**
	moves this Ball according to the current speed
	*/
    public void move()
    {
		xPosition += xSpeed;
		yPosition += ySpeed;
    }

	/**
	moves this Ball and checks for the edge of the GameArena
	@param maxX, the x edge of the GameArena in pixels
	@param maxY, the y edge of the GameArena in pixels
	*/
	public void bounce(double maxX, double maxY)
	{
        move();
		if (xPosition > maxX || xPosition < 0)
        {
			xSpeed = -xSpeed;
		    xPosition += xSpeed;
            xSpeed = xSpeed * friction;
        }

		if (yPosition > maxY || yPosition < 0)
        {
			ySpeed = -ySpeed;
		    yPosition += ySpeed;
            ySpeed = ySpeed * friction;
        }
	}

	/**
	simple collision detection and bounce between Balls - doesn't obey the laws of physics.
	@param b, the Ball to check this Ball against.
	*/
	public void collision(Ball b){
		double dist = Math.sqrt((xPosition - b.getXPosition())*(xPosition - b.getXPosition()) + (yPosition - b.getYPosition())*(yPosition - b.getYPosition()));

		if(dist < (size + b.getSize()) && !inCollision && !b.inCollision){
			inCollision = true;
			double tempXSpeed = b.getXSpeed();
			double tempYSpeed = b.getYSpeed();

			//if this ball is to the left
			if(xPosition < b.getXPosition()){
				xSpeed = -Math.abs(tempYSpeed);
				b.setXSpeed(Math.abs(ySpeed));
			}
			else{
				xSpeed = Math.abs(tempYSpeed);
				b.setXSpeed(-Math.abs(ySpeed));
			}
			if(yPosition < b.getYPosition()){
				ySpeed = -Math.abs(tempXSpeed);
				b.setYSpeed(Math.abs(xSpeed));
			}
			else{
				ySpeed = -Math.abs(tempXSpeed);
				b.setYSpeed(Math.abs(xSpeed));
			}

			//so if xPosition < b.xPosition then this ball is on the left
			//if yPosition < b.yPosition then this ball is higher up, but we can treat that as normal and imagine we're looking at it the other way up!
			//tan theta = opposite/adjacent
			//double theta = Math.atan((b.getYPosition()-yPosition)/(b.getXPosition()-xPosition));
			//want the speeds to reflect in the normal of this line between centres
			//so have existing xSpeed and ySpeed
			//if xSpeed = 0, then the result would be mainly -xSpeed = ySpeed

		}
		else if(dist < (size + b.getSize())){
			inCollision = false;
			b.inCollision = false;
		}
	}

	/**
	sets the level of friction applied to this Ball
	@param friction, the level of friction to apply to this Ball, default is 0.9
	*/
	public void setFriction(double friction){
			this.friction = friction;
	}

	/**
	obtains the level of friction applied to this Ball
	@return friction
	*/
	public double getFriction(){
		return friction;
	}

	/**
	applies gravity to this Ball when calculating movement, also detects the edge of the GameArena
	@param maxX, the edge of the GameArena
	@param maxY, the edge of the GameArena
	*/
	public void gravity(double maxX, double maxY)
	{
        ySpeed = ySpeed + GRAVITY;
        bounce(maxX, maxY);

    }

	/**
	displays the settings of this Ball, including colour, size and position
	*/
	public void display(){
			System.out.println("Ball: colour="+colour+", x="+xPosition+", y="+yPosition+", diameter="+size);
	}

	/**
	sets this Ball's isEaten state to true.
	*/
	public void isEaten(){
		this.isEaten = true;
	}
	/**
	checks whether this Ball has been eaten
	@return true if the Ball has been eaten
	*/
	public boolean getEaten(){
		return isEaten;
	}
}


text:
//------------------------------------------------------------------------------
// Project:  arrayfunc
// Module:   neg_simd_armv7.c
// Purpose:  Calculate the neg of values in an array.
//           This file provides an SIMD version of the functions.
// Language: C
// Date:     08-Oct-2019
// Ver:      31-Oct-2021.
//
//------------------------------------------------------------------------------
//
//   Copyright 2014 - 2021    Michael Griffin    <m12.griffin@gmail.com>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//------------------------------------------------------------------------------

/*--------------------------------------------------------------------------- */
// This must be defined before "Python.h" in order for the pointers in the
// argument parsing functions to work properly.
#define PY_SSIZE_T_CLEAN

#include "Python.h"

#include "simddefs.h"
#ifdef AF_HASSIMD_ARMv7_32BIT
#include "arm_neon.h"
#endif

#include "arrayerrs.h"

/*--------------------------------------------------------------------------- */

/*--------------------------------------------------------------------------- */

// Auto generated code goes below.

// Function specific macros and other definitions.
#include "neg_defs.h"

/*--------------------------------------------------------------------------- */
/* Initialise an SIMD vector with a specifired value.
   initval = The value to initialise the vector to.
   Returns the initalised SIMD vector.
*/
#if defined(AF_HASSIMD_ARMv7_32BIT)
int8x8_t initvec_signed_char(signed char initval) {

	unsigned int y;
	signed char initvals[CHARSIMDSIZE];
	int8x8_t simdvec;

	for (y = 0; y < CHARSIMDSIZE; y++) {
		initvals[y] = initval;
	}
	simdvec = vld1_s8((initvals));

	return simdvec;
}
#endif

/*--------------------------------------------------------------------------- */
/* The following series of functions reflect the different parameter options possible.
   arraylen = The length of the data arrays.
   data = The input data array.
   dataout = The output data array.
*/
// param_arr_none
#if defined(AF_HASSIMD_ARMv7_32BIT)
void neg_signed_char_1_simd(Py_ssize_t arraylen, signed char *data) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int8x8_t datasliceleft;

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, CHARSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += CHARSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s8( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_s8(datasliceleft);
		// Store the result.
		vst1_s8( &data[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		data[x] = -data[x];
	}

}
#endif

// param_arr_arr
#if defined(AF_HASSIMD_ARMv7_32BIT)
void neg_signed_char_2_simd(Py_ssize_t arraylen, signed char *data, signed char *dataout) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int8x8_t datasliceleft;

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, CHARSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += CHARSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s8( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_s8(datasliceleft);
		// Store the result.
		vst1_s8( &dataout[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		dataout[x] = -data[x];
	}

}
#endif

/*--------------------------------------------------------------------------- */
/* The following series of functions reflect the different parameter options possible.
   arraylen = The length of the data arrays.
   data = The input data array.
   dataout = The output data array.
*/
// param_arr_none
#if defined(AF_HASSIMD_ARMv7_32BIT)
char neg_signed_char_1_simd_ovfl(Py_ssize_t arraylen, signed char *data) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int8x8_t datasliceleft, ovflvec;
	uint8x8_t ovcheck;

	// This is used for detecting a potential overflow condition.
	ovflvec = initvec_signed_char(SCHAR_MIN);

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, CHARSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += CHARSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s8( &data[x]);

		// Check for overflow.
		// Do an equal compare operation.
			ovcheck = vceq_s8 (datasliceleft, ovflvec);

			// Check for overflow.
			if (!(vreinterpret_u64_u8(ovcheck) == 0x0000000000000000)){
			return 1;
		}

		// The actual SIMD operation.
		datasliceleft = vneg_s8(datasliceleft);

		// Store the result.
		vst1_s8( &data[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		if ( minval_loop_willoverflow_signed_char(data[x]) ) {return ARR_ERR_OVFL;}
		data[x] = -data[x];
	}

	return 0;

}

// param_arr_arr
char neg_signed_char_2_simd_ovfl(Py_ssize_t arraylen, signed char *data, signed char *dataout) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int8x8_t datasliceleft, ovflvec;
	uint8x8_t ovcheck;

	// This is used for detecting a potential overflow condition.
	ovflvec = initvec_signed_char(SCHAR_MIN);

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, CHARSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += CHARSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s8( &data[x]);

		// Check for overflow.
		// Do an equal compare operation.
			ovcheck = vceq_s8 (datasliceleft, ovflvec);

			// Check for overflow.
			if (!(vreinterpret_u64_u8(ovcheck) == 0x0000000000000000)){
			return 1;
		}

		// The actual SIMD operation.
		datasliceleft = vneg_s8(datasliceleft);

		// Store the result.
		vst1_s8( &dataout[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		if ( minval_loop_willoverflow_signed_char(data[x]) ) {return ARR_ERR_OVFL;}
		dataout[x] = -data[x];
	}

	return 0;

}
#endif

/*--------------------------------------------------------------------------- */
/* Initialise an SIMD vector with a specifired value.
   initval = The value to initialise the vector to.
   Returns the initalised SIMD vector.
*/
#if defined(AF_HASSIMD_ARMv7_32BIT)
int16x4_t initvec_signed_short(signed short initval) {

	unsigned int y;
	signed short initvals[SHORTSIMDSIZE];
	int16x4_t simdvec;

	for (y = 0; y < SHORTSIMDSIZE; y++) {
		initvals[y] = initval;
	}
	simdvec = vld1_s16((initvals));

	return simdvec;
}
#endif

/*--------------------------------------------------------------------------- */
/* The following series of functions reflect the different parameter options possible.
   arraylen = The length of the data arrays.
   data = The input data array.
   dataout = The output data array.
*/
// param_arr_none
#if defined(AF_HASSIMD_ARMv7_32BIT)
void neg_signed_short_1_simd(Py_ssize_t arraylen, signed short *data) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int16x4_t datasliceleft;

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, SHORTSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += SHORTSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s16( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_s16(datasliceleft);
		// Store the result.
		vst1_s16( &data[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		data[x] = -data[x];
	}

}
#endif

// param_arr_arr
#if defined(AF_HASSIMD_ARMv7_32BIT)
void neg_signed_short_2_simd(Py_ssize_t arraylen, signed short *data, signed short *dataout) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int16x4_t datasliceleft;

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, SHORTSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += SHORTSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s16( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_s16(datasliceleft);
		// Store the result.
		vst1_s16( &dataout[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		dataout[x] = -data[x];
	}

}
#endif

/*--------------------------------------------------------------------------- */
/* The following series of functions reflect the different parameter options possible.
   arraylen = The length of the data arrays.
   data = The input data array.
   dataout = The output data array.
*/
// param_arr_none
#if defined(AF_HASSIMD_ARMv7_32BIT)
char neg_signed_short_1_simd_ovfl(Py_ssize_t arraylen, signed short *data) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int16x4_t datasliceleft, ovflvec;
	uint16x4_t ovcheck;

	// This is used for detecting a potential overflow condition.
	ovflvec = initvec_signed_short(SHRT_MIN);

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, SHORTSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += SHORTSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s16( &data[x]);

		// Check for overflow.
		// Do an equal compare operation.
			ovcheck = vceq_s16 (datasliceleft, ovflvec);

			// Check for overflow.
			if (!(vreinterpret_u64_u16(ovcheck) == 0x0000000000000000)){
			return 1;
		}

		// The actual SIMD operation.
		datasliceleft = vneg_s16(datasliceleft);

		// Store the result.
		vst1_s16( &data[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		if ( minval_loop_willoverflow_signed_short(data[x]) ) {return ARR_ERR_OVFL;}
		data[x] = -data[x];
	}

	return 0;

}

// param_arr_arr
char neg_signed_short_2_simd_ovfl(Py_ssize_t arraylen, signed short *data, signed short *dataout) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	int16x4_t datasliceleft, ovflvec;
	uint16x4_t ovcheck;

	// This is used for detecting a potential overflow condition.
	ovflvec = initvec_signed_short(SHRT_MIN);

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, SHORTSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += SHORTSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_s16( &data[x]);

		// Check for overflow.
		// Do an equal compare operation.
			ovcheck = vceq_s16 (datasliceleft, ovflvec);

			// Check for overflow.
			if (!(vreinterpret_u64_u16(ovcheck) == 0x0000000000000000)){
			return 1;
		}

		// The actual SIMD operation.
		datasliceleft = vneg_s16(datasliceleft);

		// Store the result.
		vst1_s16( &dataout[x],  datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		if ( minval_loop_willoverflow_signed_short(data[x]) ) {return ARR_ERR_OVFL;}
		dataout[x] = -data[x];
	}

	return 0;

}
#endif

/*--------------------------------------------------------------------------- */
/* The following series of functions reflect the different parameter options possible.
   arraylen = The length of the data arrays.
   data = The input data array.
   dataout = The output data array.
*/
// param_arr_none
#if defined(AF_HASSIMD_ARMv7_32BIT)
void neg_float_1_simd(Py_ssize_t arraylen, float *data) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	float32x2_t datasliceleft;

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, FLOATSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += FLOATSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_f32( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_f32(datasliceleft);
		// Store the result.
		vst1_f32( &data[x], datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		data[x] = -data[x];
	}

}

// param_arr_arr
void neg_float_2_simd(Py_ssize_t arraylen, float *data, float *dataout) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	float32x2_t datasliceleft;

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, FLOATSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += FLOATSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_f32( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_f32(datasliceleft);
		// Store the result.
		vst1_f32( &dataout[x], datasliceleft);
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		dataout[x] = -data[x];
	}

}
#endif

/*--------------------------------------------------------------------------- */
/* The following series of functions reflect the different parameter options possible.
   arraylen = The length of the data arrays.
   data = The input data array.
   dataout = The output data array.
   Returns 1 if overflow occurred, else returns 0.
*/
// param_arr_none
#if defined(AF_HASSIMD_ARMv7_32BIT)
char neg_float_1_simd_ovfl(Py_ssize_t arraylen, float *data) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	float32x2_t datasliceleft, checkslice;

	float checkvecresults[FLOATSIMDSIZE];
	float checksliceinit[FLOATSIMDSIZE] = {0.0};

	// This is used to check for errors by accumulating non-finite values.
	checkslice = vld1_f32( checksliceinit);

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, FLOATSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += FLOATSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_f32( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_f32(datasliceleft);
		// Store the result.
		vst1_f32( &data[x], datasliceleft);

		// Check the result. None-finite errors should accumulate.
		checkslice = vmul_f32(checkslice, datasliceleft);
	}

	// Check the results of the SIMD operations. If all is OK then the
	// results should be all zeros. Any none-finite numbers however will
	// propagate through and accumulate.
	vst1_f32( checkvecresults, checkslice);
	for (x = 0; x < FLOATSIMDSIZE; x++) {
		if (!isfinite(checkvecresults[x])) {return 1;}
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		data[x] = -data[x];
		if (!isfinite(data[x])) {return 1;}
	}

	// Everything was OK.
	return 0;

}

// param_arr_arr
char neg_float_2_simd_ovfl(Py_ssize_t arraylen, float *data, float *dataout) {

	// array index counter.
	Py_ssize_t x;

	// SIMD related variables.
	Py_ssize_t alignedlength;

	float32x2_t datasliceleft, checkslice;

	float checkvecresults[FLOATSIMDSIZE];
	float checksliceinit[FLOATSIMDSIZE] = {0.0};

	// This is used to check for errors by accumulating non-finite values.
	checkslice = vld1_f32( checksliceinit);

	// Calculate array lengths for arrays whose lengths which are not even
	// multipes of the SIMD slice length.
	alignedlength = calcalignedlength(arraylen, FLOATSIMDSIZE);

	// Perform the main operation using SIMD instructions.
	for (x = 0; x < alignedlength; x += FLOATSIMDSIZE) {
		// Load the data into the vector register.
		datasliceleft = vld1_f32( &data[x]);
		// The actual SIMD operation.
		datasliceleft = vneg_f32(datasliceleft);
		// Store the result.
		vst1_f32( &dataout[x], datasliceleft);

		// Check the result. None-finite errors should accumulate.
		checkslice = vmul_f32(checkslice, datasliceleft);
	}

	// Check the results of the SIMD operations. If all is OK then the
	// results should be all zeros. Any none-finite numbers however will
	// propagate through and accumulate.
	vst1_f32( checkvecresults, checkslice);
	for (x = 0; x < FLOATSIMDSIZE; x++) {
		if (!isfinite(checkvecresults[x])) {return 1;}
	}

	// Get the max value within the left over elements at the end of the array.
	for (x = alignedlength; x < arraylen; x++) {
		dataout[x] = -data[x];
		if (!isfinite(dataout[x])) {return 1;}
	}

	// Everything was OK.
	return 0;

}
#endif

redpajama_set_name: RedPajamaGithub


text:
package goldilocks.util.domain;

import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class DomainTypeBase implements DomainType {

	@Override
	@JsonProperty
	public String get_type() {
		return this.getClass().getSimpleName();
	}

}


text:
import signal
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from input_handler import *
from output_handler import *
import Queue
import threading
import utilities
import platform
import sys

# XXX hack for pyinstaller
try:
    import h5py.h5ac
except:
    pass

input_handler = None
streaming_input_thread = None
output_handler = None
output_thread = None
args = None
done = False

VERSION = (1, 9, 0)

def prog_version_string():
    return "Muse Player " + ".".join(str(x) for x in VERSION)

# Catch Control-C interrupt and cancel
def ix_signal_handler(signum, frame):
    utilities.DisplayPlayback.end()
    if input_handler:
        input_handler.put_done_message()
    if output_handler:
        output_handler.put_done_message()
    if output_thread:
        output_thread.join()
    print "Aborted."
    sys.exit()

def run_():
    global args, input_handler, streaming_input_thread, output_handler, output_thread
    parsing_streaming_input_thread = None
    streaming_input_thread = None
    output_thread = None
    done = False
    debug = False
    # Catch control-C
    signal.signal(signal.SIGINT, ix_signal_handler)
    if not 'Windows' in platform.platform():
        signal.signal(signal.SIGPIPE, ix_signal_handler)

    parser = ArgumentParser(description=prog_version_string(),
                            prog="muse-player.py",
                            usage="%(prog)s <one_input:(-l|-f|-o)> <one_or_more_outputs:[-s,-F,-M,-O,-D]>",
                            formatter_class=RawDescriptionHelpFormatter,
                            epilog="""

Examples:
    muse-player -f my_eeg_recording.muse -s osc.tcp://localhost:7887
        This will read in the file "my_eeg_recording.muse" and send those messages as OSC to port 7887.

    muse-player -l 5555 -M matlab.mat -s 5001
        This will receive OSC messages on port 5555, save them to file, and rebroadcast them to port 5001.
                            """)

    parser.add_argument("-v", "--verbose",
                        action="store_true",
                        dest="verbose",
                        default=False,
                        help="Print status messages to stdout")
    parser.add_argument("--version",
                        action="version",
                        version=prog_version_string())
    parser.add_argument("-q", "--as-fast-as-possible",
                        action="store_true",
                        dest="as_fast_as_possible",
                        default=False,
                        help="Replay input as fast as possible instead of using original timing.")

    parser.add_argument("-j", "--jump-data-gaps",
                        action="store_true",
                        dest="jump_data_gaps",
                        default=False,
                        help="Replay input by omitting any data gaps larger than 1 second.")

    parser.add_argument("-n", "--no--time--data",
                        action="store_true",
                        dest="no_time_data",
                        default=False,
                        help="Replay input by omitting output of current timing info.")

    parser.add_argument("-i", "--filter",
                        dest="filter_data",
                        nargs='+',
                        help="Filter data by path. e.g. -i /muse/elements/alpha /muse/eeg")

    input_group = parser.add_argument_group("Input options",
                                            "Only one type of input can be specified, but can be multiple files of the same type:")
    input_group.add_argument("-l", "--input-osc-port",
                             const="tcp:5000",
                             nargs='?',
                             help="Listen for OSC messages on this port (default: tcp:5000).")
    input_group.add_argument("-f", "--input-muse-files",
                             nargs='+',
                             help="Input from Muse file format.")
    input_group.add_argument("-o", "--input-oscreplay-files",
                             nargs='+',
                             help="Input from OSC-replay files.")

    output_group = parser.add_argument_group("Output options", "One or more outputs can be specified:")
    output_group.add_argument("-s", "--output-osc-url",
                              help="Output OSC messages to HOST:PORT (default: osc.udp://localhost:5001)",
                              const="osc.udp://localhost:5001",
                              nargs='?')
    output_group.add_argument("-F", "--output-muse-file",
                              help="Output to a Muse file",
                              metavar="FILE")
    output_group.add_argument("-M", "--output-matlab-file",
                              help="Output to a Matlab file",
                              metavar="FILE")
    output_group.add_argument("-O", "--output-oscreplay-file",
                              help="Output to an OSC-replay file",
                              metavar="FILE")
    output_group.add_argument("-C", "--output-csv-file",
                              help="Output to an CSV file",
                              metavar="FILE")
    output_group.add_argument("-D", "--output-screen-dump",
                              help="Output to the screen directly",
                              action='store_true')

    args = parser.parse_args()

    if args.no_time_data:
        utilities.DisplayPlayback.output_timing = False

    queue = Queue.Queue()
    input_handler = None
    output_handler = None

    print parser.description
    total_input_types = int(hasattr(args, 'input_osc_port')) + int(hasattr(args, 'input_muse_files')) + int(hasattr(args, 'input_osc_files'))
    total_input_types = int(bool(args.input_osc_port)) + int(bool(args.input_muse_files)) + int(bool(args.input_oscreplay_files))
    if total_input_types > 1:
        print >>sys.stderr, args.input_osc_port
        print >>sys.stderr, args.input_muse_files
        print >>sys.stderr, args.input_oscreplay_files
        parser.print_help(sys.stderr)
        print >>sys.stderr, '*' * 80
        print >>sys.stderr, ('ERROR: You can only specify one input type, you '
                             'specified ') + str(total_input_types)
        print >>sys.stderr, ""
        sys.exit(1)

    elif total_input_types == 0:
        parser.print_help(sys.stderr)
        print >>sys.stderr, '*' * 80
        print >>sys.stderr, ('ERROR: You have no input type, please specify '
                             'an input type.')
        print >>sys.stderr, ('Options are osc stream (-l port), muse file '
                             '(-f file) or osc replay file (-o file)')
        print >>sys.stderr, ''
        sys.exit(1)

    # Check for osc output stream enabled, if not default to writing the file
    # as fast as possible
    if args.output_osc_url == None:
        args.as_fast_as_possible = True

    print "Input: "
    if args.input_osc_port:
        print args.input_osc_port
        valid_options = ['udp', 'tcp']
        if len(args.input_osc_port.split(':')) == 1:
            if args.input_osc_port.lower() in valid_options:
                print "  * OSC port: {}:5000 (Hit Control-C to stop)".format(
                    args.input_osc_port)
            elif args.input_osc_port.isdigit():
                print "  * OSC port: tcp:{} (Hit Control-C to stop)".format(
                    args.input_osc_port)
            else:
                err = (
                    "Input error: You specified OSC listening at '{}' "
                    "tcp:port and udp:port are the only valid options"
                    ).format(args.input_osc_port)
                print >>sys.stderr, err
                sys.exit(1)
        else:
            port_options = args.input_osc_port.split(':')
            type = port_options[0]
            if not (type.lower() in valid_options):
                err = (
                    "Input port type error: You specified '{}' tcp "
                    "and udp are the only valid options"
                    ).format(port_options[0].lower())
                print >>sys.stderr, err
                sys.exit(1)
            elif port_options[1].isdigit():
                print "  * OSC port: {} (Hit Control-C to stop)".format(
                    args.input_osc_port)
            else:
                err = (
                    'Invalid port: {}, not a number, defaulting to port 5000'
                    ).format(port_options[1])
                print >>sys.stderr, err

                args.input_osc_port = port_options[0] + ':' + str(5000)
                print "  * OSC port: " + args.input_osc_port + " (Hit Control-C to stop)"
        input_handler = OSCListener(queue, args.input_osc_port)

    elif args.input_muse_files:
        input_handler = MuseProtoBufFileReader(queue)
        print "  * Muse file(s): " + str(args.input_muse_files)
    elif args.input_oscreplay_files:
        print args.input_oscreplay_files
        input_handler = MuseOSCFileReader(queue)
        parsing_streaming_input_thread = threading.Thread(target=input_handler.parse_files, args=[args.input_oscreplay_files])
        parsing_streaming_input_thread.daemon = True
        print "  * OSC file(s): " + str(args.input_oscreplay_files)

    print ""
    print "Output: "
    output_handler = OutputHandler(queue)
    if args.output_oscreplay_file:
        print "  * OSC-replay file: " + str(args.output_oscreplay_file)
        osc_writer = OSCFileWriter(args.output_oscreplay_file)
        output_handler.add_listener(osc_writer)
    if args.output_csv_file:
        print "  * CSV file: " + str(args.output_csv_file)
        csv_writer = CSVFileWriter(args.output_csv_file)
        output_handler.add_listener(csv_writer)
    if args.output_muse_file:
        print "  * Muse file: " + str(args.output_muse_file)
        proto_writer = ProtoBufFileWriter(args.output_muse_file)
        output_handler.add_listener(proto_writer)
    if args.output_osc_url:
        print "  * OSC output stream URL: " + str(args.output_osc_url)
        osc_sender = OSCMessageWriter(args.output_osc_url)
        output_handler.add_listener(osc_sender)
    if args.output_matlab_file:
        print "  * Matlab output file: " + str(args.output_matlab_file)
        matlab_writer = MatlabWriter(args.output_matlab_file)
        output_handler.add_listener(matlab_writer)

    total_output_types = int(bool(args.output_csv_file)) + int(bool(args.output_oscreplay_file)) + int(bool(args.output_muse_file)) + int(bool(args.output_osc_url)) + int(bool(args.output_matlab_file))
    if total_output_types == 0 or args.output_screen_dump:
        print "  * Screen output mode"
        utilities.DisplayPlayback.screen_dump = True
        screen_writer = ScreenWriter()
        output_handler.add_listener(screen_writer)

    if args.input_muse_files:
        parsing_streaming_input_thread = threading.Thread(target=input_handler.parse_files, args=[args.input_muse_files, args.verbose, args.as_fast_as_possible, args.jump_data_gaps])
        parsing_streaming_input_thread.daemon = True
        parsing_streaming_input_thread.start()

    if args.input_oscreplay_files:
        parsing_streaming_input_thread = threading.Thread(target=input_handler.parse_files, args=[args.input_oscreplay_files, args.verbose, args.as_fast_as_possible, args.jump_data_gaps])
        parsing_streaming_input_thread.daemon = True
        parsing_streaming_input_thread.start()

    if args.input_osc_port:
        streaming_input_thread = threading.Thread(target=input_handler.start, args=[args.as_fast_as_possible, args.jump_data_gaps])
        streaming_input_thread.daemon = True
    output_thread = threading.Thread(target=output_handler.start, args=[args.filter_data, args.verbose])
    output_thread.daemon = True

    if streaming_input_thread:
        streaming_input_thread.start()
    output_thread.start()

    while not done:
        try:
            status = "Gap in Data "
            if parsing_streaming_input_thread:
                parsing_streaming_input_thread.join(0.1)
                if not args.as_fast_as_possible:
                    utilities.DisplayPlayback.playback_time_no_stream()
            if streaming_input_thread:
                streaming_input_thread.join(0.1)
            output_thread.join(0.1)
            if streaming_input_thread:
                if not streaming_input_thread.isAlive() and not output_thread.isAlive():
                    done = True
            if parsing_streaming_input_thread:
                if not parsing_streaming_input_thread.isAlive() and not output_thread.isAlive():
                    done = True
        except BaseException as ex:
            #print ex.message
            done = True
            break

    data_parsed = 0
    data_in = 0
    data_out = 0
    if parsing_streaming_input_thread and args.input_muse_files:
        data_parsed = input_handler.events_added_by_threads
        data_in = input_handler.added_to_queue_events
        if args.output_matlab_file:
            data_out = matlab_writer.data_written
            if not data_in == data_out:
                print 'Input Output size mismatch:'
                print 'Data in: ' + str(data_in) + ' Data out: ' + str(data_out) + " File: " + str(args.input_muse_files)

# If invoked as a script
if __name__ == "__main__":
    run_()


text:
package org.oscm.domobjects.enums;

/**
 * ModificationType indicates wether a History-Entry for a Domain Object comes
 * from an Insert (ADD), Update (MODIFY) or Delete (DELETE) action.
 *
 * @author schmid
 */
public enum ModificationType {
    ADD, MODIFY, DELETE
}


text:
<title>GCSE level problems</title>
<meta name="description" content="Problems set for GCSE level students">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../styles.css">

 Michal Paszkiewicz

Maths - GCSE level

    Problems involving simplifying algebraic fractions.

Number

      Structure and Calculation
      Fractions, decimals and percentages

        Home
        Maths


text:
package busyIndicator_test

import (
	"time"

	"github.com/ckaznocha/busyIndicator"
)

func ExampleThrobber() {
	c := make(chan bool)

	go busyIndicator.Throbber(busyIndicator.Spin, 50*time.Millisecond, c)
	time.Sleep(1 * time.Second)
	c <- true

	go busyIndicator.Throbber(busyIndicator.Dot, 100*time.Millisecond, c)
	time.Sleep(1 * time.Second)
	c <- true

	go busyIndicator.Throbber(busyIndicator.Grow, 150*time.Millisecond, c)
	time.Sleep(10 * time.Second)
	c <- true
}

func ExampleThrobberPrefixed() {
	c := make(chan bool)

	go busyIndicator.ThrobberPrefixed("hello ", busyIndicator.Spin, 100*time.Millisecond, c)
	time.Sleep(1 * time.Second)
	c <- true
}


text:
require 'kabal/languages/language'
require 'kabal/languages/russian/declinations'
require 'kabal/languages/russian/natural_numbers'
require 'kabal/languages/russian/fractional_numbers'

module Kabal
  class Russian < Kabal::Language
    include Kabal::RussianRules::NaturalNumbers
    include Kabal::RussianRules::FractionalNumbers
  end
end


text:
PCLIMP(void, PointCloud, copyNormal)(pcl::PointCloud<_PointT>::Ptr *self, Indices_ptr *indices, pcl::PointCloud<pcl::Normal>::Ptr *cloud_out)
{
  if (indices)
    pcl::copyPointCloud(**self, **indices, **cloud_out);
  else
    pcl::copyPointCloud(**self, **cloud_out);
}

PCLIMP(void, PointCloud, copyXYZNormal)(pcl::PointCloud<_PointT>::Ptr *self, Indices_ptr *indices, pcl::PointCloud<pcl::PointNormal>::Ptr *cloud_out)
{
  if (indices)
    pcl::copyPointCloud(**self, **indices, **cloud_out);
  else
    pcl::copyPointCloud(**self, **cloud_out);
}

PCLIMP(void, PointCloud, copyXYZINormal)(pcl::PointCloud<_PointT>::Ptr *self, Indices_ptr *indices, pcl::PointCloud<pcl::PointXYZINormal>::Ptr *cloud_out)
{
  if (indices)
    pcl::copyPointCloud(**self, **indices, **cloud_out);
  else
    pcl::copyPointCloud(**self, **cloud_out);
}

PCLIMP(void, PointCloud, copyXYZRGBNormal)(pcl::PointCloud<_PointT>::Ptr *self, Indices_ptr *indices, pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr *cloud_out)
{
  if (indices)
    pcl::copyPointCloud(**self, **indices, **cloud_out);
  else
    pcl::copyPointCloud(**self, **cloud_out);
}


text:
<?php

namespace UIFI\GrupLACScraperBundle\Service;

use Symfony\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Container;

/**
 * Servicio que se encarga de manejar la lógica de las Revistas de indexación.
 *
 * @author Cristian Chaparro Africano <cristianchaparroa@gmail.com>
*/
class RevistaService
{
    public function __construct(Container $container)
    {
       $this->container = $container;
       $this->em = $container->get('doctrine.orm.entity_manager');
    }

    /**
     * Función que se encarga de listar todas las revistas de indexación
     * @return arreglo con las revistas de indexacion
    */
    public function listar(){
      $revistas = array();
      $repostoryRevistas = $this->em->getRepository('UIFIProductosBundle:Revista');
      $lista = $repostoryRevistas->findAll();
      foreach( $listas as $revista ){
        $cateogrias = array();

        $listCategories = $revista->getCategorias();
        //recorro las categorias
        foreach( $listaCategories as  $category ){
          $categorias [] = array(
            'tipo'            => $category->getTipo(),
            'vigenciaInicial' => $category->getVigenciaInicial(),
            'vigenciaFinal'   =>$category->getVigenciaFinal(),
          );
        }
        $journal = array(
          'isbn'       => $revista->getId(),
          'nombre'     => $revista->getNombre(),
          'categorias' => $Categorias,
        );
        $revistas []  = $journal;
      }
      return $revistas;
    }
}


text: Sign-in with Facebook to post a comment


text:
package implementation

import (
	"bufio"
	"io"

	"github.com/pinpt/dialect/pkg/types"
)

type DialectImplementation struct {
}

// CreateLineByLineExaminer returns an interface which can be called with each line using the ProcessLine function
func (i *DialectImplementation) CreateLineByLineExaminer(language string, filename string, config *types.DialectConfiguration) (*types.DialectContext, error) {
	ex, err := types.ExaminerForLanguage(language)
	if err != nil {
		return nil, err
	}
	ctx := &types.DialectContext{
		Language: language,
		Filename: filename,
		Config:   config,
		Examiner: ex,
		Result:   &types.DialectResult{},
	}
	return ctx, nil
}

// Examine is used to detect information about the source code
func (i *DialectImplementation) Examine(language string, filename string, reader io.Reader, config *types.DialectConfiguration) (*types.DialectResult, error) {
	ctx, err := i.CreateLineByLineExaminer(language, filename, config)
	if err != nil {
		return nil, err
	}
	buf := bufio.NewReader(reader)
	for {
		contents, err := buf.ReadString('\n')
		eof := err == io.EOF
		if err != nil && eof == false {
			return nil, err
		}
		_, err = ctx.ProcessLine([]byte(contents), eof)
		if err != nil {
			return nil, err
		}
		if eof {
			break
		}
	}
	return ctx.Result, nil
}

// Detect will attempt to detect all the frameworks for a given project source directory
func (i *DialectImplementation) DetectFrameworks(directory string) ([]*types.DialectFramework, error) {
	frameworks := make([]*types.DialectFramework, 0)
	for _, processor := range types.Processors() {
		results, err := processor.Detect(directory)
		if err != nil {
			return nil, err
		}
		for _, r := range results {
			frameworks = append(frameworks, r)
		}
	}
	if len(frameworks) > 0 {
		return frameworks, nil
	}
	return nil, nil
}

// New returns a new implementation of Dialect
func New() types.Dialect {
	return &DialectImplementation{}
}


text:
<?php
session_start();
unset($_SESSION['guru']);
unset($_SESSION['siswa']);
header('location:../index.php');
?>


text:
#include "gm/gm.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColorSpace.h"
#include "include/core/SkImage.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkString.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTypes.h"

static sk_sp<SkImage> make_image() {
    const SkImageInfo info = SkImageInfo::MakeN32Premul(319, 52);
    auto surface(SkSurface::MakeRaster(info));
    SkCanvas* canvas = surface->getCanvas();
    canvas->drawColor(0xFFF8F8F8);

    SkPaint paint;
    paint.setAntiAlias(true);

    paint.setStyle(SkPaint::kStroke_Style);
    for (int i = 0; i < 20; ++i) {
        canvas->drawCircle(-4, 25, 20, paint);
        canvas->translate(25, 0);
    }
    return surface->makeImageSnapshot();
}

DEF_SIMPLE_GM(mipmap, canvas, 400, 200) {
    sk_sp<SkImage> img(make_image());//SkImage::NewFromEncoded(data));

    const SkRect dst = SkRect::MakeWH(177, 15);

    SkString str;
    str.printf("scale %g %g", dst.width() / img->width(), dst.height() / img->height());
//    canvas->drawString(str, 300, 100, SkFont(nullptr, 30), paint);

    const SkSamplingOptions samplings[] = {
        SkSamplingOptions(SkFilterMode::kNearest),
        SkSamplingOptions(SkFilterMode::kLinear),
        SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kLinear),
        SkSamplingOptions(SkCubicResampler::Mitchell()),
    };

    canvas->translate(20, 20);
    for (size_t i = 0; i < SK_ARRAY_COUNT(samplings); ++i) {
        canvas->drawImageRect(img.get(), dst, samplings[i], nullptr);
        canvas->translate(0, 20);
    }
    canvas->drawImage(img.get(), 20, 20);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

// create a circle image computed raw, so we can wrap it as a linear or srgb image
static sk_sp<SkImage> make(sk_sp<SkColorSpace> cs) {
    const int N = 100;
    SkImageInfo info = SkImageInfo::Make(N, N, kN32_SkColorType, kPremul_SkAlphaType, cs);
    SkBitmap bm;
    bm.allocPixels(info);

    for (int y = 0; y < N; ++y) {
        for (int x = 0; x < N; ++x) {
            *bm.getAddr32(x, y) = (x ^ y) & 1 ? 0xFFFFFFFF : 0xFF000000;
        }
    }
    bm.setImmutable();
    return bm.asImage();
}

static void show_mips(SkCanvas* canvas, SkImage* img) {
    SkSamplingOptions sampling(SkFilterMode::kLinear,
                               SkMipmapMode::kLinear);

    // Want to ensure we never draw fractional pixels, so we use an IRect
    SkIRect dst = SkIRect::MakeWH(img->width(), img->height());
    while (dst.width() > 5) {
        canvas->drawImageRect(img, SkRect::Make(dst), sampling, nullptr);
        dst.offset(dst.width() + 10, 0);
        dst.fRight = dst.fLeft + dst.width()/2;
        dst.fBottom = dst.fTop + dst.height()/2;
    }
}

/*
 *  Ensure that in L32 drawing mode, both images/mips look the same as each other, and
 *  their mips are darker than the original (since the mips should ignore the gamma in L32).
 *
 *  Ensure that in S32 drawing mode, all images/mips look the same, and look correct (i.e.
 *  the mip levels match the original in brightness).
 */
DEF_SIMPLE_GM(mipmap_srgb, canvas, 260, 230) {
    sk_sp<SkImage> limg = make(nullptr);
    sk_sp<SkImage> simg = make(SkColorSpace::MakeSRGB());

    canvas->translate(10, 10);
    show_mips(canvas, limg.get());
    canvas->translate(0, limg->height() + 10.0f);
    show_mips(canvas, simg.get());
}

///////////////////////////////////////////////////////////////////////////////////////////////////

// create a gradient image computed raw, so we can wrap it as a linear or srgb image
static sk_sp<SkImage> make_g8_gradient(sk_sp<SkColorSpace> cs) {
    const int N = 100;
    SkImageInfo info = SkImageInfo::Make(N, N, kGray_8_SkColorType, kOpaque_SkAlphaType, cs);
    SkBitmap bm;
    bm.allocPixels(info);

    for (int y = 0; y < N; ++y) {
        for (int x = 0; x < N; ++x) {
            *bm.getAddr8(x, y) = static_cast<uint8_t>(255.0f * ((x + y) / (2.0f * (N - 1))));
        }
    }
    bm.setImmutable();
    return bm.asImage();
}

static void show_mips_only(SkCanvas* canvas, SkImage* img) {
    SkSamplingOptions sampling(SkFilterMode::kLinear,
                               SkMipmapMode::kLinear);

    // Want to ensure we never draw fractional pixels, so we use an IRect
    SkIRect dst = SkIRect::MakeWH(img->width() / 2, img->height() / 2);
    while (dst.width() > 5) {
        canvas->drawImageRect(img, SkRect::Make(dst), sampling, nullptr);
        dst.offset(dst.width() + 10, 0);
        dst.fRight = dst.fLeft + dst.width() / 2;
        dst.fBottom = dst.fTop + dst.height() / 2;
    }
}

/*
 *  Ensure that in L32 drawing mode, both images/mips look the same as each other, and
 *  their mips are darker than the original (since the mips should ignore the gamma in L32).
 *
 *  Ensure that in S32 drawing mode, all images/mips look the same, and look correct (i.e.
 *  the mip levels match the original in brightness).
 */
DEF_SIMPLE_GM(mipmap_gray8_srgb, canvas, 260, 230) {
    sk_sp<SkImage> limg = make_g8_gradient(nullptr);
    sk_sp<SkImage> simg = make_g8_gradient(SkColorSpace::MakeSRGB());

    canvas->translate(10, 10);
    show_mips_only(canvas, limg.get());
    canvas->translate(0, limg->height() + 10.0f);
    show_mips_only(canvas, simg.get());
}


text:
@interface CBEditorStringInline : CBEditorString <UITextFieldDelegate> {

    BOOL _secureTextEntry;
    UITextField *_textField;

    CBCell *_cell;

}

@property (nonatomic, assign) BOOL secureTextEntry;

- (id) applySecureTextEntry:(BOOL)secureTextEntry;

@end


text:
#ifndef CPUPORT_H__
#define CPUPORT_H__

#include <rtconfig.h>

/* bytes of register width  */
#ifdef ARCH_CPU_64BIT
#define STORE                   sd
#define LOAD                    ld
#define REGBYTES                8
#else
#define STORE                   sw
#define LOAD                    lw
#define REGBYTES                4
#endif

#ifdef ARCH_RISCV_FPU
#ifdef ARCH_RISCV_FPU_D
#define FSTORE                  fsd
#define FLOAD                   fld
#define FREGBYTES               8
#define rv_floatreg_t           rt_int64_t
#endif
#ifdef ARCH_RISCV_FPU_S
#define FSTORE                  fsw
#define FLOAD                   flw
#define FREGBYTES               4
#define rv_floatreg_t           rt_int32_t
#endif
#endif

#endif


text:
namespace vixl {

// Each actual test is represented by a Test instance.
// Tests are appended to a static linked list upon creation.
class Test {
  typedef void (TestFunction)();

 public:
  Test(const char* name, TestFunction* callback);

  const char* name() { return name_; }
  TestFunction* callback() { return callback_; }
  static Test* first() { return first_; }
  static Test* last() { return last_; }
  Test* next() { return next_; }
  static bool debug() { return debug_; }
  static void set_debug(bool value) { debug_ = value; }
  static bool trace_sim() { return trace_sim_; }
  static void set_trace_sim(bool value) { trace_sim_ = value; }
  static bool trace_reg() { return trace_reg_; }
  static void set_trace_reg(bool value) { trace_reg_ = value; }
  static bool trace_write() { return trace_write_; }
  static void set_trace_write(bool value) { trace_write_ = value; }
  static bool coloured_trace() { return coloured_trace_; }
  static void set_coloured_trace(bool value) { coloured_trace_ = value; }
  static bool instruction_stats() { return instruction_stats_; }
  static void set_instruction_stats(bool value) { instruction_stats_ = value; }
  static bool sim_test_trace() { return sim_test_trace_; }
  static void set_sim_test_trace(bool value) { sim_test_trace_ = value; }

  // The debugger is needed to trace register values.
  static bool run_debugger() { return debug_; }

 private:
  const char* name_;
  TestFunction* callback_;

  static Test* first_;
  static Test* last_;
  Test* next_;
  static bool debug_;
  static bool trace_sim_;
  static bool trace_reg_;
  static bool trace_write_;
  static bool coloured_trace_;
  static bool instruction_stats_;
  static bool sim_test_trace_;
};

// Define helper macros for test files.

// Macro to register a test. It instantiates a Test and registers its
// callback function.
#define TEST_(Name)                                                            \
void Test##Name();                                                             \
Test test_##Name(#Name, &Test##Name);                                          \
void Test##Name()
}  // namespace vixl

#endif  // TEST_TEST_H_


text:
package dao

import (
	"context"
	"github.com/smartystreets/goconvey/convey"
	"math/rand"
	"strconv"
	"testing"
)

func TestDaoMainVip(t *testing.T) {
	convey.Convey("MainVip", t, func(ctx convey.C) {
		var (
			c   = context.Background()
			mid = int64(27515308)
		)
		ctx.Convey("When everything gose positive", func(ctx convey.C) {
			mv, err := d.MainVip(c, mid)
			ctx.Convey("Then err should be nil.mv should not be nil.", func(ctx convey.C) {
				ctx.So(err, convey.ShouldBeNil)
				ctx.So(mv, convey.ShouldNotBeNil)
			})
		})
	})
}

func TestDaoGiveMVipGift(t *testing.T) {
	convey.Convey("GiveMVipGift", t, func(ctx convey.C) {
		var (
			c       = context.Background()
			mid     = int64(27515308)
			batchId = int(21)
			orderNo = "1" + strconv.Itoa(rand.Int()/100000)
		)
		ctx.Convey("When everything gose positive", func(ctx convey.C) {
			err := d.GiveMVipGift(c, mid, batchId, orderNo)
			ctx.Convey("Then err should be nil.", func(ctx convey.C) {
				ctx.So(err, convey.ShouldBeNil)
			})
		})
	})
}


text:
![Academy Poster](static/img/braggers_logo.png)

One Project For The First Edition Of Axway's Node.js Training

Experimenting with following technologies and APIs:

> LokiJS / React / JSX / Webpack / Babel / Next.js / Fetch / Slack Node SDK / Github Node SDK (Octonode) / Medium Node SDK / Express / Passswordless / Nodemailer / Commander / Draft.js / Octonode / Node.js / Markdown / CSS


text: Grunt plugin to run jetty-runner from grunt; bundles current jetty-runner as well.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>intprim: intprim.basis.polynomial_model.PolynomialModel Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

intprim

Main Page

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

intprim

basis

polynomial_model

PolynomialModel

Public Member Functions |
Public Attributes |
List of all members

intprim.basis.polynomial_model.PolynomialModel Class Reference

The PolynomialModel class implements a basis model consisting of Polynomial basis functions.
 More...

Inheritance diagram for intprim.basis.polynomial_model.PolynomialModel:

  <map id="intprim.basis.polynomial_5Fmodel.PolynomialModel_map" name="intprim.basis.polynomial_model.PolynomialModel_map">
<area href="classintprim_1_1basis_1_1basis__model_1_1BasisModel.html" title="The BasisModel class is a base level class defining general methods that are used by all implemented ..." alt="intprim.basis.basis_model.BasisModel" shape="rect" coords="148,56,434,80"/>
<area href="classintprim_1_1basis_1_1basis__model_1_1BasisModel.html" title="The BasisModel class is a base level class defining general methods that are used by all implemented ..." alt="intprim.basis.basis_model.BasisModel" shape="rect" coords="740,56,1026,80"/>
</map>

Public Member Functions

def 	__init__ (self, degree, observed_dof_names, start_phase=0.0, end_phase=1.01)

 	Initializer method for PolynomialModel.  More...

def 	get_basis_functions (self, x, degree=None)

 	Gets the basis function evaluations for the given phase value(s).  More...

def 	get_basis_function_derivatives (self, x, degree=None)

 	Gets the evaluations for the derivative of the basis functions for the given phase value(s).  More...

def 	__init__ (self, degree, observed_dof_names, start_phase=0.0, end_phase=1.01)

 	Initializer method for PolynomialModel.  More...

def 	get_basis_functions (self, x, degree=None)

 	Gets the basis function evaluations for the given phase value(s).  More...

def 	get_basis_function_derivatives (self, x, degree=None)

 	Gets the evaluations for the derivative of the basis functions for the given phase value(s).  More...

 Public Member Functions inherited from intprim.basis.basis_model.BasisModel

def 	__init__ (self, degree, observed_dof_names)

 	Initialization method for the BasisModel class.  More...

def 	get_block_diagonal_basis_matrix (self, x, out_array=None, start_row=0, start_col=0)

 	Gets the block diagonal basis matrix for the given phase value(s).  More...

def 	get_block_diagonal_basis_matrix_derivative (self, x, out_array=None, start_row=0, start_col=0)

 	Gets the block diagonal basis derivative matrix for the given phase value(s).  More...

def 	get_weighted_vector_derivative (self, x, weights, out_array=None, start_row=0, start_col=0)

 	Gets the weighted vector derivatives corresponding to this basis model for the given basis state.  More...

def 	fit_basis_functions_linear_closed_form (self, x, y)

 	Fits the given trajectory to this basis model via least squares.  More...

def 	apply_coefficients (self, x, coefficients, deriv=False)

 	Applies the given weights to this basis model.  More...

def 	plot (self)

def 	plot_derivative (self)

def 	plot_weighted (self, coefficients, coefficient_names)

def 	observed_to_state_indices (self, observed_indices)

def 	observed_indices_related (self, observed_indices)

def 	__init__ (self, degree, observed_dof_names)

 	Initialization method for the BasisModel class.  More...

def 	get_block_diagonal_basis_matrix (self, x, out_array=None, start_row=0, start_col=0)

 	Gets the block diagonal basis matrix for the given phase value(s).  More...

def 	get_block_diagonal_basis_matrix_derivative (self, x, out_array=None, start_row=0, start_col=0)

 	Gets the block diagonal basis derivative matrix for the given phase value(s).  More...

def 	get_weighted_vector_derivative (self, x, weights, out_array=None, start_row=0, start_col=0)

 	Gets the weighted vector derivatives corresponding to this basis model for the given basis state.  More...

def 	fit_basis_functions_linear_closed_form (self, x, y)

 	Fits the given trajectory to this basis model via least squares.  More...

def 	apply_coefficients (self, x, coefficients, deriv=False)

 	Applies the given weights to this basis model.  More...

def 	plot (self)

def 	plot_derivative (self)

def 	plot_weighted (self, coefficients, coefficient_names)

def 	observed_to_state_indices (self, observed_indices)

def 	observed_indices_related (self, observed_indices)

Public Attributes

 	scale

 Public Attributes inherited from intprim.basis.basis_model.BasisModel

 	observed_dof_names

 	num_observed_dof

 	block_prototype

Detailed Description

The PolynomialModel class implements a basis model consisting of Polynomial basis functions.

Constructor & Destructor Documentation

          def intprim.basis.polynomial_model.PolynomialModel.__init__
          (

          self,

          degree,

          observed_dof_names,

          start_phase = 0.0,

          end_phase = 1.01

          )

Initializer method for PolynomialModel.

Parameters

degree	int The number of Sigmoid basis functions which will be uniformly distributed throughout the space.

observed_dof_names	array-like, shape (num_observed_dof, ). The names of all observed degrees of freedom.

start_phase	float The starting value from which the basis functions are uniformly distributed. The centers are calculated with linspace(start_phase, end_phase, degree).

end_phase	float The ending value from which the basis functions are uniformly distributed. The centers are calculated with linspace(start_phase, end_phase, degree).

          def intprim.basis.polynomial_model.PolynomialModel.__init__
          (

          self,

          degree,

          observed_dof_names,

          start_phase = 0.0,

          end_phase = 1.01

          )

Initializer method for PolynomialModel.

Parameters

degree	int The number of Sigmoid basis functions which will be uniformly distributed throughout the space.

observed_dof_names	array-like, shape (num_observed_dof, ). The names of all observed degrees of freedom.

start_phase	float The starting value from which the basis functions are uniformly distributed. The centers are calculated with linspace(start_phase, end_phase, degree).

end_phase	float The ending value from which the basis functions are uniformly distributed. The centers are calculated with linspace(start_phase, end_phase, degree).

Member Function Documentation

          def intprim.basis.polynomial_model.PolynomialModel.get_basis_function_derivatives
          (

          self,

          x,

          degree = None

          )

Gets the evaluations for the derivative of the basis functions for the given phase value(s).

This is necessary for the computation of the Jacobian matrix in the EKF filter. Unlike get_basis_functions, this function does not (currently) implement a hash map internally and so re-computes values everytime. Since the basis decompositions are simple linear combinations, the partial derivative of the combination with respect to each weight is simply the partial derivative of a single basis function due to the sum rule.

This is the first order partial derivative with respect to x! It is used to compute the Jacobian matrix for filtering linear dynamical systems. Verified using wolfram alpha: d/dx a*(x-(1-x))^0 + b*(x-(1-x))^1 + c*(x-(1-x))^2 and d/dx a*(2x-1)^n

Parameters

x	array-like, shape(num_phase_values, ) or float. If array, a list of phase values for which to compute basis derivative values. Otherwise, a single scalar phase value.

degree	int. Degree of this basis model.

Returns

values array-like, shape(degree, num_phase_values) or array-like, shape(degree, ) if x is a scalar. The evaluated Polynomial basis function derivatives for the given phase value.

          def intprim.basis.polynomial_model.PolynomialModel.get_basis_function_derivatives
          (

          self,

          x,

          degree = None

          )

Gets the evaluations for the derivative of the basis functions for the given phase value(s).

This is necessary for the computation of the Jacobian matrix in the EKF filter. Unlike get_basis_functions, this function does not (currently) implement a hash map internally and so re-computes values everytime. Since the basis decompositions are simple linear combinations, the partial derivative of the combination with respect to each weight is simply the partial derivative of a single basis function due to the sum rule.

This is the first order partial derivative with respect to x! It is used to compute the Jacobian matrix for filtering linear dynamical systems. Verified using wolfram alpha: d/dx a*(x-(1-x))^0 + b*(x-(1-x))^1 + c*(x-(1-x))^2 and d/dx a*(2x-1)^n

Parameters

x	array-like, shape(num_phase_values, ) or float. If array, a list of phase values for which to compute basis derivative values. Otherwise, a single scalar phase value.

degree	int. Degree of this basis model.

Returns

values array-like, shape(degree, num_phase_values) or array-like, shape(degree, ) if x is a scalar. The evaluated Polynomial basis function derivatives for the given phase value.

          def intprim.basis.polynomial_model.PolynomialModel.get_basis_functions
          (

          self,

          x,

          degree = None

          )

Gets the basis function evaluations for the given phase value(s).

Essentially a vectorized wrapper to call get_basis_values for each phase value given.

Parameters

x	array-like, shape(num_phase_values, ) or float. If array, a list of phase values for which to compute basis values. Otherwise, a single scalar phase value.

degree	int. Degree of this basis model.

Returns

array-like, shape(degree, num_phase_values) or array-like, shape(degree, ) if x is a scalar. The evaluated Polynomial basis functions for the given phase value.

          def intprim.basis.polynomial_model.PolynomialModel.get_basis_functions
          (

          self,

          x,

          degree = None

          )

Gets the basis function evaluations for the given phase value(s).

Essentially a vectorized wrapper to call get_basis_values for each phase value given.

Parameters

x	array-like, shape(num_phase_values, ) or float. If array, a list of phase values for which to compute basis values. Otherwise, a single scalar phase value.

degree	int. Degree of this basis model.

Returns

array-like, shape(degree, num_phase_values) or array-like, shape(degree, ) if x is a scalar. The evaluated Polynomial basis functions for the given phase value.

The documentation for this class was generated from the following file:

/home/joe/LibraryPythonPkg/intprim/build/lib.linux-x86_64-2.7/intprim/basis/polynomial_model.py

<address class="footer">
Generated by

 1.8.11
</address>


text:
package waf

const (

	// ErrCodeDisallowedNameException for service response error code
	// "DisallowedNameException".
	//
	// The name specified is invalid.
	ErrCodeDisallowedNameException = "DisallowedNameException"

	// ErrCodeInternalErrorException for service response error code
	// "InternalErrorException".
	//
	// The operation failed because of a system problem, even though the request
	// was valid. Retry your request.
	ErrCodeInternalErrorException = "InternalErrorException"

	// ErrCodeInvalidAccountException for service response error code
	// "InvalidAccountException".
	//
	// The operation failed because you tried to create, update, or delete an object
	// by using an invalid account identifier.
	ErrCodeInvalidAccountException = "InvalidAccountException"

	// ErrCodeInvalidOperationException for service response error code
	// "InvalidOperationException".
	//
	// The operation failed because there was nothing to do. For example:
	//
	//    * You tried to remove a Rule from a WebACL, but the Rule isn't in the
	//    specified WebACL.
	//
	//    * You tried to remove an IP address from an IPSet, but the IP address
	//    isn't in the specified IPSet.
	//
	//    * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple
	//    isn't in the specified WebACL.
	//
	//    * You tried to add a Rule to a WebACL, but the Rule already exists in
	//    the specified WebACL.
	//
	//    * You tried to add an IP address to an IPSet, but the IP address already
	//    exists in the specified IPSet.
	//
	//    * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple
	//    already exists in the specified WebACL.
	ErrCodeInvalidOperationException = "InvalidOperationException"

	// ErrCodeInvalidParameterException for service response error code
	// "InvalidParameterException".
	//
	// The operation failed because AWS WAF didn't recognize a parameter in the
	// request. For example:
	//
	//    * You specified an invalid parameter name.
	//
	//    * You specified an invalid value.
	//
	//    * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL)
	//    using an action other than INSERT or DELETE.
	//
	//    * You tried to create a WebACL with a DefaultActionType other than ALLOW,
	//    BLOCK, or COUNT.
	//
	//    * You tried to create a RateBasedRule with a RateKey value other than
	//    IP.
	//
	//    * You tried to update a WebACL with a WafActionType other than ALLOW,
	//    BLOCK, or COUNT.
	//
	//    * You tried to update a ByteMatchSet with a FieldToMatchType other than
	//    HEADER, METHOD, QUERY_STRING, URI, or BODY.
	//
	//    * You tried to update a ByteMatchSet with a Field of HEADER but no value
	//    for Data.
	//
	//    * Your request references an ARN that is malformed, or corresponds to
	//    a resource with which a web ACL cannot be associated.
	ErrCodeInvalidParameterException = "InvalidParameterException"

	// ErrCodeInvalidRegexPatternException for service response error code
	// "InvalidRegexPatternException".
	//
	// The regular expression (regex) you specified in RegexPatternString is invalid.
	ErrCodeInvalidRegexPatternException = "InvalidRegexPatternException"

	// ErrCodeLimitsExceededException for service response error code
	// "LimitsExceededException".
	//
	// The operation exceeds a resource limit, for example, the maximum number of
	// WebACL objects that you can create for an AWS account. For more information,
	// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html)
	// in the AWS WAF Developer Guide.
	ErrCodeLimitsExceededException = "LimitsExceededException"

	// ErrCodeNonEmptyEntityException for service response error code
	// "NonEmptyEntityException".
	//
	// The operation failed because you tried to delete an object that isn't empty.
	// For example:
	//
	//    * You tried to delete a WebACL that still contains one or more Rule objects.
	//
	//    * You tried to delete a Rule that still contains one or more ByteMatchSet
	//    objects or other predicates.
	//
	//    * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple
	//    objects.
	//
	//    * You tried to delete an IPSet that references one or more IP addresses.
	ErrCodeNonEmptyEntityException = "NonEmptyEntityException"

	// ErrCodeNonexistentContainerException for service response error code
	// "NonexistentContainerException".
	//
	// The operation failed because you tried to add an object to or delete an object
	// from another object that doesn't exist. For example:
	//
	//    * You tried to add a Rule to or delete a Rule from a WebACL that doesn't
	//    exist.
	//
	//    * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule
	//    that doesn't exist.
	//
	//    * You tried to add an IP address to or delete an IP address from an IPSet
	//    that doesn't exist.
	//
	//    * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from
	//    a ByteMatchSet that doesn't exist.
	ErrCodeNonexistentContainerException = "NonexistentContainerException"

	// ErrCodeNonexistentItemException for service response error code
	// "NonexistentItemException".
	//
	// The operation failed because the referenced object doesn't exist.
	ErrCodeNonexistentItemException = "NonexistentItemException"

	// ErrCodeReferencedItemException for service response error code
	// "ReferencedItemException".
	//
	// The operation failed because you tried to delete an object that is still
	// in use. For example:
	//
	//    * You tried to delete a ByteMatchSet that is still referenced by a Rule.
	//
	//    * You tried to delete a Rule that is still referenced by a WebACL.
	ErrCodeReferencedItemException = "ReferencedItemException"

	// ErrCodeStaleDataException for service response error code
	// "StaleDataException".
	//
	// The operation failed because you tried to create, update, or delete an object
	// by using a change token that has already been used.
	ErrCodeStaleDataException = "StaleDataException"
)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Quasar.HabboHotel.Talents
{
    public enum TalentType
    {
        HELPER,
        CITIZENSHIP
    }
}


text:
'''
cdrMethods processes the CDR formula functions in the context of an XBRL DTS and instance.

For description of CDR formula see: http://http://www.ffiec.gov/find/taxonomy/call_report_taxonomy.html

(c) Copyright 2014 Mark V Systems Limited, California US, All rights reserved.
Mark V copyright applies to this software, which is licensed according to the terms of Arelle(r).
'''

from math import exp, fabs, isinf, isnan, log, log10, pow, sqrt
import datetime
from arelle.ModelDtsObject import ModelConcept, ModelRelationship
from arelle.ModelDocument import Type
from arelle.ModelInstanceObject import ModelFact
from arelle.ModelRelationshipSet import ModelRelationshipSet
from arelle.ModelValue import QName, dayTimeDuration, DayTimeDuration
from arelle.ModelXbrl import ModelXbrl
from arelle.ValidateXbrlCalcs import inferredDecimals, inferredPrecision, roundValue
from arelle import XbrlConst, XmlUtil
evaluate = None # initialized at end
CdrException = None
UNBOUND = None
NONE = None

def moduleInit():
    global evaluate, CdrException, UNBOUND, NONE
    from .cdrEvaluator import evaluate, CdrException, UNBOUND, NONE

class Balance(): # fake class for balance type
    pass

class PeriodType(): # fake class for period type
    pass

class Period():
    def __init__(self, start=None, end=None):
        self.start = start
        self.end = end
    @property
    def isForever(self):
        return self.start is None and self.end is None
    @property
    def isInstant(self):
        return self.start is None and self.end is not None
    @property
    def isStartEnd(self):
        return self.start is not None and self.end is not None
    def __repr__(self):
        return "({0},{1})".format(self.start, self.end)
    def __eq__(self, other):
        if isinstance(other, Period):
            return self.start == other.start and self.end == other.end
        return False
    def __ne__(self, other):
        if isinstance(other, Period):
            return self.start != other.start or self.end != other.end
        return False
    def __lt__(self, other):
        if not isinstance(other, Period):
            return False
        if self.isInstant:
            if other.isInstant:
                return self.end < other.end
            elif other.isStartEnd:
                return self.end <= other.start
        elif self.isStartEnd:
            if other.isInstant:
                return self.end < other.end
            elif other.isStartEnd:
                return self.end <= other.start
        return False
    def __le__(self, other):
        if not isinstance(other, Period):
            return False
        if self.isInstant:
            if other.isInstant:
                return self.end <= other.end
            elif other.isStartEnd:
                return self.end <= other.start or self == other
        elif self.isStartEnd:
            if other.isInstant:
                return self.end <= other.end
            elif other.isStartEnd:
                return self.end <= other.start or self == other
        return False
    def __gt__(self, other):
        if not isinstance(other, Period):
            return False
        if self.isInstant:
            if other.isInstant:
                return self.end > other.end
            elif other.isStartEnd:
                return self.start > other.end
        elif self.isStartEnd:
            if other.isInstant:
                return self.end > other.end
            elif other.isStartEnd:
                return self.start > other.end
        return False
    def __ge__(self, other):
        if not isinstance(other, Period):
            return False
        if self.isInstant:
            if other.isInstant:
                return self.end >= other.end
            elif other.isStartEnd:
                return self.start >= other.start or self == other
        elif self.isStartEnd:
            if other.isInstant:
                return self.end >= other.end
            elif other.isStartEnd:
                return self.start >= other.start or self == other
        return False

def hasArg(node, cdrContext, args, i):
    if i >= len(args):
        raise CdrException(node, "sphinx.functionArgumentsMismatch",
                              _("Function %(name)s requires %(required)s parameters but %(provided)s are provided"),
                                name=node.name, required=i, provided=len(node.args))

def numericArg(node, cdrContext, args, i):
    hasArg(node, cdrContext, args, i)
    arg = args[i]
    if isinstance(arg, _NUM_TYPES):
        return arg
    raise CdrException(node, "sphinx.functionArgumentsMismatch",
                          _("Function %(name)s numeric parameter %(num)s is not a number: %(value)s"),
                          name=node.name, num=i, value=arg)

def numericArgs(node, cdrContext, args, expectedArgsLen):
    if expectedArgsLen != len(args):
        raise CdrException(node, "sphinx.functionArgumentsMismatch",
                              _("Function %(name)s requires %(required)s parameters but %(provided)s are provided"),
                              name=node.name, required=expectedArgsLen, provided=len(args))
    numArgs = []
    for i, arg in enumerate(args):
        if i >= expectedArgsLen:
            break
        value = evaluate(arg, cdrContext, args, value=True)
        if not isinstance(value, _NUM_TYPES):
            raise CdrException(node, "sphinx.functionArgumentsMismatch",
                                  _("Function %(name)s numeric parameters but %(num)s is not numeric: %(value)s"),
                                  num=i, value=value)
            value = 0
        numArgs.append(value)
    for i in range(i, expectedArgsLen):
        numArgs.append(0)
    return numArgs

def strArg(node, cdrContext, args, i):
    hasArg(node, cdrContext, args, i)
    arg = args[i]
    if isinstance(arg, str):
        return arg
    raise CdrException(node, "sphinx.functionArgumentsMismatch",
                          _("Function %(name)s string parameter %(num)s is not a string: %(value)s"),
                          name=node.name, num=i, value=arg)

def strArgs(node, cdrContext, args, expectedArgsLen):
    if expectedArgsLen != len(args):
        raise CdrException(node, "sphinx.functionArgumentsMismatch",
                              _("Function %(name)s requires %(required)s parameters but %(provided)s are provided"),
                              name=node.name, required=expectedArgsLen, provided=len(args))
    strArgs = []
    for i, arg in enumerate(args):
        if i >= expectedArgsLen:
            break
        value = evaluate(arg, cdrContext, value=True)
        if not isinstance(value, _STR_BASE):
            raise CdrException(node, "sphinx.functionArgumentsMismatch",
                                  _("Function %(name)s string parameters but %(num)s is not numeric: %(value)s"),
                                  name=node.name, num=i, value=value)
            value = 0
        strArgs.append(value)
    for i in range(i, expectedArgsLen):
        strArgs.append(0)
    return strArgs

def datetimeArg(node, cdrContext, args, i):
    hasArg(node, cdrContext, args, i)
    arg = args[i]
    if isinstance(arg, datetime.datetime):
        return arg
    raise CdrException(node, "sphinx.functionArgumentsMismatch",
                          _("Function %(name)s datetime parameter %(num)s is not a datetime: %(value)s"),
                          name=node.name, num=i, value=arg)

def factArg(node, cdrContext, args, i):
    hasArg(node, cdrContext, args, i)
    fact = evaluate(args[i], cdrContext, value=False, hsBoundFact=True)
    if isinstance(fact, ModelFact):
        return fact
    raise CdrException(node, "sphinx.functionArgumentsMismatch",
                          _("Function %(name)s fact parameter %(num)s is not a fact: %(value)s"),
                          name=node.name,
                          num=i, value=fact)

# numeric functions
NaN = float("NaN")
POSINF = float("INF")
NEGINF = float("-INF")

def _abs(node, cdrContext, args):
    args = numericArgs(node, cdrContext, args, 1)
    return fabs(args[0])

def _avg(node, cdrContext, args):
    sum = 0
    for i in len(args):
        sum += numericArgs(node, cdrContext, args, i)
    if len(args) > 0:
        return sum / len(args)
    return 0

def _concatenate(node, cdrContext, args):
    value1 = strArgs(node, cdrContext, args, 0)
    value2 = strArgs(node, cdrContext, args, 1)
    return value1 + value2

def _contextPeriodType(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    context = fact.context
    if context is not None:
        if context.isInstantPeriod:
            return "Instant"
        elif context.isStartEndPeriod:
            return "Duration"
        else:
            return "Forever"
    return None

def _contextPeriodEndDate(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    context = fact.context
    if context is not None:
        #return XmlUtil.dateunionValue(context.endDatetime, subtractOneDay=True)
        return context.endDatetime
    return None

def _contextPeriodStartDate(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    context = fact.context
    if context is not None:
        #return XmlUtil.dateunionValue(context.startDatetime)
        return context.startDatetime
    return None

def _currnetPeriodEndDate(node, cdrContext, args):
    hasArg(node, cdrContext, args, 0)
    arg = args[0]
    if isinstance(arg, Period):
        if arg.isForever:
            return UNBOUND
        return arg.end
    raise CdrException(node, "cdrFormula.functionArgumentsMismatch",
                          _("Function %(name)s argument is not a period %(value)s"),
                          name=node.name, value=arg)

def _date(node, cdrContext, args):
    year = numericArg(node, cdrContext, args, 0)
    month = numericArg(node, cdrContext, args, 1)
    day = numericArg(node, cdrContext, args, 2)
    return datetime.datetime(year, month, day)

def _dateToString(node, cdrContext, args):
    value = datetimeArg(node, cdrContext, args, 0)
    fmt = strArg(node, cdrContext, args, 1)
    pyFmt = fmt.replace("yyyy", "%Y").replace('yy', "%y") \
               .replace("MM", "%m") \
               .replace("DD", "%d")
    return value.strftime(pyFmt)

def _dateValue(node, cdrContext, args):
    value = datetimeArg(node, cdrContext, args, 0)
    return (value - datetime.datetime(1899,12,30)).days # produces same number as excel

def _dayOf(node, cdrContext, args):
    value = datetimeArg(node, cdrContext, args, 0)
    return value.day

def _exists(node, cdrContext, args):
    hasArg(node, cdrContext, args, 0)
    fact = evaluate(args[0], cdrContext, value=False, hsBoundFact=True)
    if isinstance(fact, ModelFact):
        return True
    return False

def _existsNonNil(node, cdrContext, args):
    hasArg(node, cdrContext, args, 0)
    fact = evaluate(args[0], cdrContext, value=False, hsBoundFact=True)
    if isinstance(fact, ModelFact) and not fact.isNil:
        return True
    return False

def _exact(node, cdrContext, args):
    value1 = strArgs(node, cdrContext, args, 0)
    value2 = strArgs(node, cdrContext, args, 1)
    return value1 == value2

def _existsNonEmpty(node, cdrContext, args):
    hasArg(node, cdrContext, args, 0)
    fact = evaluate(args[0], cdrContext, value=False, hsBoundFact=True)
    if isinstance(fact, ModelFact) and not fact.isNil and fact.xValue:
        return True
    return False

def _existingOf(node, cdrContext, args):
    for arg in args:
        fact = evaluate(arg, cdrContext, value=False, hsBoundFact=True)
        if isinstance(fact, ModelFact):
            return fact
    return None

def _false(node, cdrContext, args):
    return False

def _if(node, cdrContext, args):
    test = numericArgs(node, cdrContext, args, 0)
    if test:
        return args[1]
    else:
        return args[2]

def _int(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    if fact is not None:
        return int(float(fact.xValue))
    return 0

def _left(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    len = numericArg(node, cdrContext, args, 1)
    return value[0:len]

def _len(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    return len(value)

def _lower(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    return value.lower()

def _max(node, cdrContext, args):
    value1 = numericArg(node, cdrContext, args, 0)
    value2 = numericArg(node, cdrContext, args, 1)
    return max(value1, value2)

def _mid(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    start = numericArg(node, cdrContext, args, 1)
    len = numericArg(node, cdrContext, args, 2)
    return value[start:start+len]

def _min(node, cdrContext, args):
    value1 = numericArg(node, cdrContext, args, 0)
    value2 = numericArg(node, cdrContext, args, 1)
    return min(value1, value2)

def _monthOf(node, cdrContext, args):
    value = datetimeArg(node, cdrContext, args, 0)
    return value.month

def _not(node, cdrContext, args):
    test = numericArgs(node, cdrContext, args, 0)
    return args[1] if test else args[2]

def _power(node, cdrContext, args):
    number = numericArg(node, cdrContext, args, 0)
    power = numericArg(node, cdrContext, args, 1)
    return pow(number,power)

def _proper(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    return value.title()

def _right(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    len = numericArg(node, cdrContext, args, 1)
    return value[-len:]

def _round(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    decimals = numericArg(node, cdrContext, args, 1)
    if fact is not None:
        return round(fact.xValue, decimals)
    return 0

def _replace(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    start = numericArg(node, cdrContext, args, 1)
    numChars = numericArg(node, cdrContext, args, 2)
    new = strArgs(node, cdrContext, args, 3)
    return value[0:start-1] + new + value[start + numChars - 1:]

def _search(node, cdrContext, args):
    pattern = strArgs(node, cdrContext, args, 0).lower()
    value = strArgs(node, cdrContext, args, 1).lower()
    return value.find(pattern)

def _sign(node, cdrContext, args):
    value = numericArg(node, cdrContext, args, 0)
    if value < 0:
        return -1
    return 1

def _sqrt(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    if fact is not None:
        return sqrt(fact.xValue)
    return 0

def _substitute(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    old = strArgs(node, cdrContext, args, 1)
    new = strArgs(node, cdrContext, args, 2)
    if len(args) > 3:
        instanceNum = numericArg(node, cdrContext, args, 3)
        start = 0
        for i in range(1, instanceNum):
            start = value.find(old, start)
            if start >= 0:
                if instanceNum == i:
                    return value[0:start] + new + value[start + len(old):]
                else:
                    start += len(old)
    return value

def _trim(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    return value.strip()

def _true(node, cdrContext, args):
    return True

def _truncate(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    if len(args) > 1:
        digits = numericArg(node, cdrContext, args, 1)
    else:
        digits = 0
    if fact is not None:
        v = fact.value
        if digits == 0:
            return int(v)
        return v - v % (10 ** -digits)
    return 0

def _upper(node, cdrContext, args):
    value = strArgs(node, cdrContext, args, 0)
    return value.upper()

def _value(node, cdrContext, args):
    fact = factArg(node, cdrContext, args, 0)
    if fact is not None:
        return float(fact.xValue)
    return 0

def _yearOf(node, cdrContext, args):
    value = datetimeArg(node, cdrContext, args, 0)
    return value.year

# miscellaneous methods

def _notImplemented(node, cdrContext, args):
    cdrContext.modelXbrl.log("ERROR", "cdrFormula.functionNotImplemented",
                                _("Function %(name)s is not currently implemented"),
                                sourceFileLine=node.sourceFileLine,
                                name=node.name)
    return NaN

functionImplementation = {
    "if":             _if,
    "not":            _not,
    "true":           _true,
    "false":          _false,

    "exists":         _exists,
    "existsnonnil":   _existsNonNil,
    "existsnonempty": _existsNonEmpty,
    "existingof":     _existingOf,
    "context.period.type":      _contextPeriodType,
    "context.period.startdate": _contextPeriodStartDate,
    "context.period.enddate":   _contextPeriodEndDate,

    "yearof":         _yearOf,
    "monthof":        _monthOf,
    "dayof":          _dayOf,
    "datetostring":   _dateToString,
    "datevalue":      _dateValue,
    "date":           _date,

    "abs":            _abs,
    "round":          _round,
    "truncate":       _truncate,
    "trunc":          _truncate,
    "int":            _int,
    "sqrt":           _sqrt,
    "min":            _min,
    "max":            _max,
    "sign":           _sign,
    "power":          _power,
    "avg":            _avg,

    "len":            _len,
    "left":           _left,
    "right":          _right,
    "concatenate":    _concatenate,
    "mid":            _mid,
    "trim":           _trim,
    "replace":        _replace,
    "substitute":     _substitute,
    "search":         _search,
    "exact":          _exact,
    "upper":          _upper,
    "lower":          _lower,
    "proper":         _proper,
    "value":          _value,

    }